repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/register_array.rs | sw-emulator/lib/bus/src/register_array.rs | // Licensed under the Apache-2.0 license
use std::{
marker::PhantomData,
ops::{Index, IndexMut},
};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use tock_registers::{LocalRegisterCopy, RegisterLongName, UIntLike};
use crate::{Bus, BusError, Register};
pub trait RegisterArray {
const ITEM_SIZE: usize;
const LEN: usize;
}
impl<const LEN: usize, T: Register> RegisterArray for [T; LEN] {
const ITEM_SIZE: usize = T::SIZE;
const LEN: usize = LEN;
}
pub struct ReadWriteRegisterArray<
T: Copy + UIntLike + Into<RvData> + TryFrom<RvData>,
const SIZE: usize,
R: RegisterLongName = (),
> {
regs: [LocalRegisterCopy<T, R>; SIZE],
associated_register: PhantomData<R>,
}
impl<
T: UIntLike + Into<RvData> + TryFrom<RvData>,
const SIZE: usize,
R: Copy + RegisterLongName,
> ReadWriteRegisterArray<T, SIZE, R>
{
pub fn new(default_value: T) -> Self {
Self {
regs: [LocalRegisterCopy::new(default_value); SIZE],
associated_register: PhantomData,
}
}
}
impl<T: UIntLike + Into<RvData> + TryFrom<RvData>, const SIZE: usize, R: RegisterLongName>
ReadWriteRegisterArray<T, SIZE, R>
{
pub fn iter(&self) -> impl Iterator<Item = &LocalRegisterCopy<T, R>> {
self.regs.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut LocalRegisterCopy<T, R>> {
self.regs.iter_mut()
}
}
impl<T: UIntLike + Into<RvData> + TryFrom<RvData>, const SIZE: usize, R: RegisterLongName>
Index<usize> for ReadWriteRegisterArray<T, SIZE, R>
{
type Output = LocalRegisterCopy<T, R>;
fn index(&self, index: usize) -> &Self::Output {
&self.regs[index]
}
}
impl<T: UIntLike + Into<RvData> + TryFrom<RvData>, const SIZE: usize, R: RegisterLongName>
IndexMut<usize> for ReadWriteRegisterArray<T, SIZE, R>
{
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.regs[index]
}
}
impl<T: UIntLike + Into<RvData> + TryFrom<RvData>, const SIZE: usize, R: RegisterLongName>
RegisterArray for ReadWriteRegisterArray<T, SIZE, R>
{
const ITEM_SIZE: usize = std::mem::size_of::<T>();
const LEN: usize = SIZE;
}
impl<T: UIntLike + Into<RvData> + TryFrom<RvData>, const SIZE: usize, R: RegisterLongName> Bus
for ReadWriteRegisterArray<T, SIZE, R>
{
fn read(&mut self, _size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
if addr as usize % std::mem::size_of::<T>() != 0 {
return Err(BusError::LoadAddrMisaligned);
}
// TODO: Check size?
let i = addr as usize / std::mem::size_of::<T>();
Ok((*self.regs.get(i).ok_or(BusError::LoadAccessFault)?)
.get()
.into())
}
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
if usize::from(size) != std::mem::size_of::<T>() {
return Err(BusError::StoreAccessFault);
}
if addr as usize % std::mem::size_of::<T>() != 0 {
return Err(BusError::StoreAddrMisaligned);
}
let i = addr as usize / std::mem::size_of::<T>();
self.regs
.get_mut(i)
.ok_or(BusError::StoreAccessFault)?
.set(T::try_from(val).map_err(|_| BusError::StoreAccessFault)?);
Ok(())
}
}
#[cfg(test)]
mod tests {
use tock_registers::register_bitfields;
use super::*;
register_bitfields! [
u32,
Meipl [
PRIORITY OFFSET(0) NUMBITS(4) [],
],
];
register_bitfields! [
u16,
Meipl16 [
PRIORITY OFFSET(0) NUMBITS(4) [],
],
];
#[test]
fn test_read_and_write() {
let mut array: ReadWriteRegisterArray<u32, 32, Meipl::Register> =
ReadWriteRegisterArray::new(0x40);
assert_eq!(0, array[0].read(Meipl::PRIORITY));
assert_eq!(0x40, array[0].get());
assert_eq!(0x40, Bus::read(&mut array, RvSize::Word, 0).unwrap());
array[0].write(Meipl::PRIORITY.val(0xa));
assert_eq!(0x0a, array[0].read(Meipl::PRIORITY));
assert_eq!(0x0a, array[0].get());
assert_eq!(0x0a, Bus::read(&mut array, RvSize::Word, 0).unwrap());
array[1].modify(Meipl::PRIORITY.val(5));
assert_eq!(0x05, array[1].read(Meipl::PRIORITY));
assert_eq!(0x45, Bus::read(&mut array, RvSize::Word, 4).unwrap());
Bus::write(&mut array, RvSize::Word, 31 * 4, 0x2e).unwrap();
assert_eq!(0x2e, Bus::read(&mut array, RvSize::Word, 31 * 4).unwrap());
assert_eq!(0x0e, array[31].read(Meipl::PRIORITY));
assert_eq!(
vec![
0x0a, 0x45, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x2e
],
array.iter().map(|a| a.get()).collect::<Vec<_>>()
);
}
#[test]
fn test_bus_faults() {
let mut array: ReadWriteRegisterArray<u32, 32, Meipl::Register> =
ReadWriteRegisterArray::new(0x00);
assert_eq!(
Bus::read(&mut array, RvSize::Word, 32 * 4),
Err(BusError::LoadAccessFault)
);
assert_eq!(
Bus::write(&mut array, RvSize::Word, 32 * 4, 0),
Err(BusError::StoreAccessFault)
);
assert_eq!(
Bus::read(&mut array, RvSize::Word, 1),
Err(BusError::LoadAddrMisaligned)
);
assert_eq!(
Bus::write(&mut array, RvSize::Word, 1, 0),
Err(BusError::StoreAddrMisaligned)
);
assert_eq!(
Bus::write(&mut array, RvSize::HalfWord, 0, 0),
Err(BusError::StoreAccessFault)
);
}
#[test]
fn test_read_and_write_16bit() {
let mut array: ReadWriteRegisterArray<u16, 32, Meipl16::Register> =
ReadWriteRegisterArray::new(0x40);
assert_eq!(0, array[0].read(Meipl16::PRIORITY));
assert_eq!(0x40, array[0].get());
assert_eq!(0x40, Bus::read(&mut array, RvSize::HalfWord, 0).unwrap());
array[0].write(Meipl16::PRIORITY.val(0xa));
assert_eq!(0x0a, array[0].read(Meipl16::PRIORITY));
assert_eq!(0x0a, array[0].get());
assert_eq!(0x0a, Bus::read(&mut array, RvSize::HalfWord, 0).unwrap());
array[1].modify(Meipl16::PRIORITY.val(5));
assert_eq!(0x05, array[1].read(Meipl16::PRIORITY));
assert_eq!(0x45, Bus::read(&mut array, RvSize::HalfWord, 2).unwrap());
Bus::write(&mut array, RvSize::HalfWord, 31 * 2, 0x2e).unwrap();
assert_eq!(
0x2e,
Bus::read(&mut array, RvSize::HalfWord, 31 * 2).unwrap()
);
assert_eq!(0x0e, array[31].read(Meipl16::PRIORITY));
assert_eq!(
vec![
0x0a, 0x45, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x2e
],
array.iter().map(|a| a.get()).collect::<Vec<_>>()
);
}
#[test]
fn test_bus_faults_16bit() {
let mut array: ReadWriteRegisterArray<u16, 32, Meipl16::Register> =
ReadWriteRegisterArray::new(0x00);
assert_eq!(
Bus::read(&mut array, RvSize::HalfWord, 32 * 2),
Err(BusError::LoadAccessFault)
);
assert_eq!(
Bus::write(&mut array, RvSize::HalfWord, 32 * 2, 0),
Err(BusError::StoreAccessFault)
);
assert_eq!(
Bus::read(&mut array, RvSize::HalfWord, 1),
Err(BusError::LoadAddrMisaligned)
);
assert_eq!(
Bus::write(&mut array, RvSize::HalfWord, 1, 0),
Err(BusError::StoreAddrMisaligned)
);
assert_eq!(
Bus::write(&mut array, RvSize::Word, 0, 0),
Err(BusError::StoreAccessFault)
);
assert_eq!(
Bus::write(&mut array, RvSize::Byte, 0, 0),
Err(BusError::StoreAccessFault)
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/dynamic_bus.rs | sw-emulator/lib/bus/src/dynamic_bus.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
dynamic_bus.rs
Abstract:
File contains DynamicBus type.
--*/
use std::{io::ErrorKind, ops::RangeInclusive};
use crate::{Bus, BusError};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
struct MappedDevice {
name: String,
mmap_range: RangeInclusive<RvAddr>,
bus: Box<dyn Bus>,
}
/// A bus that uses dynamic-dispatch to delegate to a runtime-modifiable list of
/// devices. Useful as a quick-and-dirty Bus implementation.
#[derive(Default)]
pub struct DynamicBus {
/// Devices connected to the CPU
devs: Vec<MappedDevice>,
}
impl DynamicBus {
pub fn new() -> DynamicBus {
Self::default()
}
/// Attach the specified device to the CPU
///
/// # Arguments
///
/// * `dev` - Device to attach
pub fn attach_dev(
&mut self,
name: &str,
mmap_range: RangeInclusive<RvAddr>,
bus: Box<dyn Bus>,
) -> std::io::Result<()> {
let dev = MappedDevice {
name: name.into(),
mmap_range,
bus,
};
let dev_addr = dev.mmap_range.clone();
let mut index = 0;
for cur_dev in self.devs.iter() {
let cur_dev_addr = cur_dev.mmap_range.clone();
// Check if the device range overlaps existing device
if dev_addr.end() >= cur_dev_addr.start() && dev_addr.start() <= cur_dev_addr.end() {
return Err(std::io::Error::new(
ErrorKind::AddrInUse,
format!("Address space for device {} ({:#010x}-{:#010x}) collides with device {} ({:#010x}-{:#010x})",
dev.name, dev.mmap_range.start(), dev.mmap_range.end(),
cur_dev.name, cur_dev.mmap_range.start(), cur_dev.mmap_range.end())));
}
// Found the position to insert the device
if dev_addr.start() < cur_dev_addr.start() {
break;
}
index += 1;
}
self.devs.insert(index, dev);
Ok(())
}
}
impl Bus for DynamicBus {
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
let dev = self.devs.iter_mut().find(|d| d.mmap_range.contains(&addr));
match dev {
Some(dev) => dev.bus.read(size, addr - dev.mmap_range.start()),
None => Err(BusError::LoadAccessFault),
}
}
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
let dev = self.devs.iter_mut().find(|d| d.mmap_range.contains(&addr));
match dev {
Some(dev) => dev.bus.write(size, addr - dev.mmap_range.start(), val),
None => Err(BusError::StoreAccessFault),
}
}
fn poll(&mut self) {
for dev in self.devs.iter_mut() {
dev.bus.poll();
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{testing::FakeBus, BusError, Ram, Rom};
use caliptra_emu_types::RvSize;
#[test]
fn test_dynamic_bus_read() {
let mut bus = DynamicBus::new();
let rom = Rom::new(vec![1, 2]);
bus.attach_dev("ROM0", 1..=2, Box::new(rom)).unwrap();
assert_eq!(bus.read(RvSize::Byte, 1).ok(), Some(1));
assert_eq!(bus.read(RvSize::Byte, 2).ok(), Some(2));
assert_eq!(
bus.read(RvSize::Byte, 3).err(),
Some(BusError::LoadAccessFault),
);
}
#[test]
fn test_dynamic_bus_write() {
let mut bus = DynamicBus::new();
let rom = Ram::new(vec![1, 2]);
bus.attach_dev("RAM0", 1..=2, Box::new(rom)).unwrap();
assert_eq!(bus.write(RvSize::Byte, 1, 3).ok(), Some(()));
assert_eq!(bus.read(RvSize::Byte, 1).ok(), Some(3));
assert_eq!(bus.write(RvSize::Byte, 2, 4).ok(), Some(()));
assert_eq!(bus.read(RvSize::Byte, 2).ok(), Some(4));
assert_eq!(
bus.write(RvSize::Byte, 3, 0).err(),
Some(BusError::StoreAccessFault),
);
}
#[test]
fn test_dynamic_bus_poll() {
let mut dynamic_bus = DynamicBus::new();
let fake_bus0 = Box::new(FakeBus::new());
let log0 = fake_bus0.log.clone();
dynamic_bus
.attach_dev("fake_bus0", 0..=0xffff, fake_bus0)
.unwrap();
let fake_bus1 = Box::new(FakeBus::new());
let log1 = fake_bus1.log.clone();
dynamic_bus
.attach_dev("fake_bus1", 0x1_0000..=0x1_ffff, fake_bus1)
.unwrap();
assert_eq!("", log0.take());
assert_eq!("", log1.take());
dynamic_bus.poll();
assert_eq!("poll()\n", log0.take());
assert_eq!("poll()\n", log1.take());
}
fn is_sorted<T>(slice: &[T]) -> bool
where
T: Ord,
{
slice.windows(2).all(|s| s[0] <= s[1])
}
#[test]
fn test_attach_dev() {
let mut bus = DynamicBus::new();
let rom = Rom::new(vec![1, 2]);
// Attach valid devices
bus.attach_dev("ROM0", 1..=2, Box::new(rom)).unwrap();
let rom = Rom::new(vec![1]);
bus.attach_dev("ROM1", 0..=0, Box::new(rom)).unwrap();
let rom = Rom::new(vec![1]);
bus.attach_dev("ROM2", 3..=3, Box::new(rom)).unwrap();
// Try inserting devices whose address maps overlap existing devices
let rom = Rom::new(vec![1]);
let err = bus.attach_dev("ROM3", 1..=1, Box::new(rom)).err().unwrap();
assert_eq!(err.to_string(), "Address space for device ROM3 (0x00000001-0x00000001) collides with device ROM0 (0x00000001-0x00000002)");
let rom = Rom::new(vec![1]);
let err = bus.attach_dev("ROM4", 2..=2, Box::new(rom)).err().unwrap();
assert_eq!(err.to_string(), "Address space for device ROM4 (0x00000002-0x00000002) collides with device ROM0 (0x00000001-0x00000002)");
let addrs: Vec<RvAddr> = bus
.devs
.iter()
.flat_map(|d| [*d.mmap_range.start(), *d.mmap_range.end()])
.collect();
assert_eq!(addrs.len(), 6);
assert!(is_sorted(&addrs));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/clock.rs | sw-emulator/lib/bus/src/clock.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
clock.rs
Abstract:
File contains Clock and Timer types, used to implement timer-based deferred
execution for peripherals.
--*/
use crate::Bus;
use std::{
collections::{BTreeSet, HashSet},
ptr,
sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex, RwLock,
},
};
/// Peripherals that want to use timer-based deferred execution will typically
/// store a clone of Timer inside themselves, and use it to schedule future
/// notification via [`Bus::poll`]).
///
/// # Example
///
/// ```
/// use caliptra_emu_bus::{Bus, BusError, Timer, ActionHandle};
/// use caliptra_emu_types::{RvAddr, RvData, RvSize};
/// struct MyPeriph {
/// timer: Timer,
/// action0: Option<ActionHandle>,
/// }
/// impl Bus for MyPeriph {
/// fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
/// Ok(0)
/// }
/// fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
/// // If a timer action was previously scheduled, cancel it
/// if let Some(action0) = self.action0.take() {
/// self.timer.cancel(action0);
/// }
/// // Request that Bus::poll be called in 1000 clock cycles, storing
/// // a reference to the timer action in self.action0.
/// self.action0 = Some(self.timer.schedule_poll_in(1000));
/// Ok(())
/// }
/// fn poll(&mut self) {
/// if self.timer.fired(&mut self.action0) {
/// println!("It is 1000 clock cyles after the last write to MyPeriph.")
/// }
/// }
/// }
/// ```
#[derive(Clone)]
pub struct Timer {
clock: Arc<ClockImpl>,
}
impl Timer {
/// Constructs a new timer bound to the specified clock.
pub fn new(clock: &Clock) -> Self {
Self {
clock: Arc::clone(&clock.clock),
}
}
/// Returns the current time: the number of clock cycles that have elapsed
/// since simulation start.
#[inline]
pub fn now(&self) -> u64 {
self.clock.now()
}
/// If the scheduled time for `action` has come, `action` will be set to
/// None and the function will return true. Otherwise (or if action is None),
/// the function will return false.
pub fn fired(&self, action: &mut Option<ActionHandle>) -> bool {
let has_fired = if let Some(ref action) = action {
debug_assert_eq!(
action.0.id.timer_ptr,
Arc::as_ptr(&self.clock),
"Supplied action was not created by this timer."
);
self.clock.has_fired(action.0.time)
} else {
false
};
if has_fired {
*action = None;
}
has_fired
}
/// Schedules a future call to [`Bus::poll()`] at `time`, and returns a
/// `ActionHandle` that can be used with [`Timer::cancel`] or
/// [`Timer::fired`].
pub fn schedule_poll_at(&self, time: u64) -> ActionHandle {
self.clock.schedule_action_at(time, TimerAction::Poll)
}
/// Schedules a future call to [`Bus::poll()`] at `self.now() + time`, and
/// returns a `ActionHandle` that can be used with [`Timer::cancel`] or
/// [`Timer::fired`].
pub fn schedule_poll_in(&self, ticks_from_now: u64) -> ActionHandle {
self.schedule_poll_at(self.now().wrapping_add(ticks_from_now))
}
/// Schedules an action at `self.now() + time`, and returns an `ActionHandle`
/// that can be used with [`Timer::cancel`] or [`Timer::fired`].
pub fn schedule_action_in(&self, ticks_from_now: u64, reset_type: TimerAction) -> ActionHandle {
self.clock
.schedule_action_at(self.now().wrapping_add(ticks_from_now), reset_type)
}
/// Cancels a previously scheduled poll action.
///
/// * Panics
///
/// Panics if the supplied `ActionHandle` was not created by this Timer.
pub fn cancel(&self, handle: ActionHandle) {
self.clock.cancel(handle)
}
}
pub struct Clock {
clock: Arc<ClockImpl>,
}
impl Default for Clock {
fn default() -> Self {
Self::new()
}
}
impl Clock {
/// Constructs a new Clock with the cycle counter set to 0.
pub fn new() -> Clock {
Self {
clock: ClockImpl::new(),
}
}
/// Constructs a `Timer` associated with this clock.
pub fn timer(&self) -> Timer {
Timer::new(self)
}
/// Returns the number of simulated clock cycles that have elapsed since
/// simulation start.
#[inline]
pub fn now(&self) -> u64 {
self.clock.now()
}
/// Increments the clock by `delta`, and returns a list of timer
/// actions fired.
#[inline]
pub fn increment(&self, delta: u64) -> HashSet<TimerAction> {
self.clock.increment(delta)
}
/// Increments the clock by `delta`, and polls the bus if any scheduled
/// timer actions fired.
#[inline]
pub fn increment_and_process_timer_actions(
&self,
delta: u64,
bus: &mut impl Bus,
) -> HashSet<TimerAction> {
let fired_actions = self.increment(delta);
for action in fired_actions.iter() {
match action {
TimerAction::Poll => bus.poll(),
TimerAction::WarmReset => {
bus.warm_reset();
break;
}
TimerAction::UpdateReset => {
bus.update_reset();
break;
}
TimerAction::Nmi { .. }
| TimerAction::SetNmiVec { .. }
| TimerAction::ExtInt { .. }
| TimerAction::SetExtIntVec { .. }
| TimerAction::SetGlobalIntEn { .. }
| TimerAction::SetExtIntEn { .. }
| TimerAction::InternalTimerLocalInterrupt { .. }
| TimerAction::MachineTimerInterrupt { .. }
| TimerAction::Halt => {}
}
}
fired_actions
}
}
/// Represents an action scheduled with a `Timer`. Returned by
/// [`Timer::schedule_poll_at`] and passed to [`Timer::has_fired()`] or
/// [`Timer::cancel`].
pub struct ActionHandle(ActionHandleImpl);
impl From<ActionHandleImpl> for ActionHandle {
fn from(val: ActionHandleImpl) -> Self {
ActionHandle(val)
}
}
/// The internal representation of `ActionHandle`. We keep these types separate
/// to avoid exposing these implementation-specific traits.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
struct ActionHandleImpl {
/// The time the action is supposed to fire.
time: u64,
id: TimerActionId,
action: TimerAction,
}
impl From<ActionHandle> for ActionHandleImpl {
fn from(val: ActionHandle) -> Self {
val.0
}
}
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
struct TimerActionId {
/// Pointer to the TimerImpl that this action is scheduled on. This pointer
/// is used for identification purposes only; it prevents ActionIds from one
/// Timer from being mixed up with another Timer.
timer_ptr: *const ClockImpl,
/// An ID assigned by the TimerImpl
id: u64,
}
/// Safety: the *const ClockImpl is Send safe because it is only used for comparisons.
unsafe impl Send for TimerActionId {}
/// Safety: the *const ClockImpl is Sync safe because it is only used for comparisons.
unsafe impl Sync for TimerActionId {}
impl Default for TimerActionId {
fn default() -> Self {
Self {
timer_ptr: ptr::null(),
id: 0,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum TimerAction {
Poll,
WarmReset,
UpdateReset,
Nmi {
mcause: u32,
},
SetNmiVec {
addr: u32,
},
ExtInt {
irq: u8,
can_wake: bool,
},
SetExtIntVec {
addr: u32,
},
SetGlobalIntEn {
en: bool,
},
SetExtIntEn {
en: bool,
},
InternalTimerLocalInterrupt {
timer_id: u8,
},
Halt,
/// Assert the machine timer interrupt (mip.MTIP = 1).
MachineTimerInterrupt, //
}
impl TimerAction {
/// Sort priority based on VeeR EL2 Programmer's Reference Manual Table 14.1.
pub fn priority(&self) -> isize {
match self {
TimerAction::Poll => 0,
TimerAction::Halt => 1,
TimerAction::SetExtIntVec { .. } => 2,
TimerAction::SetNmiVec { .. } => 3,
TimerAction::SetGlobalIntEn { .. } => 4,
TimerAction::SetExtIntEn { .. } => 5,
TimerAction::WarmReset => 6,
TimerAction::UpdateReset => 7,
TimerAction::Nmi { .. } => 8,
TimerAction::ExtInt { .. } => 9,
TimerAction::InternalTimerLocalInterrupt { .. } => 10,
TimerAction::MachineTimerInterrupt => 11,
}
}
}
struct ClockImpl {
now: AtomicU64,
next_action_time: Mutex<Option<u64>>,
next_action_id: AtomicU64,
action_handles: Arc<RwLock<BTreeSet<ActionHandleImpl>>>,
}
impl ClockImpl {
fn new() -> Arc<Self> {
Arc::new(Self {
now: AtomicU64::new(0),
next_action_time: Mutex::new(None),
next_action_id: AtomicU64::new(0),
action_handles: Arc::new(RwLock::new(BTreeSet::new())),
})
}
#[inline]
fn now(&self) -> u64 {
self.now.load(Ordering::Relaxed)
}
#[inline]
fn increment(&self, delta: u64) -> HashSet<TimerAction> {
let mut fired_actions: HashSet<TimerAction> = HashSet::new();
assert!(
delta < (u64::MAX >> 1),
"Cannot increment the current time by more than {} clock cycles.",
(u64::MAX >> 1)
);
self.now.fetch_add(delta, Ordering::Relaxed);
let next_action_time = *self.next_action_time.lock().unwrap();
if let Some(next_action_time) = next_action_time {
if self.has_fired(next_action_time) {
self.remove_fired_actions(&mut fired_actions);
return fired_actions;
}
};
fired_actions
}
fn schedule_action_at(self: &Arc<Self>, time: u64, action: TimerAction) -> ActionHandle {
assert!(
time.wrapping_sub(self.now()) < (u64::MAX >> 1),
"Cannot schedule a timer action more than {} clock cycles from now.",
(u64::MAX >> 1)
);
let new_action = ActionHandleImpl {
time,
id: self.next_action_id(),
action,
};
let mut actions = self.action_handles.write().unwrap();
actions.insert(new_action);
self.recompute_next_action_time(&actions);
new_action.into()
}
fn cancel(self: &Arc<Self>, action: ActionHandle) {
let action = ActionHandleImpl::from(action);
assert_eq!(
Arc::as_ptr(self),
action.id.timer_ptr,
"Supplied action was not created by this timer."
);
let mut future_actions = self.action_handles.write().unwrap();
future_actions.remove(&action);
self.recompute_next_action_time(&future_actions)
}
fn next_action_id(self: &Arc<Self>) -> TimerActionId {
let id = self.next_action_id.fetch_add(1, Ordering::Relaxed);
TimerActionId {
timer_ptr: Arc::as_ptr(self),
id,
}
}
fn has_fired(&self, action_time: u64) -> bool {
self.now().wrapping_sub(action_time) < (u64::MAX >> 1)
}
fn recompute_next_action_time(&self, future_actions: &BTreeSet<ActionHandleImpl>) {
*self.next_action_time.lock().unwrap() =
self.find_next_action(future_actions).map(|a| a.time);
}
fn find_next_action<'a>(
&self,
future_actions: &'a BTreeSet<ActionHandleImpl>,
) -> Option<&'a ActionHandleImpl> {
let search_start = self.now().wrapping_sub(u64::MAX >> 1);
let search_action = ActionHandleImpl {
time: search_start,
id: TimerActionId::default(),
action: TimerAction::Poll,
};
if let Some(action) = future_actions.range(&search_action..).next() {
return Some(action);
}
future_actions.iter().next()
}
#[cold]
fn remove_fired_actions(&self, fired_actions: &mut HashSet<TimerAction>) {
let mut future_actions = self.action_handles.write().unwrap();
while let Some(action) = self.find_next_action(&future_actions) {
if !self.has_fired(action.time) {
break;
}
let action = *action;
future_actions.remove(&action);
fired_actions.insert(action.action);
}
self.recompute_next_action_time(&future_actions);
}
}
#[cfg(test)]
mod tests {
use crate::testing::FakeBus;
use super::*;
#[test]
fn test_clock() {
let clock = Clock::new();
assert_eq!(clock.now(), 0);
assert_eq!(clock.now(), 0);
assert!(clock.increment(25).is_empty());
assert_eq!(clock.now(), 25);
assert!(clock.increment(100).is_empty());
assert_eq!(clock.now(), 125);
}
fn test_timer_schedule_with_clock(clock: Clock) {
let t0 = clock.now();
let timer = clock.timer();
let mut action0 = Some(timer.schedule_poll_in(25));
let mut action1 = Some(timer.schedule_poll_in(40));
let mut action2 = Some(timer.schedule_poll_in(100));
let mut action3 = Some(timer.schedule_poll_in(100));
let mut action4 = Some(timer.schedule_poll_in(101));
let mut action5 = Some(timer.schedule_poll_in(102));
let mut action6 = Option::<ActionHandle>::None;
assert!(clock.increment(24).is_empty());
assert_eq!(clock.now().wrapping_sub(t0), 24);
assert!(!timer.fired(&mut action0) && action0.is_some());
assert!(!timer.fired(&mut action2) && action2.is_some());
assert!(!timer.fired(&mut action3) && action3.is_some());
assert!(!timer.fired(&mut action4) && action4.is_some());
assert!(!timer.fired(&mut action5) && action5.is_some());
assert!(!timer.fired(&mut action6) && action6.is_none());
assert!(!clock.increment(1).is_empty());
assert_eq!(clock.now().wrapping_sub(t0), 25);
assert!(timer.fired(&mut action0) && action0.is_none());
assert!(!timer.fired(&mut action2) && action2.is_some());
assert!(!timer.fired(&mut action3) && action3.is_some());
assert!(!timer.fired(&mut action4) && action4.is_some());
assert!(!timer.fired(&mut action5) && action5.is_some());
assert!(!timer.fired(&mut action6) && action6.is_none());
assert!(clock.increment(1).is_empty());
assert_eq!(clock.now().wrapping_sub(t0), 26);
assert!(!timer.fired(&mut action0) && action0.is_none());
assert!(!timer.fired(&mut action2) && action2.is_some());
assert!(!timer.fired(&mut action3) && action3.is_some());
assert!(!timer.fired(&mut action4) && action4.is_some());
assert!(!timer.fired(&mut action5) && action5.is_some());
assert!(!timer.fired(&mut action6) && action6.is_none());
action6 = Some(timer.schedule_poll_in(1));
assert!(!clock.increment(1).is_empty());
assert_eq!(clock.now().wrapping_sub(t0), 27);
assert!(!timer.fired(&mut action0) && action0.is_none());
assert!(!timer.fired(&mut action2) && action2.is_some());
assert!(!timer.fired(&mut action3) && action3.is_some());
assert!(!timer.fired(&mut action4) && action4.is_some());
assert!(!timer.fired(&mut action5) && action5.is_some());
assert!(timer.fired(&mut action6) && action6.is_none());
timer.cancel(action1.take().unwrap());
assert!(clock.increment(24).is_empty());
assert_eq!(clock.now().wrapping_sub(t0), 51);
assert!(!clock.increment(50).is_empty());
assert_eq!(clock.now().wrapping_sub(t0), 101);
assert!(!timer.fired(&mut action0) && action0.is_none());
assert!(timer.fired(&mut action2) && action2.is_none());
assert!(timer.fired(&mut action3) && action3.is_none());
assert!(timer.fired(&mut action4) && action4.is_none());
assert!(!timer.fired(&mut action5) && action5.is_some());
assert!(!timer.fired(&mut action6) && action6.is_none());
assert!(!clock.increment(1000000000000000000).is_empty());
assert!(!timer.fired(&mut action0) && action0.is_none());
assert!(!timer.fired(&mut action2) && action2.is_none());
assert!(!timer.fired(&mut action3) && action3.is_none());
assert!(!timer.fired(&mut action4) && action4.is_none());
assert!(timer.fired(&mut action5) && action5.is_none());
assert!(!timer.fired(&mut action6) && action6.is_none());
assert!(clock.increment(1000000000000000000).is_empty());
}
#[test]
fn test_timer_schedule_with_clock_at_0() {
let clock = Clock::new();
test_timer_schedule_with_clock(clock);
}
#[test]
fn test_timer_schedule_with_clock_at_12327834() {
let clock = Clock::new();
assert!(clock.increment(234293489238).is_empty());
test_timer_schedule_with_clock(clock);
}
#[test]
fn test_timer_schedule_clock_wraparound() {
for i in (u64::MAX - 120)..=u64::MAX {
let clock = Clock::new();
clock.clock.now.store(i, Ordering::Relaxed);
test_timer_schedule_with_clock(clock);
}
}
#[test]
fn test_timer_schedule_clock_searchback_wraparound() {
for i in ((u64::MAX >> 1) - 130)..=((u64::MAX >> 1) + 130) {
let clock = Clock::new();
clock.clock.now.store(i, Ordering::Relaxed);
test_timer_schedule_with_clock(clock);
}
}
#[test]
fn test_increment_and_poll() {
let clock = Clock::new();
let timer = clock.timer();
let mut bus = FakeBus::new();
let mut action0 = Some(timer.schedule_poll_in(25));
clock.increment_and_process_timer_actions(20, &mut bus);
assert_eq!(bus.log.take(), "");
clock.increment_and_process_timer_actions(20, &mut bus);
assert_eq!(bus.log.take(), "poll()\n");
assert!(timer.fired(&mut action0));
}
#[test]
#[should_panic(
expected = "Cannot schedule a timer action more than 9223372036854775807 clock cycles from now."
)]
fn test_schedule_too_far_in_future() {
let clock = Clock::new();
clock.increment(123729);
let timer = Timer::new(&clock);
timer.schedule_poll_in(0x7fff_ffff_ffff_ffff);
}
#[test]
#[should_panic(
expected = "Cannot increment the current time by more than 9223372036854775807 clock cycles."
)]
fn test_increment_too_far() {
let clock = Clock::new();
clock.increment(0x7fff_ffff_ffff_ffff);
}
#[test]
#[should_panic(expected = "Supplied action was not created by this timer.")]
fn test_mixup_timer_actions_on_cancel() {
let clock0 = Clock::new();
let clock0_action0 = clock0.timer().schedule_poll_at(50);
let clock1 = Clock::new();
let _clock1_action0 = clock1.timer().schedule_poll_at(50);
clock1.timer().cancel(clock0_action0);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/ram.rs | sw-emulator/lib/bus/src/ram.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
ram.rs
Abstract:
File contains implementation of RAM
--*/
use crate::{mem::Mem, Bus, BusError};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
/// Trait defining memory access behavior
pub trait MemAccess {
fn read_mem(mem: &Mem, size: RvSize, addr: RvAddr) -> Result<RvData, crate::mem::MemError>;
fn write_mem(
mem: &mut Mem,
size: RvSize,
addr: RvAddr,
val: RvData,
) -> Result<(), crate::mem::MemError>;
}
/// Unaligned memory access (current behavior)
pub struct UnalignedAccess;
impl MemAccess for UnalignedAccess {
fn read_mem(mem: &Mem, size: RvSize, addr: RvAddr) -> Result<RvData, crate::mem::MemError> {
mem.read(size, addr)
}
fn write_mem(
mem: &mut Mem,
size: RvSize,
addr: RvAddr,
val: RvData,
) -> Result<(), crate::mem::MemError> {
mem.write(size, addr, val)
}
}
/// Aligned memory access
pub struct AlignedAccess;
impl MemAccess for AlignedAccess {
fn read_mem(mem: &Mem, size: RvSize, addr: RvAddr) -> Result<RvData, crate::mem::MemError> {
mem.read_aligned(size, addr)
}
fn write_mem(
mem: &mut Mem,
size: RvSize,
addr: RvAddr,
val: RvData,
) -> Result<(), crate::mem::MemError> {
mem.write_aligned(size, addr, val)
}
}
/// Random Access Memory Device
pub struct RamImpl<T: MemAccess = UnalignedAccess> {
/// Inject double-bit ECC errors on read
pub error_injection: u8,
/// Random Access Data
data: Mem,
/// Memory access behavior
_phantom: std::marker::PhantomData<T>,
}
impl<T: MemAccess> RamImpl<T> {
/// Create new RAM
///
/// # Arguments
///
/// * `data` - Data to be stored in the RAM
pub fn new(data: Vec<u8>) -> Self {
Self {
error_injection: 0,
data: Mem::new(data),
_phantom: std::marker::PhantomData,
}
}
/// Size of the memory in bytes
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> RvAddr {
self.data.len() as RvAddr
}
/// Immutable reference to data
pub fn data(&self) -> &[u8] {
self.data.data()
}
/// Mutable reference to data
pub fn data_mut(&mut self) -> &mut [u8] {
self.data.data_mut()
}
}
impl<T: MemAccess> Bus for RamImpl<T> {
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `BusException` - Exception with cause `BusExceptionCause::LoadAccessFault`
/// or `BusExceptionCause::LoadAddrMisaligned`
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
if 2 == self.error_injection {
return Err(BusError::InstrAccessFault);
}
if 8 == self.error_injection {
return Err(BusError::LoadAccessFault);
}
match T::read_mem(&self.data, size, addr) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `data` - Data to write
///
/// # Error
///
/// * `BusException` - Exception with cause `BusExceptionCause::StoreAccessFault`
/// or `BusExceptionCause::StoreAddrMisaligned`
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match T::write_mem(&mut self.data, size, addr, val) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
}
/// Type alias for unaligned RAM (default behavior)
pub type Ram = RamImpl<UnalignedAccess>;
/// Type alias for aligned RAM
pub type AlignedRam = RamImpl<AlignedAccess>;
#[cfg(test)]
mod tests {
use super::*;
use crate::BusError;
#[test]
fn test_new() {
let _ram = Ram::new(vec![1, 2, 3, 4]);
}
#[test]
fn test_read() {
let mut ram = Ram::new(vec![1, 2, 3, 4]);
assert_eq!(ram.read(RvSize::Byte, 0).ok(), Some(1));
assert_eq!(ram.read(RvSize::HalfWord, 0).ok(), Some(1 | (2 << 8)));
assert_eq!(
ram.read(RvSize::Word, 0).ok(),
Some(1 | (2 << 8) | (3 << 16) | (4 << 24))
);
}
#[test]
fn test_read_error() {
let mut ram = Ram::new(vec![1, 2, 3, 4]);
assert_eq!(
ram.read(RvSize::Byte, ram.len()).err(),
Some(BusError::LoadAccessFault),
)
}
#[test]
fn test_write() {
let mut ram = Ram::new(vec![1, 2, 3, 4]);
assert_eq!(ram.write(RvSize::Byte, 0, u32::MAX).ok(), Some(()))
}
#[test]
fn test_write_error() {
let mut ram = Ram::new(vec![1, 2, 3, 4]);
assert_eq!(
ram.write(RvSize::Byte, ram.len(), 0).err(),
Some(BusError::StoreAccessFault),
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/mem.rs | sw-emulator/lib/bus/src/mem.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mem.rs
Abstract:
File contains implementation of helper data structures to support memory
devices like ROM, TCM and RAM.
--*/
use crate::BusError;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
/// Memory Exception
#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq)]
pub enum MemError {
/// Read Address misaligned
ReadAddrMisaligned,
/// Read Access fault
ReadAccessFault,
/// Write Address misaligned
WriteAddrMisaligned,
/// Write access fault
WriteAccessFault,
}
impl From<MemError> for BusError {
/// Converts to this type from the input type.
fn from(exception: MemError) -> BusError {
match exception {
MemError::ReadAddrMisaligned => BusError::LoadAddrMisaligned,
MemError::ReadAccessFault => BusError::LoadAccessFault,
MemError::WriteAddrMisaligned => BusError::StoreAddrMisaligned,
MemError::WriteAccessFault => BusError::StoreAccessFault,
}
}
}
/// Memory
#[allow(dead_code)]
pub struct Mem {
/// Data storage
data: Vec<u8>,
}
#[allow(dead_code)]
impl Mem {
/// Create a new memory object
///
/// # Arguments
///
/// * `data` - Data contents for memory
pub fn new(data: Vec<u8>) -> Self {
Self { data }
}
/// Size of the memory in bytes
#[inline]
pub fn len(&self) -> usize {
self.data.len()
}
/// Immutable reference to data
pub fn data(&self) -> &[u8] {
&self.data
}
/// Mutable reference to data
pub fn data_mut(&mut self) -> &mut [u8] {
&mut self.data
}
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
pub fn read(&self, size: RvSize, addr: RvAddr) -> Result<RvData, MemError> {
match size {
RvSize::Byte => self.read_byte(addr as usize),
RvSize::HalfWord => self.read_half_word(addr as usize),
RvSize::Word => self.read_word(addr as usize),
RvSize::Invalid => Err(MemError::ReadAccessFault),
}
}
/// Read data of specified size from given address. This function checks the address
/// is `size` aligned.
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAddrMisaligned` - Read address is not `size` aligned
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
pub fn read_aligned(&self, size: RvSize, addr: RvAddr) -> Result<RvData, MemError> {
match size {
RvSize::Byte => self.read_byte(addr as usize),
RvSize::HalfWord => self.read_aligned_half_word(addr as usize),
RvSize::Word => self.read_aligned_word(addr as usize),
RvSize::Invalid => Err(MemError::ReadAccessFault),
}
}
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `val` - Data to write
///
/// # Error
///
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
pub fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), MemError> {
match size {
RvSize::Byte => self.write_byte(addr as usize, val),
RvSize::HalfWord => self.write_half_word(addr as usize, val),
RvSize::Word => self.write_word(addr as usize, val),
RvSize::Invalid => Err(MemError::WriteAccessFault),
}
}
/// Write data of specified size to given address. This function checks the address
/// is `size` aligned.
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `data` - Data to write
///
/// # Error
///
/// * `MemError::WriteAddrMisaligned` - Write address is not `size` aligned
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
pub fn write_aligned(
&mut self,
size: RvSize,
addr: RvAddr,
data: RvData,
) -> Result<(), MemError> {
match size {
RvSize::Byte => self.write_byte(addr as usize, data),
RvSize::HalfWord => self.write_aligned_half_word(addr as usize, data),
RvSize::Word => self.write_aligned_word(addr as usize, data),
RvSize::Invalid => Err(MemError::WriteAccessFault),
}
}
/// Read a byte from given address
///
/// # Arguments
///
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
fn read_byte(&self, addr: usize) -> Result<RvData, MemError> {
if addr < self.data.len() {
Ok(self.data[addr] as RvData)
} else {
Err(MemError::ReadAccessFault)
}
}
/// Read half word (two bytes) from given address
///
/// # Arguments
///
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
fn read_half_word(&self, addr: usize) -> Result<RvData, MemError> {
if addr < self.data.len() && addr + 1 < self.data.len() {
Ok((self.data[addr] as RvData) | ((self.data[addr + 1] as RvData) << 8))
} else {
Err(MemError::ReadAccessFault)
}
}
/// Read word (four bytes) from given address
///
/// # Arguments
///
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
fn read_word(&self, addr: usize) -> Result<RvData, MemError> {
if addr < self.data.len() && addr + 3 < self.data.len() {
Ok((self.data[addr] as RvData)
| ((self.data[addr + 1] as RvData) << 8)
| ((self.data[addr + 2] as RvData) << 16)
| ((self.data[addr + 3] as RvData) << 24))
} else {
Err(MemError::ReadAccessFault)
}
}
/// Read aligned half word (two bytes) from given address.
///
/// # Arguments
///
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAddrMisaligned` - Read address is misaligned
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
fn read_aligned_half_word(&self, addr: usize) -> Result<RvData, MemError> {
if addr < self.data.len() {
if addr & 1 == 0 {
self.read_half_word(addr)
} else {
Err(MemError::ReadAddrMisaligned)
}
} else {
Err(MemError::ReadAccessFault)
}
}
/// Read aligned word (four bytes) from given address.
///
/// # Arguments
///
/// * `addr` - Address to read from
///
/// # Error
///
/// * `MemError::ReadAddrMisaligned` - Read address is misaligned
/// * `MemError::ReadAccessFault` - Read from invalid or non existent address
#[inline]
fn read_aligned_word(&self, addr: usize) -> Result<RvData, MemError> {
if addr < self.data.len() {
if addr & 3 == 0 {
self.read_word(addr)
} else {
Err(MemError::ReadAddrMisaligned)
}
} else {
Err(MemError::ReadAccessFault)
}
}
/// Write a byte to given address
///
/// # Arguments
///
/// * `addr` - Address to write to
/// * `data` - Data to write
///
/// # Error
///
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
fn write_byte(&mut self, addr: usize, data: RvData) -> Result<(), MemError> {
if addr < self.data.len() {
self.data[addr] = data as u8;
Ok(())
} else {
Err(MemError::WriteAccessFault)
}
}
/// Write half word (2 bytes) to given address
///
/// # Arguments
///
/// * `addr` - Address to write to
/// * `data` - Data to write
///
/// # Error
///
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
fn write_half_word(&mut self, addr: usize, data: RvData) -> Result<(), MemError> {
if addr < self.data.len() && addr + 1 < self.data.len() {
self.data[addr] = (data & 0xff) as u8;
self.data[addr + 1] = ((data >> 8) & 0xff) as u8;
Ok(())
} else {
Err(MemError::WriteAccessFault)
}
}
/// Write word (4 bytes) to given address
///
/// # Arguments
///
/// * `addr` - Address to write to
/// * `data` - Data to write
///
/// # Error
///
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
fn write_word(&mut self, addr: usize, data: RvData) -> Result<(), MemError> {
if addr < self.data.len() && addr + 3 < self.data.len() {
self.data[addr] = (data & 0xff) as u8;
self.data[addr + 1] = ((data >> 8) & 0xff) as u8;
self.data[addr + 2] = ((data >> 16) & 0xff) as u8;
self.data[addr + 3] = ((data >> 24) & 0xff) as u8;
Ok(())
} else {
Err(MemError::WriteAccessFault)
}
}
/// Write aligned half word (2 bytes) to given address
///
/// # Arguments
///
/// * `addr` - Address to write to
/// * `data` - Data to write
///
/// # Error
///
/// * `MemException::WriteAddrMisaligned` - Write address is misaligned
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
fn write_aligned_half_word(&mut self, addr: usize, data: RvData) -> Result<(), MemError> {
if addr < self.data.len() {
if addr & 1 == 0 {
self.write_half_word(addr, data)
} else {
Err(MemError::WriteAddrMisaligned)
}
} else {
Err(MemError::WriteAccessFault)
}
}
/// Write aligned word (4 bytes) to given address
///
/// # Arguments
///
/// * `addr` - Address to write to
/// * `data` - Data to write
///
/// # Error
///
/// * `MemException::WriteAddrMisaligned` - Write address is misaligned
/// * `MemError::WriteAccessFault` - Write to invalid or non existent address
#[inline]
fn write_aligned_word(&mut self, addr: usize, data: RvData) -> Result<(), MemError> {
if addr < self.data.len() {
if addr & 3 == 0 {
self.write_word(addr, data)
} else {
Err(MemError::WriteAddrMisaligned)
}
} else {
Err(MemError::WriteAccessFault)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! read_test {
($func:ident, $size:path, $aligned:literal) => {
#[test]
fn $func() {
fn make_word(size: usize, idx: usize, vec: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..size {
res |= ((vec[idx + i] as RvData) << i * 8);
}
res
}
let size: usize = $size.into();
let read_fn = if !$aligned {
Mem::read
} else {
Mem::read_aligned
};
let vec = vec![1, 2, 3, 4, 5];
let mem = Mem::new(vec.clone());
let mut i = 0;
while (mem.len() - i) > (size - 1) {
if !$aligned || i & (size - 1) == 0 {
assert_eq!(
read_fn(&mem, $size, i as RvAddr).ok(),
Some(make_word(size, i, &vec))
);
} else {
assert_eq!(
read_fn(&mem, $size, i as RvAddr).err(),
Some(MemError::ReadAddrMisaligned)
);
}
i += 1;
}
while (mem.len() - i) > 1 {
if !$aligned || i & (size - 1) == 0 {
assert_eq!(
read_fn(&mem, $size, i as RvAddr).err(),
Some(MemError::ReadAccessFault)
);
} else {
assert_eq!(
read_fn(&mem, $size, i as RvAddr).err(),
Some(MemError::ReadAddrMisaligned)
);
}
i += 1;
}
assert_eq!(
read_fn(&mem, $size, i as RvAddr).err(),
Some(MemError::ReadAccessFault)
);
}
};
}
macro_rules! write_test {
($func:ident, $size:path, $aligned:literal) => {
#[test]
fn $func() {
let size: usize = $size.into();
let write_fn = if !$aligned {
Mem::write
} else {
Mem::write_aligned
};
let mask = !(u64::MAX.wrapping_shl(8u32 * size as u32)) as u32;
let vec = vec![0, 0, 0, 0, 0];
let mut mem = Mem::new(vec.clone());
let mut i = 0;
let mut data = 0xCAFEBABE as RvData;
while mem.len() - i > size - 1 {
if !$aligned || i & (size - 1) == 0 {
assert_eq!(write_fn(&mut mem, $size, i as RvAddr, data).ok(), Some(()));
assert_eq!(mem.read($size, i as RvAddr).ok(), Some(mask & data));
} else {
assert_eq!(
write_fn(&mut mem, $size, i as RvAddr, data).err(),
Some(MemError::WriteAddrMisaligned),
);
}
i += 1;
data += 1;
}
while (mem.len() - i) > 0 {
if !$aligned || i & (size - 1) == 0 {
assert_eq!(
write_fn(&mut mem, $size, i as RvAddr, data).err(),
Some(MemError::WriteAccessFault),
);
} else {
assert_eq!(
write_fn(&mut mem, $size, i as RvAddr, data).err(),
Some(MemError::WriteAddrMisaligned),
);
}
i += 1;
}
assert_eq!(
write_fn(&mut mem, $size, i as RvAddr, data).err(),
Some(MemError::WriteAccessFault),
);
}
};
}
#[test]
fn test_new() {
// Test zero sized memory
let mem = Mem::new(Vec::new());
assert_eq!(mem.len(), 0);
// Test memory
let data = vec![1, 2, 3];
let mem = Mem::new(data.clone());
assert_eq!(mem.len(), data.len());
}
read_test!(test_read_byte, RvSize::Byte, false);
read_test!(test_read_half_word, RvSize::HalfWord, false);
read_test!(test_read_word, RvSize::Word, false);
read_test!(test_read_aligned_byte, RvSize::Byte, true);
read_test!(test_read_aligned_half_word, RvSize::HalfWord, true);
read_test!(test_read_aligned_word, RvSize::Word, true);
write_test!(test_write_byte, RvSize::Byte, false);
write_test!(test_write_half_word, RvSize::HalfWord, false);
write_test!(test_write_word, RvSize::Word, false);
write_test!(test_write_aligned_byte, RvSize::Byte, true);
write_test!(test_write_aligned_half_word, RvSize::HalfWord, true);
write_test!(test_write_aligned_word, RvSize::Word, true);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/bus.rs | sw-emulator/lib/bus/src/bus.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
bus.rs
Abstract:
File contains definition of the Bus trait.
--*/
use crate::Event;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use std::{rc::Rc, sync::mpsc};
#[allow(unused)]
pub trait EventListener {
fn incoming_event(&mut self, _event: Rc<Event>) {
// By default, do nothing
}
}
#[allow(unused)]
pub trait EventSender {
fn register_outgoing_events(&mut self, _sender: mpsc::Sender<Event>) {
// By default, do nothing
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BusError {
/// Instruction access exception
InstrAccessFault,
/// Load address misaligned exception
LoadAddrMisaligned,
/// Load access fault exception
LoadAccessFault,
/// Store address misaligned exception
StoreAddrMisaligned,
/// Store access fault exception
StoreAccessFault,
}
/// Represents an abstract memory bus. Used to read and write from RAM and
/// peripheral addresses.
pub trait Bus {
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::LoadAccessFault` or `BusError::LoadAddrMisaligned`
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError>;
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError>;
/// This method is used to notify peripherals of the passage of time. The
/// owner of this bus MAY call this function periodically, or in response to
/// a previously scheduled timer event.
fn poll(&mut self) {
// By default, do nothing
}
fn warm_reset(&mut self) {
// By default, do nothing
}
fn update_reset(&mut self) {
// By default, do nothing
}
fn incoming_event(&mut self, _event: Rc<Event>) {
// By default, do nothing
}
fn register_outgoing_events(&mut self, _sender: mpsc::Sender<Event>) {
// By default, do nothing
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/mmio.rs | sw-emulator/lib/bus/src/mmio.rs | // Licensed under the Apache-2.0 license
use std::cell::RefCell;
use caliptra_emu_types::RvSize;
use crate::Bus;
const fn rvsize<T>() -> RvSize {
match core::mem::size_of::<T>() {
1 => RvSize::Byte,
2 => RvSize::HalfWord,
4 => RvSize::Word,
_other => panic!("Unsupported RvSize"),
}
}
unsafe fn transmute_to_u32<T>(src: &T) -> u32 {
match std::mem::size_of::<T>() {
1 => std::mem::transmute_copy::<T, u8>(src).into(),
2 => std::mem::transmute_copy::<T, u16>(src).into(),
4 => std::mem::transmute_copy::<T, u32>(src),
_ => panic!("Unsupported write size"),
}
}
/// An MMIO implementation that reads and writes to a `caliptra_emu_bus::Bus`.
pub struct BusMmio<TBus: Bus> {
bus: RefCell<TBus>,
}
impl<TBus: Bus> BusMmio<TBus> {
pub fn new(bus: TBus) -> Self {
Self {
bus: RefCell::new(bus),
}
}
pub fn into_inner(self) -> TBus {
self.bus.into_inner()
}
}
impl<TBus: Bus> ureg::Mmio for BusMmio<TBus> {
/// Loads from address `src` on the bus and returns the value.
///
/// # Panics
///
/// This function panics if the bus faults.
///
/// # Safety
///
/// As the pointer isn't read from, this Mmio implementation isn't actually
/// unsafe for POD types like u8/u16/u32.
unsafe fn read_volatile<T: Clone + Copy + Sized>(&self, src: *const T) -> T {
let val_u32 = self
.bus
.borrow_mut()
.read(rvsize::<T>(), src as usize as u32)
.unwrap();
match std::mem::size_of::<T>() {
1 => std::mem::transmute_copy::<u8, T>(&(val_u32 as u8)),
2 => std::mem::transmute_copy::<u16, T>(&(val_u32 as u16)),
4 => std::mem::transmute_copy::<u32, T>(&val_u32),
_ => panic!("Unsupported read size"),
}
}
}
impl<TBus: Bus> ureg::MmioMut for BusMmio<TBus> {
/// Stores `src` to address `dst` on the bus.
///
/// # Panics
///
/// This function panics if the bus faults.
///
/// # Safety
///
/// As the pointer isn't written to, this Mmio implementation isn't actually
/// unsafe for POD types like u8/u16/u32.
unsafe fn write_volatile<T: Clone + Copy>(&self, dst: *mut T, src: T) {
self.bus
.borrow_mut()
.write(rvsize::<T>(), dst as usize as u32, transmute_to_u32(&src))
.unwrap()
}
}
#[cfg(test)]
mod tests {
use crate::Ram;
use ureg::{Mmio, MmioMut};
use super::*;
#[test]
fn test_bus_mmio() {
let mmio = BusMmio::new(Ram::new(vec![0u8; 12]));
unsafe {
mmio.write_volatile(4 as *mut u32, 0x3abc_9321);
mmio.write_volatile(8 as *mut u16, 0x39af);
mmio.write_volatile(10 as *mut u8, 0xf3);
assert_eq!(mmio.read_volatile(4 as *const u32), 0x3abc_9321);
assert_eq!(mmio.read_volatile(8 as *const u16), 0x39af);
assert_eq!(mmio.read_volatile(10 as *const u8), 0xf3);
}
assert_eq!(
mmio.into_inner().data(),
&[0x00, 0x00, 0x00, 0x00, 0x21, 0x93, 0xbc, 0x3a, 0xaf, 0x39, 0xf3, 0x00]
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/testing/fake_bus.rs | sw-emulator/lib/bus/src/testing/fake_bus.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
fake_bus.rs
Abstract:
File contains code for a fake implementation of the Bus trait.
--*/
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use crate::{testing::Log, Bus, BusError};
use std::fmt::Write;
/// A Bus implementation that logs all calls, and allows the user to override
/// the return value of the methods.
///
/// # Example
///
/// ```
/// use caliptra_emu_bus::{Bus, testing::FakeBus};
/// use caliptra_emu_types::RvSize;
///
/// let mut fake_bus = FakeBus::new();
/// fake_bus.read_result = Ok(35);
/// assert_eq!(fake_bus.read(RvSize::HalfWord, 0xdeadcafe), Ok(35));
/// assert_eq!("read(RvSize::HalfWord, 0xdeadcafe)\n", fake_bus.log.take());
/// ```
pub struct FakeBus {
pub log: Log,
pub read_result: Result<RvData, crate::BusError>,
pub write_result: Result<(), crate::BusError>,
}
impl FakeBus {
pub fn new() -> Self {
Self {
log: Log::new(),
read_result: Ok(0),
write_result: Ok(()),
}
}
}
impl Default for FakeBus {
fn default() -> Self {
Self::new()
}
}
impl Bus for FakeBus {
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
writeln!(self.log.w(), "read(RvSize::{size:?}, {addr:#x})").unwrap();
self.read_result
}
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
writeln!(self.log.w(), "write(RvSize::{size:?}, {addr:#x}, {val:#x})").unwrap();
self.write_result
}
fn poll(&mut self) {
writeln!(self.log.w(), "poll()").unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fake_bus() {
let mut fake_bus = FakeBus::new();
assert_eq!(fake_bus.read(RvSize::HalfWord, 0xdeadcafe), Ok(0));
assert_eq!("read(RvSize::HalfWord, 0xdeadcafe)\n", fake_bus.log.take());
assert_eq!(fake_bus.write(RvSize::Word, 0xf00dcafe, 0x537), Ok(()));
assert_eq!(
"write(RvSize::Word, 0xf00dcafe, 0x537)\n",
fake_bus.log.take()
);
fake_bus.read_result = Err(BusError::LoadAccessFault);
assert_eq!(
fake_bus.read(RvSize::Byte, 0x12345678),
Err(BusError::LoadAccessFault)
);
assert_eq!("read(RvSize::Byte, 0x12345678)\n", fake_bus.log.take());
fake_bus.write_result = Err(BusError::StoreAddrMisaligned);
assert_eq!(
fake_bus.write(RvSize::Word, 0x131, 0x1),
Err(BusError::StoreAddrMisaligned)
);
assert_eq!("write(RvSize::Word, 0x131, 0x1)\n", fake_bus.log.take());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/testing/log.rs | sw-emulator/lib/bus/src/testing/log.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
log.rs
Abstract:
File contains code useful for logging inside unit tests.
--*/
use std::{
cell::{Ref, RefCell},
fmt::Write,
ops::Deref,
rc::Rc,
};
/// A type for logging actions without needing &mut self. Useful for logging
/// actions that occur in "fake" Bus trait implementations in unit tests.
///
/// When `Log` is cloned, the clones all share the same underlying buffer. This
/// allows tests to introspect logs that are not accessible directly.
///
/// * Example
///
/// ```
/// use caliptra_emu_bus::testing::Log;
/// use std::fmt::Write;
///
/// let log = Log::new();
/// writeln!(log.w(), "Line 1").unwrap();
/// writeln!(log.w(), "Line 2").unwrap();
/// assert_eq!("Line 1\nLine 2\n", &*log.as_str());
/// assert_eq!("Line 1\nLine 2\n", log.take());
/// assert_eq!("", log.take());
/// ```
#[derive(Clone)]
pub struct Log {
log: Rc<RefCell<String>>,
}
impl Log {
/// Construct an empty `Log`.
pub fn new() -> Self {
Self {
log: Rc::new(RefCell::new(String::new())),
}
}
/// Access the contents of the log without modifying it.
pub fn as_str(&self) -> (impl Deref<Target = str> + '_) {
Ref::map(self.log.borrow(), String::as_str)
}
/// Replaces the existing contents of the log with an empty string, and
/// returns the previous contents. Useful for writing assertions for recent
/// actions.
pub fn take(&self) -> String {
let mut result = String::new();
std::mem::swap(&mut *self.log.borrow_mut(), &mut result);
result
}
/// returns a writer that can be use with write!() or writeln!().
pub fn w(&self) -> (impl Write + '_) {
LogWriter { log: &self.log }
}
}
impl Default for Log {
fn default() -> Self {
Self::new()
}
}
struct LogWriter<'a> {
log: &'a RefCell<String>,
}
impl Write for LogWriter<'_> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
Write::write_str(&mut *self.log.borrow_mut(), s)
}
fn write_char(&mut self, c: char) -> std::fmt::Result {
Write::write_char(&mut *self.log.borrow_mut(), c)
}
fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::fmt::Result {
Write::write_fmt(&mut *self.log.borrow_mut(), args)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fmt::Write;
#[test]
fn test() {
let log = Log::new();
writeln!(log.w(), "Line 1").unwrap();
writeln!(log.w(), "Line 2").unwrap();
assert_eq!("Line 1\nLine 2\n", &*log.as_str());
assert_eq!("Line 1\nLine 2\n", log.take());
assert_eq!("", log.take());
}
#[test]
#[allow(clippy::redundant_clone)]
fn test_clone() {
let log = Log::new();
writeln!(log.clone().w(), "Line 1").unwrap();
writeln!(log.clone().w(), "Line 2").unwrap();
assert_eq!("Line 1\nLine 2\n", &*log.as_str());
assert_eq!("Line 1\nLine 2\n", log.take());
assert_eq!("", log.take());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/testing/mod.rs | sw-emulator/lib/bus/src/testing/mod.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mod.rs
Abstract:
File contains exports for code useful for testing Bus traits.
--*/
mod fake_bus;
mod log;
pub use fake_bus::FakeBus;
pub use log::Log;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/aes256gcm.rs | sw-emulator/lib/crypto/src/aes256gcm.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
aes256gcm.rs
Abstract:
File contains implementation of AES-256 GCM algorithm.
--*/
use crate::{AES_256_BLOCK_SIZE, AES_256_KEY_SIZE};
use aes::cipher::{BlockEncrypt, KeyInit};
use aes::Aes256;
use aes_gcm::{
aead::{AeadCore, AeadMutInPlace, OsRng},
Key,
};
const AES_256_GCM_IV_SIZE: usize = 12;
const AES_256_GCM_TAG_SIZE: usize = 16;
/// Streaming GHASH implementation for AES-256-GCM.
#[derive(Default)]
pub struct GHash {
h: u128,
state: u128,
}
impl GHash {
pub fn new(key: &[u8; AES_256_KEY_SIZE]) -> Self {
// h = encrypt(0)
let cipher = Aes256::new(key.into());
let ghash_key = &mut [0u8; AES_256_BLOCK_SIZE];
cipher.encrypt_block(ghash_key.into());
let h = u128::from_be_bytes(*ghash_key);
Self { h, state: 0 }
}
pub fn restore(&mut self, state: [u8; AES_256_BLOCK_SIZE]) {
self.state = u128::from_be_bytes(state);
}
pub fn update(&mut self, block: &[u8; AES_256_BLOCK_SIZE]) {
let block = u128::from_be_bytes(*block);
self.state ^= block;
self.state = gf2_128_mul(self.state, self.h);
}
pub fn finalize(
&self,
key: &[u8; AES_256_KEY_SIZE],
iv: &[u8; AES_256_GCM_IV_SIZE],
) -> [u8; AES_256_BLOCK_SIZE] {
let mut iv_bytes = [0u8; AES_256_BLOCK_SIZE];
iv_bytes[..12].copy_from_slice(iv);
iv_bytes[15] = 1;
let cipher = Aes256::new(key.into());
cipher.encrypt_block((&mut iv_bytes).into());
let e_j0 = u128::from_be_bytes(iv_bytes);
let output = self.state ^ e_j0;
output.to_be_bytes()
}
pub fn state(&self) -> [u8; AES_256_BLOCK_SIZE] {
self.state.to_be_bytes()
}
}
pub enum Aes256Gcm {}
impl Aes256Gcm {
/// One-shot AES-256-GCM decryption.
pub fn decrypt(
key: &[u8; AES_256_KEY_SIZE],
iv: &[u8; AES_256_GCM_IV_SIZE],
aad: &[u8],
tag: &[u8; AES_256_GCM_TAG_SIZE],
ciphertext: &[u8],
) -> Option<Vec<u8>> {
let key: &Key<aes_gcm::Aes256Gcm> = key.into();
let mut cipher = aes_gcm::Aes256Gcm::new(key);
let mut buffer = ciphertext.to_vec();
match cipher.decrypt_in_place_detached(iv.into(), aad, &mut buffer, tag.into()) {
Ok(_) => Some(buffer),
Err(_) => None,
}
}
/// One-shot AES-256-GCM encryption.
pub fn encrypt(
key: &[u8; AES_256_KEY_SIZE],
iv: Option<&[u8; AES_256_GCM_IV_SIZE]>,
aad: &[u8],
plaintext: &[u8],
) -> Option<(
[u8; AES_256_GCM_IV_SIZE],
Vec<u8>,
[u8; AES_256_GCM_TAG_SIZE],
)> {
let random_iv = aes_gcm::Aes256Gcm::generate_nonce(&mut OsRng).into();
let iv = iv.unwrap_or(&random_iv);
let key: &Key<aes_gcm::Aes256Gcm> = key.into();
let mut cipher = aes_gcm::Aes256Gcm::new(key);
let mut buffer = plaintext.to_vec();
match cipher.encrypt_in_place_detached(iv.into(), aad, &mut buffer) {
Ok(tag) => Some((*iv, buffer, tag.into())),
Err(_) => None,
}
}
/// Encrypts/decrypts a single block of data at an arbitrary location using AES-256-GCM.
pub fn crypt_block(
key: &[u8; AES_256_KEY_SIZE],
iv: &[u8; AES_256_GCM_IV_SIZE],
block_num: usize,
plaintext: &[u8; 16],
) -> [u8; 16] {
let key: &Key<aes_gcm::Aes256Gcm> = key.into();
let mut cipher = aes_gcm::Aes256Gcm::new(key);
// TODO: remove this hack and use propert CTR mode for performance.
let mut buffer = [0u8; AES_256_BLOCK_SIZE].repeat(block_num);
buffer.extend_from_slice(plaintext);
cipher
.encrypt_in_place_detached(iv.into(), &[], &mut buffer)
.unwrap();
buffer[buffer.len() - AES_256_BLOCK_SIZE..]
.try_into()
.unwrap()
}
}
/// The AES GCM polynomial for GF(2^128), bit-reversed as in the standard.
const GCM_POLY: u128 = 0xE1000000000000000000000000000000;
/// Computes a * b in GF(2^128).
/// See https://en.wikipedia.org/wiki/Finite_field_arithmetic#Multiplication for some details.
///
/// This is implemented as constant time. It could be faster if we used carryless multiply instructions:
/// https://en.wikipedia.org/wiki/CLMUL_instruction_set
fn gf2_128_mul(mut a: u128, b: u128) -> u128 {
let mut m = 0;
for i in 0..128 {
m ^= ((b >> (127 - i)) & 1) * a;
let xor_poly = a & 1;
a >>= 1;
a ^= xor_poly * GCM_POLY;
}
m
}
#[cfg(test)]
mod tests {
use super::{gf2_128_mul, Aes256Gcm, GHash};
#[test]
fn test_gf2_128_mul_inverse() {
let a = 0x66e94bd4ef8a2c3b884cfa59ca342b2eu128;
let b = 0x5e2ec746917062882c85b0685353de37u128;
assert_eq!(gf2_128_mul(a, b), 0xf38cbb1ad69223dcc3457ae5b6b0f885);
}
#[test]
fn test_encrypt_decrypt() {
let expected_tag = [
0x9a, 0x4a, 0x25, 0x79, 0x52, 0x93, 0x1, 0xbc, 0xfb, 0x71, 0xc7, 0x8d, 0x40, 0x60,
0xf5, 0x2c,
];
let expected_ciphertext = [0xe2, 0x7a, 0xbd, 0xd2, 0xd2, 0xa5, 0x3d, 0x2f, 0x13, 0x6b];
let fixed_iv = [
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb,
];
let key = [
0x92, 0xac, 0xe3, 0xe3, 0x48, 0xcd, 0x82, 0x10, 0x92, 0xcd, 0x92, 0x1a, 0xa3, 0x54,
0x63, 0x74, 0x29, 0x9a, 0xb4, 0x62, 0x9, 0x69, 0x1b, 0xc2, 0x8b, 0x87, 0x52, 0xd1,
0x7f, 0x12, 0x3c, 0x20,
];
let aad = [0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff];
let expected_plaintext = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09];
// from https://github.com/C2SP/wycheproof/blob/master/testvectors/aes_gcm_test.json
let (iv, ciphertext, tag) =
Aes256Gcm::encrypt(&key, Some(&fixed_iv), &aad, &expected_plaintext).unwrap();
assert_eq!(&expected_ciphertext[..], &ciphertext);
assert_eq!(expected_tag, tag);
assert_eq!(fixed_iv, iv);
let plaintext =
Aes256Gcm::decrypt(&key, &fixed_iv, &aad, &expected_tag, &expected_ciphertext).unwrap();
assert_eq!(&expected_plaintext[..], plaintext);
}
#[test]
fn test_ghash() {
let key: [u8; 32] = 0xfeffe9928665731c6d6a8f9467308308u128
.to_be_bytes()
.to_vec()
.repeat(2)
.try_into()
.unwrap();
let mut h = GHash::new(&key);
let ct: [u128; 4] = [
0x522dc1f099567d07f47f37a32a84427d,
0x643a8cdcbfe5c0c97598a2bd2555d1aa,
0x8cb08e48590dbb3da7b08b1056828838,
0xc5f61e6393ba7a0abcc9f662898015ad,
];
for c in ct {
h.update(&c.to_be_bytes());
}
h.update(&0x0000_0000_0000_0000_0000_0000_0000_0200u128.to_be_bytes());
let iv = 0xcafebabefacedbaddecaf888u128.to_be_bytes()[4..16]
.try_into()
.unwrap();
let tag = h.finalize(&key, &iv);
assert_eq!(tag, 0xb094dac5d93471bdec1a502270e3cc6cu128.to_be_bytes());
}
#[test]
fn test_ghash2() {
// KEY = f0eaf7b41b42f4500635bc05d9cede11a5363d59a6288870f527bcffeb4d6e04
// IV = 18f316781077a595c72d4c07
// CT = 7a1b61009dce6b7cd4d1ea0203b179f1219dd5ce7407e12ea0a4c56c71bb791b
// AAD = 42cade3a19204b7d4843628c425c2375
// Tag = 4419180b0b963b7289a4fa3f45c535a3
// PT = 400fb5ef32083b3abea957c4f068abad50c8d86bbf9351fa72e7da5171df38f9
const KEY: [u8; 32] = [
0xf0, 0xea, 0xf7, 0xb4, 0x1b, 0x42, 0xf4, 0x50, 0x6, 0x35, 0xbc, 0x5, 0xd9, 0xce, 0xde,
0x11, 0xa5, 0x36, 0x3d, 0x59, 0xa6, 0x28, 0x88, 0x70, 0xf5, 0x27, 0xbc, 0xff, 0xeb,
0x4d, 0x6e, 0x4,
];
let mut h = GHash::new(&KEY);
let ct: [u128; 3] = [
0x42cade3a19204b7d4843628c425c2375,
0x7a1b61009dce6b7cd4d1ea0203b179f1,
0x219dd5ce7407e12ea0a4c56c71bb791b,
];
for c in ct {
h.update(&c.to_be_bytes());
}
h.update(&0x0000_0000_0000_0080_0000_0000_0000_0100u128.to_be_bytes());
let iv = 0x18f316781077a595c72d4c07u128.to_be_bytes()[4..16]
.try_into()
.unwrap();
let tag = h.finalize(&KEY, &iv);
assert_eq!(tag, 0x4419180b0b963b7289a4fa3f45c535a3u128.to_be_bytes());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/ecc384.rs | sw-emulator/lib/crypto/src/ecc384.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
ecc384.rs
Abstract:
File contains implementation of Elliptic Curve Cryptography P-384 (ECC-384) Algorithm.
--*/
use p384::ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier};
use p384::ecdsa::{Signature, SigningKey, VerifyingKey};
use p384::{EncodedPoint, SecretKey};
use rfc6979::HmacDrbg;
use sha2::digest::generic_array::GenericArray;
use sha2::Sha384;
use crate::EndianessTransform;
/// ECC-384 coordinate size in bytes
pub const ECC_384_COORD_SIZE: usize = 48;
/// ECC-384 Coordinate
pub type Ecc384Scalar = [u8; ECC_384_COORD_SIZE];
/// ECC-384 Private Key
pub type Ecc384PrivKey = Ecc384Scalar;
/// ECC-384 Public Key
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Ecc384PubKey {
/// X coordinate
pub x: Ecc384Scalar,
/// Y coordinate
pub y: Ecc384Scalar,
}
impl Default for Ecc384PubKey {
/// Returns the "default value" for a type.
fn default() -> Self {
Self {
x: [0u8; ECC_384_COORD_SIZE],
y: [0u8; ECC_384_COORD_SIZE],
}
}
}
impl From<EncodedPoint> for Ecc384PubKey {
/// Converts to this type from the input type.
fn from(point: EncodedPoint) -> Self {
let mut pub_key = Self::default();
pub_key.x.copy_from_slice(point.x().unwrap());
pub_key.y.copy_from_slice(point.y().unwrap());
pub_key
}
}
impl From<&mut Ecc384PubKey> for EncodedPoint {
/// Converts to this type from the input type.
fn from(key: &mut Ecc384PubKey) -> Self {
EncodedPoint::from_affine_coordinates(
GenericArray::from_slice(&key.x),
GenericArray::from_slice(&key.y),
false,
)
}
}
impl From<Ecc384PubKey> for EncodedPoint {
/// Converts to this type from the input type.
fn from(key: Ecc384PubKey) -> Self {
EncodedPoint::from_affine_coordinates(
GenericArray::from_slice(&key.x),
GenericArray::from_slice(&key.y),
false,
)
}
}
/// ECC-384 Signature
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Ecc384Signature {
/// Random point
pub r: Ecc384Scalar,
/// Proof
pub s: Ecc384Scalar,
}
impl Default for Ecc384Signature {
/// Returns the "default value" for a type.
fn default() -> Self {
Self {
r: [0u8; ECC_384_COORD_SIZE],
s: [0u8; ECC_384_COORD_SIZE],
}
}
}
impl From<Signature> for Ecc384Signature {
/// Converts to this type from the input type.
fn from(ecc_sig: Signature) -> Self {
let mut sig = Self::default();
sig.r.copy_from_slice(ecc_sig.r().to_bytes().as_slice());
sig.s.copy_from_slice(ecc_sig.s().to_bytes().as_slice());
sig
}
}
impl From<&mut Ecc384Signature> for Signature {
/// Converts to this type from the input type.
fn from(signature: &mut Ecc384Signature) -> Self {
Signature::from_scalars(
GenericArray::clone_from_slice(&signature.r),
GenericArray::clone_from_slice(&signature.s),
)
.unwrap()
}
}
impl From<Ecc384Signature> for Signature {
/// Converts to this type from the input type.
fn from(signature: Ecc384Signature) -> Self {
Signature::from_scalars(
GenericArray::clone_from_slice(&signature.r),
GenericArray::clone_from_slice(&signature.s),
)
.unwrap()
}
}
pub enum Ecc384 {}
impl Ecc384 {
/// Compute a shared secret using ECDH
///
/// # Arguments
///
/// * `priv_key` - Private key
/// * `pub_key` - Public key
///
/// # Result
///
/// * Ecc384Scalar - Shared secret
pub fn compute_shared_secret(priv_key: &Ecc384PrivKey, pub_key: &Ecc384PubKey) -> Ecc384Scalar {
// Private key and public key are received as a list of big-endian DWORDs. Changing them to little-endian.
let mut priv_key_reversed = *priv_key;
let mut pub_key_reversed = *pub_key;
priv_key_reversed.to_little_endian();
pub_key_reversed.x.to_little_endian();
pub_key_reversed.y.to_little_endian();
// Convert to p384 types
let secret_key = SecretKey::from_slice(&priv_key_reversed).unwrap();
let verifying_key =
VerifyingKey::from_encoded_point(&EncodedPoint::from(pub_key_reversed)).unwrap();
// Compute shared secret using ECDH
// We use the public key point and multiply it by our private key scalar
let shared_secret =
p384::ecdh::diffie_hellman(secret_key.to_nonzero_scalar(), verifying_key.as_affine());
// Use the x-coordinate as the shared secret
let mut result = [0u8; ECC_384_COORD_SIZE];
result.copy_from_slice(shared_secret.raw_secret_bytes().as_slice());
result.to_big_endian();
result
}
/// Generate a deterministic ECC private & public key pair based on the seed
///
/// # Arguments
///
/// * `Seed` - The seed used to derive the deterministic key
///
/// # Result
///
/// * (Ecc384PrivKey, Ecc384PubKey) - Private & public key pair
pub fn gen_key_pair(
seed: &Ecc384Scalar,
nonce: &Ecc384Scalar,
) -> (Ecc384PrivKey, Ecc384PubKey) {
let mut priv_key = [0u8; ECC_384_COORD_SIZE];
// Seed is received as a list of big-endian DWORDs. Changing them to little-endian.
let mut seed_reversed = *seed;
seed_reversed.to_little_endian();
// Nonce is received as a list of big-endian DWORDs. Changing them to little-endian.
let mut nonce_reversed = *nonce;
nonce_reversed.to_little_endian();
let mut drbg = HmacDrbg::<Sha384>::new(&seed_reversed, &nonce_reversed, &[]);
drbg.fill_bytes(&mut priv_key);
let signing_key = SigningKey::from_slice(&priv_key).unwrap();
let verifying_key = signing_key.verifying_key();
let ecc_point = verifying_key.to_encoded_point(false);
let mut pub_key: Ecc384PubKey = ecc_point.into();
// Changing the DWORD endianess of the private and public keys to big-endian.
priv_key.to_big_endian();
pub_key.x.to_big_endian();
pub_key.y.to_big_endian();
(priv_key, pub_key)
}
/// Sign the hash with specified private key
///
/// # Arguments
///
/// * `priv_key` - Private key
/// * `hash` - Hash to sign
///
/// # Result
///
/// * Ecc384Signature - Signature
pub fn sign(priv_key: &Ecc384PrivKey, hash: &Ecc384Scalar) -> Ecc384Signature {
// Private key and hash are received as a list of big-endian DWORDs. Changing them to little-endian.
let mut priv_key_reversed = *priv_key;
let mut hash_reversed = *hash;
priv_key_reversed.to_little_endian();
hash_reversed.to_little_endian();
let signing_key = SigningKey::from_slice(&priv_key_reversed).unwrap();
let ecc_sig: Signature = signing_key.sign_prehash(&hash_reversed).unwrap();
let mut signature: Ecc384Signature = ecc_sig.into();
// Changing the DWORD endianess of the signature to big-endian.
signature.r.to_big_endian();
signature.s.to_big_endian();
signature
}
/// Verify the signature
///
/// # Arguments
///
/// * `pub_key` - Public key
/// * `hash` - Hash to sign
/// * `signature` - Signature to verify
///
/// # Result
///
/// * Ecc384Scalar - The 'r' value from signature verification calculation
pub fn verify(
pub_key: &Ecc384PubKey,
hash: &Ecc384Scalar,
signature: &Ecc384Signature,
) -> Ecc384Scalar {
// Public key, hash and signature are received as a list of big-endian DWORDs. Changing them to little-endian.
let mut pub_key_reversed = *pub_key;
pub_key_reversed.x.to_little_endian();
pub_key_reversed.y.to_little_endian();
let mut hash_reversed = *hash;
hash_reversed.to_little_endian();
let mut signature_reversed = *signature;
signature_reversed.r.to_little_endian();
signature_reversed.s.to_little_endian();
let verifying_key = VerifyingKey::from_encoded_point(&pub_key_reversed.into()).unwrap();
let result =
verifying_key.verify_prehash(&hash_reversed, &Signature::from(signature_reversed));
if result.is_ok() {
signature.r
} else {
// Note: We do not have access to the failed 'r'. Hence we reverse the original 'r'
// value and flip the bits of each byte. This implementation should be good for
// emulating the ECC-384 hardware
let mut r = signature.r;
r.iter_mut().for_each(|r| *r = !*r);
r
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const PRIV_KEY: [u8; 48] = [
0xF2, 0x74, 0xF6, 0x9D, 0x16, 0x3B, 0x0C, 0x9F, 0x1F, 0xC3, 0xEB, 0xF4, 0x29, 0x2A, 0xD1,
0xC4, 0xEB, 0x3C, 0xEC, 0x1C, 0x5A, 0x7D, 0xDE, 0x6F, 0x80, 0xC1, 0x42, 0x92, 0x93, 0x4C,
0x20, 0x55, 0xE0, 0x87, 0x74, 0x8D, 0x0A, 0x16, 0x9C, 0x77, 0x24, 0x83, 0xAD, 0xEE, 0x5E,
0xE7, 0x0E, 0x17,
];
const PUB_KEY_X: [u8; 48] = [
0xD7, 0x9C, 0x6D, 0x97, 0x2B, 0x34, 0xA1, 0xDF, 0xC9, 0x16, 0xA7, 0xB6, 0xE0, 0xA9, 0x9B,
0x6B, 0x53, 0x87, 0xB3, 0x4D, 0xA2, 0x18, 0x76, 0x07, 0xC1, 0xAD, 0x0A, 0x4D, 0x1A, 0x8C,
0x2E, 0x41, 0x72, 0xAB, 0x5F, 0xA5, 0xD9, 0xAB, 0x58, 0xFE, 0x45, 0xE4, 0x3F, 0x56, 0xBB,
0xB6, 0x6B, 0xA4,
];
const PUB_KEY_Y: [u8; 48] = [
0x5A, 0x73, 0x63, 0x93, 0x2B, 0x06, 0xB4, 0xF2, 0x23, 0xBE, 0xF0, 0xB6, 0x0A, 0x63, 0x90,
0x26, 0x51, 0x12, 0xDB, 0xBD, 0x0A, 0xAE, 0x67, 0xFE, 0xF2, 0x6B, 0x46, 0x5B, 0xE9, 0x35,
0xB4, 0x8E, 0x45, 0x1E, 0x68, 0xD1, 0x6F, 0x11, 0x18, 0xF2, 0xB3, 0x2B, 0x4C, 0x28, 0x60,
0x87, 0x49, 0xED,
];
const SEED: [u8; 48] = [
0x8F, 0xA8, 0x54, 0x1C, 0x82, 0xA3, 0x92, 0xCA, 0x74, 0xF2, 0x3E, 0xD1, 0xDB, 0xFD, 0x73,
0x54, 0x1C, 0x59, 0x66, 0x39, 0x1B, 0x97, 0xEA, 0x73, 0xD7, 0x44, 0xB0, 0xE3, 0x4B, 0x9D,
0xF5, 0x9E, 0xD0, 0x15, 0x80, 0x63, 0xE3, 0x9C, 0x09, 0xA5, 0xA0, 0x55, 0x37, 0x1E, 0xDF,
0x7A, 0x54, 0x41,
];
const NONCE: [u8; 48] = [
0x1B, 0x7E, 0xC5, 0xE5, 0x48, 0xE8, 0xAA, 0xA9, 0x2E, 0xC7, 0x70, 0x97, 0xCA, 0x95, 0x51,
0xC9, 0x78, 0x3C, 0xE6, 0x82, 0xCA, 0x18, 0xFB, 0x1E, 0xDB, 0xD9, 0xF1, 0xE5, 0x0B, 0xC3,
0x82, 0xDB, 0x8A, 0xB3, 0x94, 0x96, 0xC8, 0xEE, 0x42, 0x3F, 0x8C, 0xA1, 0x05, 0xCB, 0xBA,
0x7B, 0x65, 0x88,
];
const SIGNATURE_R: [u8; 48] = [
0x87, 0x1E, 0x6E, 0xA4, 0xDD, 0xC5, 0x43, 0x2C, 0xDD, 0xAA, 0x60, 0xFD, 0x7F, 0x05, 0x54,
0x72, 0xD3, 0xC4, 0xDD, 0x41, 0xA5, 0xBF, 0xB2, 0x67, 0x09, 0xE8, 0x8C, 0x31, 0x1A, 0x97,
0x09, 0x35, 0x99, 0xA7, 0xC8, 0xF5, 0x5B, 0x39, 0x74, 0xC1, 0x9E, 0x4F, 0x5A, 0x7B, 0xFC,
0x1D, 0xD2, 0xAC,
];
const MESSAGE: [u8; 48] = [
0xC8, 0xF5, 0x18, 0xD4, 0xF3, 0xAA, 0x1B, 0xD4, 0x6E, 0xD5, 0x6C, 0x1C, 0x3C, 0x9E, 0x16,
0xFB, 0x80, 0x0A, 0xF5, 0x04, 0xDB, 0x98, 0x84, 0x35, 0x48, 0xC5, 0xF6, 0x23, 0xEE, 0x11,
0x5F, 0x73, 0xD4, 0xC6, 0x2A, 0xBC, 0x06, 0xD3, 0x03, 0xB5, 0xD9, 0x0D, 0x9A, 0x17, 0x50,
0x87, 0x29, 0x0D,
];
const SIGNATURE_S: [u8; 48] = [
0x3E, 0x55, 0x52, 0xDE, 0x64, 0x03, 0x35, 0x0E, 0xE7, 0x0A, 0xD7, 0x4E, 0x4B, 0x85, 0x4D,
0x2D, 0xC4, 0x12, 0x6B, 0xBF, 0x9C, 0x15, 0x3A, 0x5D, 0x7A, 0x07, 0xBD, 0x4B, 0x85, 0xD0,
0x6E, 0x45, 0xF8, 0x50, 0x92, 0x0E, 0x89, 0x8F, 0xB7, 0xD3, 0x4F, 0x80, 0x79, 0x6D, 0xAE,
0x29, 0x36, 0x5C,
];
#[test]
fn test_gen_key_pair() {
let mut seed = SEED;
seed.to_big_endian();
let mut nonce = NONCE;
nonce.to_big_endian();
let (mut priv_key, mut pub_key) = Ecc384::gen_key_pair(&seed, &nonce);
priv_key.to_little_endian();
pub_key.x.to_little_endian();
pub_key.y.to_little_endian();
assert_eq!(priv_key, PRIV_KEY);
assert_eq!(pub_key.x, PUB_KEY_X);
assert_eq!(pub_key.y, PUB_KEY_Y);
}
#[test]
fn test_sign() {
let mut hash = MESSAGE;
hash.to_big_endian();
let mut priv_key = PRIV_KEY;
priv_key.to_big_endian();
let mut signature = Ecc384::sign(&priv_key, &hash);
signature.r.to_little_endian();
signature.s.to_little_endian();
assert_eq!(signature.r, SIGNATURE_R);
assert_eq!(signature.s, SIGNATURE_S);
}
#[test]
fn test_verify() {
let hash = [0u8; 48];
let mut priv_key = PRIV_KEY;
priv_key.to_big_endian();
let mut signature = Ecc384::sign(&priv_key, &hash);
let mut pub_key_x = PUB_KEY_X;
let mut pub_key_y = PUB_KEY_Y;
pub_key_x.to_big_endian();
pub_key_y.to_big_endian();
let pub_key = Ecc384PubKey {
x: pub_key_x,
y: pub_key_y,
};
let mut r = Ecc384::verify(&pub_key, &hash, &signature);
r.to_little_endian();
signature.r.to_little_endian();
assert_eq!(r, signature.r)
}
#[test]
fn test_verify_fail() {
let hash = [0u8; 48];
let mut priv_key = PRIV_KEY;
priv_key.to_big_endian();
let mut signature = Ecc384::sign(&priv_key, &hash);
let mut pub_key_x = PUB_KEY_X;
let mut pub_key_y = PUB_KEY_Y;
pub_key_x.to_big_endian();
pub_key_y.to_big_endian();
let pub_key = Ecc384PubKey {
x: pub_key_x,
y: pub_key_y,
};
let hash = [0xFFu8; 48];
let mut r = Ecc384::verify(&pub_key, &hash, &signature);
r.to_little_endian();
signature.r.to_little_endian();
assert_ne!(r, signature.r)
}
#[test]
fn test_shared_secret() {
// Generate two key pairs
let seed1 = [1u8; 48];
let nonce1 = [2u8; 48];
let (priv_key1, pub_key1) = Ecc384::gen_key_pair(&seed1, &nonce1);
let seed2 = [3u8; 48];
let nonce2 = [4u8; 48];
let (priv_key2, pub_key2) = Ecc384::gen_key_pair(&seed2, &nonce2);
// Compute shared secrets from both sides
let shared1 = Ecc384::compute_shared_secret(&priv_key1, &pub_key2);
let shared2 = Ecc384::compute_shared_secret(&priv_key2, &pub_key1);
// Both sides should compute the same shared secret
assert_eq!(shared1, shared2);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/lib.rs | sw-emulator/lib/crypto/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains exports for for Caliptra Emulator Crypto library.
--*/
mod aes256cbc;
mod aes256ctr;
mod aes256gcm;
mod ecc384;
mod helpers;
mod hmac512;
mod sha256;
mod sha3;
mod sha512;
pub use sha256::Sha256;
pub use sha256::Sha256Mode;
pub use sha512::Sha512;
pub use sha512::Sha512Mode;
pub use sha3::{Sha3, Sha3Mode, Sha3Strength};
pub use hmac512::{Hmac512, Hmac512Interface, Hmac512Mode};
pub use ecc384::Ecc384;
pub use ecc384::Ecc384PrivKey;
pub use ecc384::Ecc384PubKey;
pub use ecc384::Ecc384Signature;
pub const AES_256_BLOCK_SIZE: usize = 16;
pub const AES_256_KEY_SIZE: usize = 32;
pub use aes256cbc::Aes256Cbc;
pub use aes256ctr::Aes256Ctr;
pub use aes256gcm::{Aes256Gcm, GHash};
pub use helpers::EndianessTransform;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/sha3.rs | sw-emulator/lib/crypto/src/sha3.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha3.rs
Abstract:
File contains implementation of Secure Hash 3 Algorithm (SHA-3)
--*/
// use crate::helpers::EndianessTransform;
use sha3::{
digest::{ExtendableOutput, Update, XofReader},
Shake256,
};
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Sha3Mode {
SHA3 = 0x0,
SHAKE = 0x2,
}
impl From<Sha3Mode> for u32 {
/// Converts to this type from the input type.
fn from(mode: Sha3Mode) -> Self {
mode as Self
}
}
impl From<u32> for Sha3Mode {
/// Converts to this type from the input type.
fn from(value: u32) -> Self {
match value {
0x0 => Sha3Mode::SHA3,
0x2 => Sha3Mode::SHAKE,
_ => panic!("Invalid mode"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Sha3Strength {
L128 = 0x0,
L224 = 0x1,
L256 = 0x2,
L384 = 0x3,
L512 = 0x4,
}
impl From<Sha3Strength> for u32 {
/// Converts to this type from the input type.
fn from(strength: Sha3Strength) -> Self {
strength as Self
}
}
impl From<u32> for Sha3Strength {
/// Converts to this type from the input type.
fn from(value: u32) -> Self {
match value {
0x0 => Sha3Strength::L128,
0x1 => Sha3Strength::L224,
0x2 => Sha3Strength::L256,
0x3 => Sha3Strength::L384,
0x4 => Sha3Strength::L512,
_ => panic!("Invalid strength"),
}
}
}
const DIGEST_SIZE: usize = 200;
/// SHA-3
pub struct Sha3 {
/// Hasher
hasher: Option<Shake256>,
/// Output digest
digest: [u8; DIGEST_SIZE],
}
impl Default for Sha3 {
fn default() -> Self {
Self::new()
}
}
impl Sha3 {
/// Create a new instance of Secure Hash Algorithm object
///
/// # Arguments
///
/// * `mode` - Mode of the SHA Operation
/// * `strength` - Strength of SHA Operation
pub fn new() -> Self {
Self {
hasher: None,
digest: [0u8; DIGEST_SIZE],
}
}
/// Set hashing algorithm.
pub fn set_hasher(&mut self, mode: Sha3Mode, strength: Sha3Strength) {
if mode != Sha3Mode::SHAKE || strength != Sha3Strength::L256 {
todo!("Only SHAKE256 implemented currently");
}
self.hasher = Some(Shake256::default());
}
/// Write data to hasher.
pub fn update(&mut self, data: &[u8]) -> bool {
if let Some(ref mut hasher) = &mut self.hasher {
hasher.update(data);
return true;
}
false
}
/// Write hash to digest.
pub fn finalize(&mut self) -> bool {
if let Some(hasher) = &self.hasher {
let mut reader = hasher.clone().finalize_xof();
reader.read(&mut self.digest);
return true;
}
false
}
pub fn digest(&self) -> [u8; DIGEST_SIZE] {
self.digest
}
pub fn has_hasher(&self) -> bool {
self.hasher.is_some()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn test_invalid_mode() {
let mut sha3 = Sha3::new();
sha3.set_hasher(Sha3Mode::SHA3, Sha3Strength::L256);
}
#[test]
fn test_shake256() {
let mut shake = Sha3::new();
shake.set_hasher(Sha3Mode::SHAKE, Sha3Strength::L256);
shake.update(b"abc");
shake.finalize();
assert!(shake.digest.iter().any(|n| *n != 0));
}
#[test]
fn test_shake256_kat() {
let mut shake = Sha3::new();
shake.set_hasher(Sha3Mode::SHAKE, Sha3Strength::L256);
shake.update(&[0xEF, 0xBE, 0xAD, 0xDE]);
shake.finalize();
let expected = [
0x5e, 0xf7, 0xcc, 0xa6, 0x1e, 0xd4, 0x44, 0x74, 0xcc, 0x56, 0x82, 0x73, 0x7e, 0x25,
0x75, 0xf8, 0xc5, 0x9a, 0x56, 0x5d, 0xa8, 0xab, 0x5b, 0x29, 0x44, 0x75, 0xb2, 0x6e,
0x76, 0x79, 0x79, 0xe5, 0x4d, 0x0c, 0x37, 0x51, 0x0b, 0xb4, 0x3b, 0x6d, 0x5e, 0x48,
0xba, 0xae, 0x48, 0x56, 0x75, 0xc1, 0x40, 0x6d, 0x6d, 0x8b, 0x57, 0x45, 0x6f, 0x6c,
0x87, 0x08, 0xfb, 0x6e, 0x36, 0x3d, 0x8a, 0x56, 0xa4, 0xae, 0x90, 0xff, 0x72, 0x30,
0x06, 0x14, 0x2a, 0x72, 0x87, 0x4f, 0xc6, 0x31, 0x21, 0xbf, 0xe5, 0x26, 0xda, 0x23,
0xe7, 0x64, 0xe0, 0xf8, 0xa5, 0x4a, 0x49, 0xe3, 0x6f, 0x05, 0xe6, 0x22, 0x9f, 0x21,
0x67, 0xdf, 0xb8, 0xef, 0xa9, 0x69, 0x2f, 0x8a, 0xc6, 0xa6, 0x87, 0x84, 0x68, 0x39,
0x04, 0x7b, 0x82, 0xcb, 0x55, 0x00, 0x95, 0x41, 0x28, 0x19, 0x51, 0x57, 0xf3, 0xc8,
0x71, 0xaa, 0x97, 0x0e, 0x7c, 0xc6, 0x43, 0x66, 0x7e, 0xe2, 0xab, 0xe9, 0xc1, 0x3e,
0x05, 0xc3, 0xaf, 0x69, 0xb1, 0x0d, 0x3e, 0x35, 0xb0, 0x1d, 0x1b, 0x8d, 0x02, 0x32,
0xcd, 0x05, 0xb8, 0x7b, 0x7c, 0x38, 0x9c, 0xe5, 0x58, 0xdb, 0x66, 0x1c, 0xe4, 0x79,
0xc5, 0x51, 0x44, 0x2d, 0x0f, 0xeb, 0x7e, 0x8d, 0x9b, 0x7a, 0x2b, 0x5e, 0xf8, 0x78,
0xe5, 0xad, 0xc1, 0xfd, 0x31, 0x70, 0xcf, 0xf0, 0x3e, 0x04, 0x15, 0x6b, 0x3e, 0x27,
0xe3, 0xb8, 0x6d, 0x4f,
];
assert_eq!(shake.digest, expected);
}
#[test]
fn test_unset_hasher() {
let mut shake = Sha3::new();
let res = shake.update(b"abc");
assert!(!res);
shake.finalize();
assert!(shake.digest.iter().all(|n| *n == 0));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/helpers.rs | sw-emulator/lib/crypto/src/helpers.rs | // Licensed under the Apache-2.0 license
// TODO: These names need to make it clearer what they're actually doing. It's
// swapping the bytes of every 4-byte chunk, regardless of the element type.
pub trait EndianessTransform {
fn change_endianess(&mut self);
fn to_big_endian(&mut self);
fn to_little_endian(&mut self);
}
impl EndianessTransform for [u8] {
fn change_endianess(&mut self) {
for idx in (0..self.len()).step_by(4) {
self.swap(idx, idx + 3);
self.swap(idx + 1, idx + 2);
}
}
fn to_big_endian(&mut self) {
self.change_endianess();
}
fn to_little_endian(&mut self) {
self.change_endianess();
}
}
impl EndianessTransform for [u32] {
fn change_endianess(&mut self) {
for val in self.iter_mut() {
*val = val.swap_bytes();
}
}
fn to_big_endian(&mut self) {
self.change_endianess();
}
fn to_little_endian(&mut self) {
self.change_endianess();
}
}
impl EndianessTransform for [u64] {
fn change_endianess(&mut self) {
for val in self.iter_mut() {
let msd_be = ((*val >> 32) as u32).swap_bytes();
let lsd_be = ((*val & 0xFFFFFFFF) as u32).swap_bytes();
*val = ((msd_be as u64) << 32) | lsd_be as u64;
}
}
fn to_big_endian(&mut self) {
self.change_endianess();
}
fn to_little_endian(&mut self) {
self.change_endianess();
}
}
#[cfg(test)]
mod test {
use crate::EndianessTransform;
#[test]
fn test_change_endianness_u8() {
let mut val = [0x11_u8, 0x22, 0x33, 0x44, 0x99, 0xaa, 0xbb, 0xcc];
val.change_endianess();
assert_eq!([0x44, 0x33, 0x22, 0x11, 0xcc, 0xbb, 0xaa, 0x99], val);
}
#[test]
fn test_change_endianness_u32() {
let mut val = [0x1122_3344_u32, 0x99aa_bbcc];
val.change_endianess();
assert_eq!([0x4433_2211, 0xccbb_aa99], val);
}
#[test]
fn test_change_endianness_u64() {
let mut val = [0x1122_3344_5566_7788_u64, 0x99aa_bbcc_ddee_ff00];
val.change_endianess();
assert_eq!([0x4433_2211_8877_6655, 0xccbb_aa99_00ff_eedd], val);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/aes256ctr.rs | sw-emulator/lib/crypto/src/aes256ctr.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
aes256ctr.rs
Abstract:
File contains implementation of AES-256 CTR algorithm
--*/
use crate::{AES_256_BLOCK_SIZE, AES_256_KEY_SIZE};
use aes::Aes256;
use cipher::{KeyIvInit, StreamCipherCore};
pub struct Aes256Ctr {
cryptor: Ctr,
}
impl Default for Aes256Ctr {
fn default() -> Self {
Self::new(&[0u8; AES_256_IV_SIZE], &[0u8; AES_256_KEY_SIZE])
}
}
const AES_256_IV_SIZE: usize = AES_256_BLOCK_SIZE;
type Ctr = ctr::CtrCore<Aes256, ctr::flavors::Ctr128BE>;
impl Aes256Ctr {
pub fn new(iv: &[u8; AES_256_IV_SIZE], key: &[u8; AES_256_KEY_SIZE]) -> Self {
Self {
cryptor: Ctr::new(key.into(), iv.into()),
}
}
/// Streaming mode: encrypt or decrypt a single block and return the output.
pub fn crypt_block(&mut self, block: &[u8; AES_256_BLOCK_SIZE]) -> [u8; AES_256_BLOCK_SIZE] {
let mut out_block = [(*block).into()];
self.cryptor.apply_keystream_blocks(&mut out_block);
out_block[0].into()
}
}
#[cfg(test)]
mod tests {
use crate::{Aes256Ctr, AES_256_BLOCK_SIZE};
#[test]
fn test_encrypt_decrypt() {
let mut ctr = Aes256Ctr::new(&[0u8; 16], &[0u8; 32]);
let plaintext: [u8; 48] = [
0xdc, 0x95, 0xc0, 0x78, 0xa2, 0x40, 0x89, 0x89, 0xad, 0x48, 0xa2, 0x14, 0x92, 0x84,
0x20, 0x87, 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9, 0xa9, 0x63, 0xb4, 0xf1,
0xc4, 0xcb, 0x73, 0x8b, 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e,
0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18,
];
for pblock in plaintext.chunks_exact(AES_256_BLOCK_SIZE) {
assert_eq!(pblock, ctr.crypt_block(&[0u8; AES_256_BLOCK_SIZE]));
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/sha512.rs | sw-emulator/lib/crypto/src/sha512.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha512.rs
Abstract:
File contains implementation of Secure Hash 512 Algorithm (SHA-512)
--*/
use crate::helpers::EndianessTransform;
use sha2::digest::block_buffer::Block;
use sha2::digest::consts::U128;
/// SHA-512 Mode
#[derive(Debug, Copy, Clone)]
pub enum Sha512Mode {
Sha224,
Sha256,
Sha384,
Sha512,
}
impl From<Sha512Mode> for u32 {
/// Converts to this type from the input type.
fn from(sha_mode: Sha512Mode) -> Self {
sha_mode as Self
}
}
/// SHA-512
pub struct Sha512 {
/// Hash
hash: [u64; 8],
/// SHA 512 Mode
mode: Sha512Mode,
/// Partial block to be processed
partial_block: Vec<u8>,
/// Number of full blocks processed to create hash
blocks_processed: usize,
}
impl Sha512 {
/// SHA-512 Block Size
pub const BLOCK_SIZE: usize = 128;
/// SHA-512 Hash Size
pub const HASH_SIZE: usize = 64;
/// SHA-512-224 Initial Hash Vectors
const HASH_IV_224: [u64; 8] = [
0x8c3d37c819544da2,
0x73e1996689dcd4d6,
0x1dfab7ae32ff9c82,
0x679dd514582f9fcf,
0x0f6d2b697bd44da8,
0x77e36f7304c48942,
0x3f9d85a86a1d36c8,
0x1112e6ad91d692a1,
];
/// SHA-512-256 Initial Hash Vectors
const HASH_IV_256: [u64; 8] = [
0x22312194fc2bf72c,
0x9f555fa3c84c64c2,
0x2393b86b6f53b151,
0x963877195940eabd,
0x96283ee2a88effe3,
0xbe5e1e2553863992,
0x2b0199fc2c85b8aa,
0x0eb72ddc81c52ca2,
];
/// SHA-384 Initial Hash Vectors
const HASH_IV_384: [u64; 8] = [
0xcbbb9d5dc1059ed8,
0x629a292a367cd507,
0x9159015a3070dd17,
0x152fecd8f70e5939,
0x67332667ffc00b31,
0x8eb44a8768581511,
0xdb0c2e0d64f98fa7,
0x47b5481dbefa4fa4,
];
/// SHA-512 Initial Hash Vectors
const HASH_IV_512: [u64; 8] = [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179,
];
/// Create a new instance of Secure Hash Algorithm object
///
/// # Arguments
///
/// * `mode` - Mode of the SHA Operation
pub fn new(mode: Sha512Mode) -> Self {
Self {
hash: Self::hash_iv(mode),
mode,
partial_block: vec![],
blocks_processed: 0,
}
}
pub fn set_hash(&mut self, hash: &[u8]) {
let mut hash = Vec::from(hash);
hash.to_big_endian();
for i in 0..Self::HASH_SIZE / 8 {
self.hash[i] = u64::from_be_bytes(hash[i * 8..(i + 1) * 8].try_into().unwrap());
}
}
/// Reset the state
pub fn reset(&mut self, mode: Sha512Mode) {
self.mode = mode;
self.hash = Self::hash_iv(self.mode);
self.blocks_processed = 0;
}
/// Update the hash
///
/// # Arguments
///
/// * `block` - Block to compress. Each word in `block` is expected to
/// be little-endian
pub fn update(&mut self, block: &[u8; Self::BLOCK_SIZE]) {
let mut block = *Block::<U128>::from_slice(block);
block.to_big_endian();
sha2::compress512(&mut self.hash, &[block]);
self.blocks_processed += 1;
}
/// Update the hash with an arbitrary number of bytes
///
/// `bytes` is expected to be big-endian data.
/// `dlen` may be specified when `bytes` can have undesired padding.
/// `dlen` is expected to be the total number of bytes to hash.
pub fn update_bytes(&mut self, bytes: &[u8], dlen: Option<u32>) {
self.partial_block.extend_from_slice(bytes);
let total_received_bytes =
self.blocks_processed * Self::BLOCK_SIZE + self.partial_block.len();
if let Some(dlen) = dlen {
if total_received_bytes > dlen as usize {
// TODO: can panic if `update_bytes` is used wrong
// (e.g. calling `update_bytes` with a dlen that would remove more bytes than BLOCK_SIZE)
let to_remove =
(self.partial_block.len() - (total_received_bytes - dlen as usize))..;
self.partial_block.drain(to_remove);
}
}
while self.partial_block.len() >= Self::BLOCK_SIZE {
// Safe to unwrap becasue slice is guaranteed to be correct size
self.partial_block[..Self::BLOCK_SIZE].to_little_endian();
self.update(&self.partial_block[..Self::BLOCK_SIZE].try_into().unwrap());
self.partial_block.drain(..Self::BLOCK_SIZE);
}
}
/// Finalize the hash by adding padding
pub fn finalize(&mut self, dlen: u32) {
// Check if dlen is less than the amount of data streamed
// TODO: What to do if dlen is less than the blocks we've already processed?
let bytes_of_blocks = self.blocks_processed * Self::BLOCK_SIZE;
let partial = if (dlen as usize) < bytes_of_blocks + self.partial_block.len() {
(dlen as usize) - bytes_of_blocks
} else {
self.partial_block.len()
};
let msg_len = (self.blocks_processed * Self::BLOCK_SIZE) + partial;
self.partial_block.resize(partial, 0);
self.partial_block.push(0b1000_0000);
let zeros: usize = Self::BLOCK_SIZE - ((msg_len + 1 + 16) % 128);
self.partial_block.extend_from_slice(&vec![0u8; zeros]);
// Add bit length of hashed data
self.partial_block
.extend_from_slice(&((msg_len * 8) as u128).to_be_bytes());
// update function expects little endian words
self.partial_block.to_little_endian();
while self.partial_block.len() >= Self::BLOCK_SIZE {
// Safe to unwrap becasue slice is guaranteed to be correct size
self.update(&self.partial_block[..Self::BLOCK_SIZE].try_into().unwrap());
self.partial_block.drain(..Self::BLOCK_SIZE);
}
}
/// Retrieve the hash
///
/// # Arguments
///
/// * `hash` - Hash to copy
pub fn copy_hash(&self, hash: &mut [u8]) {
// Return the hash as a list of big-endian DWORDs.
let mut hash_be: [u64; 8] = self.hash;
hash_be.to_big_endian();
hash_be
.iter()
.flat_map(|i| i.to_be_bytes())
.take(std::cmp::min(hash.len(), Self::HASH_SIZE))
.zip(hash)
.for_each(|(src, dest)| *dest = src);
}
/// Get the length of the hash
pub fn hash_len(&self) -> usize {
match self.mode {
Sha512Mode::Sha224 => 28,
Sha512Mode::Sha256 => 32,
Sha512Mode::Sha384 => 48,
Sha512Mode::Sha512 => 64,
}
}
/// Retrieve the hash initialization vector for specified SHA mode
///
/// # Arguments
///
/// * `mode` - Mode of the SHA Operation
///
/// # Returns
///
/// * `[u64; 8]` - The initialization vector
fn hash_iv(mode: Sha512Mode) -> [u64; 8] {
match mode {
Sha512Mode::Sha224 => Self::HASH_IV_224,
Sha512Mode::Sha256 => Self::HASH_IV_256,
Sha512Mode::Sha384 => Self::HASH_IV_384,
Sha512Mode::Sha512 => Self::HASH_IV_512,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const SHA_512_TEST_BLOCK: [u8; 128] = [
0x61, 0x62, 0x63, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18,
];
#[test]
fn test_sha512_224() {
let mut sha_512_test_block_var = SHA_512_TEST_BLOCK;
sha_512_test_block_var.to_big_endian();
let mut sha = Sha512::new(Sha512Mode::Sha224);
sha.update(&sha_512_test_block_var);
let expected: [u8; 28] = [
0x46, 0x34, 0x27, 0x0F, 0x70, 0x7B, 0x6A, 0x54, 0xDA, 0xAE, 0x75, 0x30, 0x46, 0x08,
0x42, 0xE2, 0x0E, 0x37, 0xED, 0x26, 0x5C, 0xEE, 0xE9, 0xA4, 0x3E, 0x89, 0x24, 0xAA,
];
let mut hash = [0u8; 28];
sha.copy_hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
#[test]
fn test_sha512_256() {
let mut sha_512_test_block_var = SHA_512_TEST_BLOCK;
sha_512_test_block_var.to_big_endian();
let mut sha = Sha512::new(Sha512Mode::Sha256);
sha.update(&sha_512_test_block_var);
let expected: [u8; 32] = [
0x53, 0x04, 0x8E, 0x26, 0x81, 0x94, 0x1E, 0xF9, 0x9B, 0x2E, 0x29, 0xB7, 0x6B, 0x4C,
0x7D, 0xAB, 0xE4, 0xC2, 0xD0, 0xC6, 0x34, 0xFC, 0x6D, 0x46, 0xE0, 0xE2, 0xF1, 0x31,
0x07, 0xE7, 0xAF, 0x23,
];
let mut hash = [0u8; 32];
sha.copy_hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
#[test]
fn test_sha384() {
let mut sha_512_test_block_var = SHA_512_TEST_BLOCK;
sha_512_test_block_var.to_big_endian();
let mut sha = Sha512::new(Sha512Mode::Sha384);
sha.update(&sha_512_test_block_var);
let expected: [u8; 48] = [
0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B, 0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6,
0x50, 0x07, 0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63, 0x1A, 0x8B, 0x60, 0x5A,
0x43, 0xFF, 0x5B, 0xED, 0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23, 0x58, 0xBA,
0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7,
];
let mut hash = [0u8; 48];
sha.copy_hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
#[test]
fn test_finalize_sha384() {
let mut sha = Sha512::new(Sha512Mode::Sha384);
sha.update_bytes(&SHA_512_TEST_BLOCK, None);
sha.finalize(128);
let expected: [u8; 48] = [
0x3e, 0x16, 0x50, 0xca, 0x72, 0x6e, 0x44, 0x7e, 0xca, 0xdf, 0x8f, 0xa9, 0xe5, 0xd2,
0xb9, 0x81, 0x02, 0x9d, 0x5a, 0x76, 0xfc, 0x2c, 0x68, 0xa9, 0xdb, 0x34, 0x1e, 0xa1,
0x3d, 0x01, 0xc7, 0xff, 0x7e, 0x82, 0x7f, 0x0f, 0x6a, 0x62, 0xde, 0x5a, 0x6f, 0xa3,
0x2f, 0xcd, 0xa2, 0x3e, 0xb8, 0x3b,
];
let mut hash = [0u8; 48];
sha.copy_hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
#[test]
fn test_finalize_127byte_sha384() {
let mut sha = Sha512::new(Sha512Mode::Sha384);
sha.update_bytes(&SHA_512_TEST_BLOCK, Some(127));
sha.finalize(127);
let expected: [u8; 48] = [
0x4e, 0x12, 0xac, 0x25, 0xbf, 0xad, 0xf7, 0x25, 0x5c, 0xb7, 0x9a, 0x06, 0x3d, 0x83,
0x45, 0x4f, 0x87, 0x9b, 0x89, 0x70, 0x13, 0x0f, 0xa4, 0xf1, 0xed, 0xcc, 0xbd, 0xee,
0xd2, 0x22, 0x6e, 0x6d, 0xcd, 0x36, 0xcb, 0x11, 0x6c, 0x9b, 0x1a, 0x41, 0x6b, 0x4b,
0xbb, 0x62, 0x45, 0xe1, 0x79, 0xfd,
];
let mut hash = [0u8; 48];
sha.copy_hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
#[test]
fn test_sha512() {
let mut sha_512_test_block_var = SHA_512_TEST_BLOCK;
sha_512_test_block_var.to_big_endian();
let mut sha = Sha512::new(Sha512Mode::Sha512);
sha.update(&sha_512_test_block_var);
let expected: [u8; 64] = [
0xDD, 0xAF, 0x35, 0xA1, 0x93, 0x61, 0x7A, 0xBA, 0xCC, 0x41, 0x73, 0x49, 0xAE, 0x20,
0x41, 0x31, 0x12, 0xE6, 0xFA, 0x4E, 0x89, 0xA9, 0x7E, 0xA2, 0x0A, 0x9E, 0xEE, 0xE6,
0x4B, 0x55, 0xD3, 0x9A, 0x21, 0x92, 0x99, 0x2A, 0x27, 0x4F, 0xC1, 0xA8, 0x36, 0xBA,
0x3C, 0x23, 0xA3, 0xFE, 0xEB, 0xBD, 0x45, 0x4D, 0x44, 0x23, 0x64, 0x3C, 0xE8, 0x0E,
0x2A, 0x9A, 0xC9, 0x4F, 0xA5, 0x4C, 0xA4, 0x9F,
];
let mut hash = [0u8; 64];
sha.copy_hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/sha256.rs | sw-emulator/lib/crypto/src/sha256.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha256.rs
Abstract:
File contains implementation of Secure Hash 256 Algorithm (SHA-256 )
--*/
use crate::helpers::EndianessTransform;
use sha2::digest::block_buffer::Block;
use sha2::digest::consts::U64;
/// SHA-256 Mode
#[derive(Debug, Copy, Clone)]
pub enum Sha256Mode {
Sha224,
Sha256,
}
/// SHA-256
pub struct Sha256 {
/// Hash
hash: [u32; 8],
/// SHA 256 Mode
mode: Sha256Mode,
}
impl Sha256 {
/// SHA-256 Block Size
pub const BLOCK_SIZE: usize = 64;
/// SHA-256 Hash Size
pub const HASH_SIZE: usize = 32;
/// SHA-256-224 Initial Hash Vectors
#[rustfmt::skip]
const HASH_IV_224: [u32; 8] = [
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
];
/// SHA-256-256 Initial Hash Vectors
#[rustfmt::skip]
const HASH_IV_256 : [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];
/// Create a new instance of Secure Hash Algorithm object
///
/// # Arguments
///
/// * `mode` - Mode of the SHA Operation
pub fn new(mode: Sha256Mode) -> Self {
Self {
hash: Self::hash_iv(mode),
mode,
}
}
/// Reset the state
pub fn reset(&mut self, mode: Sha256Mode) {
self.mode = mode;
self.hash = Self::hash_iv(self.mode)
}
/// Update the hash
///
/// # Arguments
///
/// * `block` - Block to compress
pub fn update(&mut self, block: &[u8; Self::BLOCK_SIZE]) {
let mut block = *Block::<U64>::from_slice(block);
// Block is received as a list of big-endian DWORDs.
// Changing them to little-endian.
block.to_little_endian();
sha2::compress256(&mut self.hash, &[block]);
}
/// Retrieve the hash
///
/// # Arguments
///
/// * `hash` - Hash to copy
pub fn hash(&mut self, hash: &mut [u8]) {
// Return the hash as a list of big-endian DWORDs.
self.hash
.iter()
.flat_map(|i| i.to_le_bytes())
.take(self.hash_len())
.zip(hash)
.for_each(|(src, dest)| *dest = src);
}
/// Get the length of the hash
pub fn hash_len(&self) -> usize {
match self.mode {
Sha256Mode::Sha224 => 28,
Sha256Mode::Sha256 => 32,
}
}
/// Retrieve the hash initialization vector for specified SHA mode
///
/// # Arguments
///
/// * `mode` - Mode of the SHA Operation
///
/// # Returns
///
/// * `[u64; 8]` - The initialization vector
fn hash_iv(mode: Sha256Mode) -> [u32; 8] {
match mode {
Sha256Mode::Sha224 => Self::HASH_IV_224,
Sha256Mode::Sha256 => Self::HASH_IV_256,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[rustfmt::skip]
const SHA_256_TEST_BLOCK: [u8; 64] = [
0x61, 0x62, 0x63, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18,
];
#[test]
fn test_sha256_224() {
let mut sha_256_test_block = SHA_256_TEST_BLOCK;
sha_256_test_block.to_big_endian();
let mut sha = Sha256::new(Sha256Mode::Sha224);
sha.update(&sha_256_test_block);
#[rustfmt::skip]
let expected: [u8; 28] = [
0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8, 0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2, 0x55, 0xb3,
0x2a, 0xad, 0xbc, 0xe4, 0xbd, 0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7,
];
let mut hash = [0u8; 28];
sha.hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
#[test]
fn test_sha256_256() {
let mut sha_256_test_block = SHA_256_TEST_BLOCK;
sha_256_test_block.to_big_endian();
let mut sha = Sha256::new(Sha256Mode::Sha256);
sha.update(&sha_256_test_block);
#[rustfmt::skip]
let expected: [u8; 32] = [
0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x1, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23,
0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x0, 0x15, 0xAD,
];
let mut hash = [0u8; 32];
sha.hash(&mut hash);
hash.to_little_endian();
assert_eq!(&hash, &expected);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/hmac512.rs | sw-emulator/lib/crypto/src/hmac512.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hmac512.rs
Abstract:
File contains implementation of Hash Message Authenticated Code (HMAC-512)
--*/
use crate::{helpers::EndianessTransform, Sha512, Sha512Mode};
pub trait Hmac512Interface {
/// Create a new instance
fn new(mode: Hmac512Mode) -> Self
where
Self: Sized;
/// Reset the state
fn reset(&mut self);
/// Initialize the HMAC Algorithm
///
/// # Arguments
///
/// * `key` - Key to use for HMAC
/// * `block` - Block to calculate MAC over
fn init(&mut self, key: &[u8], block: &[u8; BLOCK_SIZE]);
/// Update the MAC with the block
///
/// # Arguments
///
/// * `block` - Block to calculate MAC over
fn update(&mut self, block: &[u8; BLOCK_SIZE]);
/// Retrieve the tag
///
/// # Arguments
///
/// * `tag` - Buffer to copy the tag to
fn tag(&self, tag: &mut [u8]);
}
/// HMAC-512 Mode
#[derive(Debug, Copy, Clone)]
pub enum Hmac512Mode {
Sha224,
Sha256,
Sha384,
Sha512,
}
/// Block Size
const BLOCK_SIZE: usize = Sha512::BLOCK_SIZE;
/// Tag Size
const MAX_TAG_SIZE: usize = Sha512::HASH_SIZE;
/// Length field size
const LEN_SIZE: usize = 16;
/// Input Pad
const IPAD: u8 = 0x36;
/// Output Pad
const OPAD: u8 = 0x5C;
impl From<Hmac512Mode> for Sha512Mode {
/// Converts to this type from the input type.
fn from(mode: Hmac512Mode) -> Self {
match mode {
Hmac512Mode::Sha224 => Sha512Mode::Sha224,
Hmac512Mode::Sha256 => Sha512Mode::Sha256,
Hmac512Mode::Sha384 => Sha512Mode::Sha384,
Hmac512Mode::Sha512 => Sha512Mode::Sha512,
}
}
}
/// HMAC-512
pub struct Hmac512<const KEY_SIZE: usize> {
/// Hash One
hash1: Sha512,
/// Hash Two
hash2: Sha512,
/// HMAC Mode
mode: Hmac512Mode,
/// Output Pad
opad: [u8; BLOCK_SIZE],
}
impl<const KEY_SIZE: usize> Hmac512Interface for Hmac512<KEY_SIZE> {
fn new(mode: Hmac512Mode) -> Self {
Self {
hash1: Sha512::new(mode.into()),
hash2: Sha512::new(mode.into()),
mode,
opad: [0u8; BLOCK_SIZE],
}
}
fn reset(&mut self) {
// Reset both hashing engines
self.hash1.reset(self.mode.into());
self.hash2.reset(self.mode.into());
self.opad.iter_mut().for_each(|b| *b = 0);
}
/// Initialize the HMAC Algorithm
///
/// # Arguments
///
/// * `key` - Key to use for HMAC
/// * `block` - Block to calculate MAC over
fn init(&mut self, key: &[u8], block: &[u8; BLOCK_SIZE]) {
let key: &[u8; KEY_SIZE] = key.try_into().expect("key size mismatch");
assert!(KEY_SIZE <= BLOCK_SIZE, "key is larger than block size");
// Reset the state
self.reset();
// Key is received as a list of big-endian DWORDs. Changing them to little-endian.
let mut key_le = *key;
key_le.to_little_endian();
// Expand the key and XOR it with OPAD
self.opad[..KEY_SIZE].copy_from_slice(&key_le);
self.opad.iter_mut().for_each(|b| *b ^= OPAD);
// Expand the key and XOR it with IPAD
let mut ipad = [0u8; BLOCK_SIZE];
ipad[..KEY_SIZE].copy_from_slice(&key_le);
ipad.iter_mut().for_each(|b| *b ^= IPAD);
// The SHA512::update function expects the block as a list of big-endian DWORDs.
ipad.to_big_endian();
// Hash the ipad
self.hash1.update(&ipad);
// Hash the block
self.update(block);
}
/// Update the MAC with the block
///
/// # Arguments
///
/// * `block` - Block to calculate MAC over
fn update(&mut self, block: &[u8; BLOCK_SIZE]) {
// hash the block
self.hash1.update(block);
// Calculate the summary hash so far
let mut sum_hash = [0u8; MAX_TAG_SIZE];
self.hash1.copy_hash(&mut sum_hash);
// The SHA512::hash function returns the hash as a list of big-endian DWORDs.
// Converting sum_hash to little-endian DWORDs.
sum_hash.to_little_endian();
// Copy the summary hash into block
let mut sum_block = [0u8; BLOCK_SIZE];
sum_block[..self.hash1.hash_len()].copy_from_slice(&sum_hash[..self.hash1.hash_len()]);
// Mark start of padding in the block
sum_block[self.hash1.hash_len()] = 1 << 7;
// Copy the length of the data hashed in bits
let len: u128 = ((BLOCK_SIZE + self.hash1.hash_len()) * 8) as u128;
sum_block[BLOCK_SIZE - LEN_SIZE..].copy_from_slice(&len.to_be_bytes());
// Reset the second hash engine and generate the new tag.
self.hash2.reset(self.mode.into());
// The SHA512::update function expects the block as a list of big-endian DWORDs.
self.opad.to_big_endian();
self.hash2.update(&self.opad);
// Changing back to little-endian.
self.opad.to_little_endian();
// The SHA512::update function expects the block as a list of big-endian DWORDs.
sum_block.to_big_endian();
self.hash2.update(&sum_block);
}
/// Retrieve the tag
///
/// # Arguments
///
/// * `tag` - Buffer to copy the tag to
fn tag(&self, tag: &mut [u8]) {
self.hash2.copy_hash(tag);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test<const N: usize>(mode: Hmac512Mode, key: &mut [u8; N], data: &[u8], result: &[u8]) {
let mut block = [0u8; BLOCK_SIZE];
block[..data.len()].copy_from_slice(data);
block[data.len()] = 1 << 7;
let len: u128 = (BLOCK_SIZE + data.len()) as u128;
let len = len * 8;
block[BLOCK_SIZE - LEN_SIZE..].copy_from_slice(&len.to_be_bytes());
let mut hmac: Hmac512<N> = Hmac512::new(mode);
block.to_big_endian();
key.to_big_endian();
hmac.init(key, &block);
let mut tag = [0u8; MAX_TAG_SIZE];
hmac.tag(&mut tag);
tag.to_little_endian();
assert_eq!(&tag[..result.len()], result);
}
// Test cases from https://datatracker.ietf.org/doc/html/rfc4231
#[test]
fn test_hmac_sha384_0() {
let mut key: [u8; 48] = [
0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65,
0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65,
0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65,
0x66, 0x65, 0x4a, 0x65, 0x66, 0x65,
];
let data: [u8; 28] = [
0x77, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x79, 0x61, 0x20, 0x77, 0x61, 0x6e,
0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x3f,
];
let result: [u8; 48] = [
0x2c, 0x73, 0x53, 0x97, 0x4f, 0x18, 0x42, 0xfd, 0x66, 0xd5, 0x3c, 0x45, 0x2c, 0xa4,
0x21, 0x22, 0xb2, 0x8c, 0x0b, 0x59, 0x4c, 0xfb, 0x18, 0x4d, 0xa8, 0x6a, 0x36, 0x8e,
0x9b, 0x8e, 0x16, 0xf5, 0x34, 0x95, 0x24, 0xca, 0x4e, 0x82, 0x40, 0x0c, 0xbd, 0xe0,
0x68, 0x6d, 0x40, 0x33, 0x71, 0xc9,
];
test(Hmac512Mode::Sha384, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha384_1() {
let mut key: [u8; 20] = [
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
];
let data: [u8; 8] = [0x48, 0x69, 0x20, 0x54, 0x68, 0x65, 0x72, 0x65];
let result: [u8; 48] = [
0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4, 0xab, 0x46,
0x90, 0x7f, 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6, 0x82, 0xaa, 0x03, 0x4c,
0x7c, 0xeb, 0xc5, 0x9c, 0xfa, 0xea, 0x9e, 0xa9, 0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1,
0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6,
];
test(Hmac512Mode::Sha384, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha384_2() {
let mut key: [u8; 4] = [0x4a, 0x65, 0x66, 0x65];
let data: [u8; 28] = [
0x77, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x79, 0x61, 0x20, 0x77, 0x61, 0x6e,
0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x3f,
];
let result: [u8; 48] = [
0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2, 0xb5, 0x8a,
0x6b, 0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47, 0xe4, 0x2e, 0xc3, 0x73,
0x63, 0x22, 0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca, 0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32,
0x39, 0xec, 0xfa, 0xb2, 0x16, 0x49,
];
test(Hmac512Mode::Sha384, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha384_3() {
let mut key: [u8; 20] = [
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
];
let data: [u8; 50] = [
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
];
let result: [u8; 48] = [
0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0, 0x14, 0xc8,
0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb, 0xe8, 0x3e, 0xf4, 0xe5,
0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d, 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a,
0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
];
test(Hmac512Mode::Sha384, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha384_4() {
let mut key: [u8; 28] = [
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00,
];
let data: [u8; 50] = [
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
];
let result: [u8; 48] = [
0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62, 0x90, 0xaf,
0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c, 0xc5, 0x57, 0x7c, 0x6e,
0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23, 0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8,
0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
];
test(Hmac512Mode::Sha384, &mut key, &data, &result);
}
#[test]
#[should_panic(expected = "key is larger than block size")]
fn test_hmac_sha384_5() {
let mut key: [u8; 132] = [
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00,
];
let data: [u8; 54] = [
0x54, 0x65, 0x73, 0x74, 0x20, 0x55, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x4c, 0x61, 0x72,
0x67, 0x65, 0x72, 0x20, 0x54, 0x68, 0x61, 0x6e, 0x20, 0x42, 0x6c, 0x6f, 0x63, 0x6b,
0x2d, 0x53, 0x69, 0x7a, 0x65, 0x20, 0x4b, 0x65, 0x79, 0x20, 0x2d, 0x20, 0x48, 0x61,
0x73, 0x68, 0x20, 0x4b, 0x65, 0x79, 0x20, 0x46, 0x69, 0x72, 0x73, 0x74,
];
let result: [u8; 48] = [
0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a, 0x04, 0x1b,
0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f, 0x3c, 0xd1, 0x1f, 0x05,
0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab, 0x40, 0x30, 0xfe, 0x82, 0x96, 0x24,
0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
];
test(Hmac512Mode::Sha384, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha512_1() {
let mut key: [u8; 20] = [
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
];
let data: [u8; 8] = [0x48, 0x69, 0x20, 0x54, 0x68, 0x65, 0x72, 0x65];
let result: [u8; 64] = [
0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a, 0x1d,
0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0, 0xb3, 0x05,
0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7, 0x02, 0x03, 0x8b,
0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e, 0xeb, 0x61, 0xf1, 0x70,
0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54,
];
test(Hmac512Mode::Sha512, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha512_2() {
let mut key: [u8; 4] = [0x4a, 0x65, 0x66, 0x65];
let data: [u8; 28] = [
0x77, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x79, 0x61, 0x20, 0x77, 0x61, 0x6e,
0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x3f,
];
let result: [u8; 64] = [
0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b, 0x56,
0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27, 0x0c, 0xd7,
0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99, 0x4a, 0x6d, 0x03,
0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3, 0x4d, 0x4a, 0x6b, 0x4b,
0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37,
];
test(Hmac512Mode::Sha512, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha512_3() {
let mut key: [u8; 20] = [
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
];
let data: [u8; 50] = [
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
];
let result: [u8; 64] = [
0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c, 0x89,
0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8, 0x3e, 0x33,
0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22, 0xc8, 0x06, 0xb4,
0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37, 0xbe, 0xe8, 0x94, 0x26,
0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
];
test(Hmac512Mode::Sha512, &mut key, &data, &result);
}
#[test]
fn test_hmac_sha512_4() {
let mut key: [u8; 28] = [
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00,
];
let data: [u8; 50] = [
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
];
let result: [u8; 64] = [
0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6, 0x1d,
0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f, 0x80, 0x50,
0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e, 0xb4, 0xd6, 0x79,
0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41, 0x12, 0x0c, 0x4f, 0x2d,
0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
];
test(Hmac512Mode::Sha512, &mut key, &data, &result);
}
#[test]
#[should_panic(expected = "key is larger than block size")]
fn test_hmac_sha512_5() {
let mut key: [u8; 132] = [
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00,
];
let data: [u8; 54] = [
0x54, 0x65, 0x73, 0x74, 0x20, 0x55, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x4c, 0x61, 0x72,
0x67, 0x65, 0x72, 0x20, 0x54, 0x68, 0x61, 0x6e, 0x20, 0x42, 0x6c, 0x6f, 0x63, 0x6b,
0x2d, 0x53, 0x69, 0x7a, 0x65, 0x20, 0x4b, 0x65, 0x79, 0x20, 0x2d, 0x20, 0x48, 0x61,
0x73, 0x68, 0x20, 0x4b, 0x65, 0x79, 0x20, 0x46, 0x69, 0x72, 0x73, 0x74,
];
let result: [u8; 64] = [
0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6, 0x1d,
0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f, 0x80, 0x50,
0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e, 0xb4, 0xd6, 0x79,
0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41, 0x12, 0x0c, 0x4f, 0x2d,
0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
];
test(Hmac512Mode::Sha512, &mut key, &data, &result);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/crypto/src/aes256cbc.rs | sw-emulator/lib/crypto/src/aes256cbc.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
aes256cbc.rs
Abstract:
File contains implementation of AES-256 CBC algorithm
--*/
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use crate::{helpers::EndianessTransform, AES_256_BLOCK_SIZE, AES_256_KEY_SIZE};
pub struct Aes256Cbc {
last: [u8; AES_256_BLOCK_SIZE],
encryptor: Aes256Encryptor,
decryptor: Aes256Decryptor,
}
impl Default for Aes256Cbc {
fn default() -> Self {
Self::new(&[0u8; AES_256_IV_SIZE], &[0u8; AES_256_KEY_SIZE])
}
}
const AES_256_IV_SIZE: usize = AES_256_BLOCK_SIZE;
type Aes256Encryptor = cbc::Encryptor<aes::Aes256>;
type Aes256Decryptor = cbc::Decryptor<aes::Aes256>;
impl Aes256Cbc {
pub fn new(iv: &[u8; AES_256_IV_SIZE], key: &[u8; AES_256_KEY_SIZE]) -> Self {
Self {
last: *iv,
encryptor: Aes256Encryptor::new(key.into(), iv.into()),
decryptor: Aes256Decryptor::new(key.into(), iv.into()),
}
}
/// Streaming mode: encrypt a single block and return the ciphertext.
pub fn encrypt_block(&mut self, block: &[u8; AES_256_BLOCK_SIZE]) -> [u8; AES_256_BLOCK_SIZE] {
let mut out_block = [0u8; AES_256_BLOCK_SIZE].into();
self.encryptor
.encrypt_block_b2b_mut(block.into(), &mut out_block);
self.last = out_block.into();
out_block.into()
}
/// Streaming mode: decrypt a single block and return the plaintext.
pub fn decrypt_block(&mut self, block: &[u8; AES_256_BLOCK_SIZE]) -> [u8; AES_256_BLOCK_SIZE] {
let mut out_block = [0u8; AES_256_BLOCK_SIZE].into();
self.decryptor
.decrypt_block_b2b_mut(block.into(), &mut out_block);
self.last = *block;
out_block.into()
}
/// Decrypt the cipher text
///
/// # Arguments
///
/// * `key` - Key
/// * `iv` - Initialization vector
/// * `cipher_text` - Cipher text
/// * `plain_text` - plain text
pub fn decrypt(
key: &[u8; AES_256_KEY_SIZE],
iv: &[u8; AES_256_IV_SIZE],
cipher_txt: &[u8],
plain_txt: &mut [u8],
) {
assert_eq!(cipher_txt.len(), plain_txt.len());
assert_eq!(cipher_txt.len() % AES_256_BLOCK_SIZE, 0);
// IV is received as a list of big-endian DWORDs.
// Convert them to little-endian.
let mut iv_be = *iv;
iv_be.to_little_endian();
// Not changing key or cipher text endianess since it is internal from the firmware crypto API perspective.
let mut decryptor = Aes256Decryptor::new(key.into(), &iv_be.into());
for idx in (0..cipher_txt.len()).step_by(AES_256_BLOCK_SIZE) {
let in_block = cipher_txt[idx..idx + 16].into();
let out_block = (&mut plain_txt[idx..idx + 16]).into();
decryptor.decrypt_block_b2b_mut(in_block, out_block);
}
}
}
#[cfg(test)]
mod tests {
use crate::{helpers::EndianessTransform, Aes256Cbc, AES_256_BLOCK_SIZE};
#[test]
fn test_encrypt_decrypt_streaming() {
let mut cbc = Aes256Cbc::new(&[0u8; 16], &[0u8; 32]);
let plaintext: [u8; 128] = [
0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F, 0xBB, 0xB3, 0x66, 0xB5,
0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F, 0xBB, 0xB3,
0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F,
0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB,
0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91,
0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1,
0xFA, 0x91, 0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67,
0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4,
0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5,
0x31, 0xB4,
];
for pblock in plaintext.chunks_exact(AES_256_BLOCK_SIZE) {
assert_eq!(
[0; AES_256_BLOCK_SIZE],
cbc.encrypt_block(pblock.try_into().unwrap())
);
}
let mut cbc = Aes256Cbc::new(&[0u8; 16], &[0u8; 32]);
for pblock in plaintext.chunks_exact(AES_256_BLOCK_SIZE) {
assert_eq!(pblock, cbc.decrypt_block(&[0u8; AES_256_BLOCK_SIZE]));
}
}
#[test]
fn test_decrypt_1024bit() {
let expected = [
0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F, 0xBB, 0xB3, 0x66, 0xB5,
0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F, 0xBB, 0xB3,
0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F,
0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB,
0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91,
0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1,
0xFA, 0x91, 0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67,
0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4,
0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0x0F, 0x8F, 0xBB, 0xB3, 0x66, 0xB5,
0x31, 0xB4,
];
let mut actual = [0u8; 128];
Aes256Cbc::decrypt(&[0u8; 32], &[0u8; 16], &[0u8; 128], &mut actual);
assert_eq!(expected, actual);
}
#[test]
fn test_decrypt_384bit() {
let expected = [
0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F, 0xBB, 0xB3, 0x66, 0xB5,
0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F, 0xBB, 0xB3,
0x66, 0xB5, 0x31, 0xB4, 0x67, 0x67, 0x1C, 0xE1, 0xFA, 0x91, 0xDD, 0xEB, 0xF, 0x8F,
0xBB, 0xB3, 0x66, 0xB5, 0x31, 0xB4,
];
let mut actual = [0u8; 48];
Aes256Cbc::decrypt(&[0u8; 32], &[0u8; 16], &[0u8; 48], &mut actual);
assert_eq!(expected, actual);
}
#[test]
fn test_decrypt_256bit() {
const KEY: [u8; 32] = [
0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D,
0x77, 0x81, 0x1F, 0x35, 0x2C, 0x7, 0x3B, 0x61, 0x8, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x9,
0x14, 0xDF, 0xF4,
];
let mut iv: [u8; 16] = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f,
];
const CIPHER_TEXT: [u8; 64] = [
0xF5, 0x8C, 0x4C, 0x04, 0xD6, 0xE5, 0xF1, 0xBA, 0x77, 0x9E, 0xAB, 0xFB, 0x5F, 0x7B,
0xFB, 0xD6, 0x9C, 0xFC, 0x4E, 0x96, 0x7E, 0xDB, 0x80, 0x8D, 0x67, 0x9F, 0x77, 0x7B,
0xC6, 0x70, 0x2C, 0x7D, 0x39, 0xF2, 0x33, 0x69, 0xA9, 0xD9, 0xBA, 0xCF, 0xA5, 0x30,
0xE2, 0x63, 0x04, 0x23, 0x14, 0x61, 0xB2, 0xEB, 0x05, 0xE2, 0xC3, 0x9B, 0xE9, 0xFC,
0xDA, 0x6C, 0x19, 0x07, 0x8C, 0x6A, 0x9D, 0x1B,
];
const EXPECTED_PLAIN_TEXT: [u8; 64] = [
0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93,
0x17, 0x2A, 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x3, 0xAC, 0x9C, 0x9E, 0xB7, 0x6F, 0xAC,
0x45, 0xAF, 0x8E, 0x51, 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, 0xE5, 0xFB,
0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17,
0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10,
];
let mut actual_plain_text = [0u8; 64];
iv.to_big_endian();
Aes256Cbc::decrypt(&KEY, &iv, &CIPHER_TEXT, &mut actual_plain_text);
assert_eq!(actual_plain_text, EXPECTED_PLAIN_TEXT);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/hmac.rs | sw-emulator/lib/periph/src/hmac.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hmac_sha384.rs
Abstract:
File contains HMACSha384 peripheral implementation.
--*/
use crate::helpers::bytes_from_words_le;
use crate::{KeyUsage, KeyVault};
use caliptra_emu_bus::{ActionHandle, BusError, Clock, ReadOnlyRegister, ReadWriteRegister, Timer};
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_crypto::{Hmac512, Hmac512Interface, Hmac512Mode};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use tock_registers::registers::InMemoryRegister;
use zerocopy::IntoBytes;
register_bitfields! [
u32,
/// Control Register Fields
Control [
INIT OFFSET(0) NUMBITS(1) [],
NEXT OFFSET(1) NUMBITS(1) [],
ZEROIZE OFFSET(2) NUMBITS(1) [],
MODE OFFSET(3) NUMBITS(1) [
HMAC384 = 0,
HMAC512 = 1,
],
CSR_MODE OFFSET(4) NUMBITS(1) [],
RSVD OFFSET(4) NUMBITS(28) [],
],
/// Status Register Fields
Status[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// Key Read Control Register Fields
pub KeyReadControl[
KEY_READ_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
PCR_HASH_EXTEND OFFSET(6) NUMBITS(1) [],
RSVD OFFSET(7) NUMBITS(25) [],
],
/// Key Read Status Register Fields
pub KeyReadStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
KV_SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL= 2,
],
RSVD OFFSET(10) NUMBITS(22) [],
],
/// Tag Write Control Register Fields
pub TagWriteControl[
KEY_WRITE_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
USAGE OFFSET(6) NUMBITS(8) [],
RSVD OFFSET(12) NUMBITS(20) [],
],
// Tag Status Register Fields
pub TagWriteStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
KV_SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL= 2,
],
RSVD OFFSET(10) NUMBITS(22) [],
],
];
/// HMAC384 Key Size.
const HMAC_KEY_SIZE_384: usize = 48;
/// HMAC512 Key Size in Bytes.
const HMAC_KEY_SIZE_BYTES_512: usize = 64;
/// HMAC512 Key Size in DWORDs.
const HMAC_KEY_SIZE_DWORD_512: usize = 16;
/// HMAC Block Size
const HMAC_BLOCK_SIZE: usize = 128; // SHA-384/512 block size is 128 bytes
/// HMAC512 Tag Size
const HMAC_TAG_SIZE_512: usize = 64; // SHA512 produces 64-byte tags
/// The number of CPU clock cycles it takes to perform initialization action.
const INIT_TICKS: u64 = 1000;
/// The number of CPU clock cycles it takes to perform the hash update action.
const UPDATE_TICKS: u64 = 1000;
/// The number of CPU clock cycles read and write keys from key vault
pub const KEY_RW_TICKS: u64 = 100;
/// LSFR Seed Size.
const HMAC_LFSR_SEED_SIZE: usize = 48;
const DEFAULT_CSR_HMAC_KEY: [u32; HMAC_KEY_SIZE_DWORD_512] = [
0x14552AD, 0x19550757, 0x50C602DD, 0x85DE4E9B, 0x815CC9EF, 0xBA81A35, 0x7A05D7C0, 0x7F5EFAEB,
0xF76DD9D2, 0x9E38197F, 0x4052537, 0x25B568F4, 0x432665F1, 0xD11D02A7, 0xBFB9279F, 0xA2EB96D7,
];
/// HMAC-SHA-384 Peripheral
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct HmacSha {
/// Name 0 register
#[register(offset = 0x0000_0000)]
name0: ReadOnlyRegister<u32>,
/// Name 1 register
#[register(offset = 0x0000_0004)]
name1: ReadOnlyRegister<u32>,
/// Version 0 register
#[register(offset = 0x0000_0008)]
version0: ReadOnlyRegister<u32>,
/// Version 1 register
#[register(offset = 0x0000_000C)]
version1: ReadOnlyRegister<u32>,
/// Control register
#[register(offset = 0x0000_0010, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
/// Status register
#[register(offset = 0x0000_0018)]
status: ReadOnlyRegister<u32, Status::Register>,
/// HMAC Key Register
#[register_array(offset = 0x0000_0040, item_size = 4, len = 16, read_fn = read_access_fault, write_fn = on_write_key)]
key: [u32; HMAC_KEY_SIZE_DWORD_512],
/// HMAC Block Register
#[register_array(offset = 0x0000_0080, item_size = 4, len = 32, read_fn = read_access_fault, write_fn = on_write_block)]
block: [u32; HMAC_BLOCK_SIZE / 4],
/// HMAC Tag Register
#[register_array(offset = 0x0000_0100, item_size = 4, len = 16, read_fn = on_read_tag, write_fn = write_access_fault)]
tag: [u32; HMAC_TAG_SIZE_512 / 4],
/// LSFR Seed Register
#[register_array(offset = 0x0000_0140)]
lfsr_seed: [u32; HMAC_LFSR_SEED_SIZE / 4],
/// Key Read Control Register
#[register(offset = 0x0000_0600, write_fn = on_write_key_read_control)]
key_read_ctrl: ReadWriteRegister<u32, KeyReadControl::Register>,
/// Key Read Status Register
#[register(offset = 0x0000_0604)]
key_read_status: ReadOnlyRegister<u32, KeyReadStatus::Register>,
/// Block Read Control Register
#[register(offset = 0x0000_0608, write_fn = on_write_block_read_control)]
block_read_ctrl: ReadWriteRegister<u32, KeyReadControl::Register>,
/// Block Read Status Register
#[register(offset = 0x0000_060c)]
block_read_status: ReadOnlyRegister<u32, KeyReadStatus::Register>,
/// Tag Write Control Register
#[register(offset = 0x0000_0610, write_fn = on_write_tag_write_control)]
tag_write_ctrl: ReadWriteRegister<u32, TagWriteControl::Register>,
/// Tag Write Status Register
#[register(offset = 0x0000_0614)]
tag_write_status: ReadOnlyRegister<u32, TagWriteStatus::Register>,
// True if the current key was read from the key-vault
key_from_kv: bool,
// True if the current block was read from the key-vault
block_from_kv: bool,
// True if the tag should be hidden from the CPU
hide_tag_from_cpu: bool,
/// HMAC engine
hmac: Box<dyn Hmac512Interface>,
/// Key Vault
key_vault: KeyVault,
/// Timer
timer: Timer,
/// Operation complete action
op_complete_action: Option<ActionHandle>,
/// Key read complete action
op_key_read_complete_action: Option<ActionHandle>,
/// Block read complete action
op_block_read_complete_action: Option<ActionHandle>,
/// Tag write complete action
op_tag_write_complete_action: Option<ActionHandle>,
/// CSR Key
csr_key: [u32; HMAC_KEY_SIZE_DWORD_512],
}
impl HmacSha {
/// NAME0 Register Value
const NAME0_VAL: RvData = 0x63616d68; // hmac
/// NAME1 Register Value
const NAME1_VAL: RvData = 0x32616873; // sha2
/// VERSION0 Register Value
const VERSION0_VAL: RvData = 0x30302E31; // 1.0
/// VERSION1 Register Value
const VERSION1_VAL: RvData = 0x00000000;
/// Create a new instance of HMAC-SHA-384 Engine
///
/// # Arguments
///
/// * `clock` - Clock
/// * `key_vault` - Key Vault
///
/// # Returns
///
/// * `Self` - Instance of HMAC-SHA-384 Engine
pub fn new(clock: &Clock, key_vault: KeyVault) -> Self {
Self {
hmac: Box::new(Hmac512::<HMAC_KEY_SIZE_BYTES_512>::new(Hmac512Mode::Sha512)),
name0: ReadOnlyRegister::new(Self::NAME0_VAL),
name1: ReadOnlyRegister::new(Self::NAME1_VAL),
version0: ReadOnlyRegister::new(Self::VERSION0_VAL),
version1: ReadOnlyRegister::new(Self::VERSION1_VAL),
control: ReadWriteRegister::new(0),
status: ReadOnlyRegister::new(Status::READY::SET.value),
key: Default::default(),
block: Default::default(),
tag: Default::default(),
lfsr_seed: Default::default(),
key_read_ctrl: ReadWriteRegister::new(0),
key_read_status: ReadOnlyRegister::new(KeyReadStatus::READY::SET.value),
block_read_ctrl: ReadWriteRegister::new(0),
block_read_status: ReadOnlyRegister::new(KeyReadStatus::READY::SET.value),
tag_write_ctrl: ReadWriteRegister::new(0),
tag_write_status: ReadOnlyRegister::new(TagWriteStatus::READY::SET.value),
key_vault,
timer: Timer::new(clock),
key_from_kv: false,
block_from_kv: false,
hide_tag_from_cpu: false,
op_complete_action: None,
op_key_read_complete_action: None,
op_block_read_complete_action: None,
op_tag_write_complete_action: None,
csr_key: DEFAULT_CSR_HMAC_KEY,
}
}
fn read_access_fault(&mut self, _size: RvSize, _index: usize) -> Result<u32, BusError> {
Err(BusError::LoadAccessFault)
}
fn write_access_fault(
&mut self,
_size: RvSize,
_index: usize,
_val: RvData,
) -> Result<(), BusError> {
Err(BusError::StoreAccessFault)
}
fn on_write_key(&mut self, _size: RvSize, index: usize, val: RvData) -> Result<(), BusError> {
if self.key_from_kv {
self.key_from_kv = false;
self.key.fill(0);
}
self.key[index] = val;
Ok(())
}
fn on_write_block(&mut self, _size: RvSize, index: usize, val: RvData) -> Result<(), BusError> {
if self.block_from_kv {
self.block_from_kv = false;
self.block.fill(0);
}
self.block[index] = val;
Ok(())
}
fn on_read_tag(&mut self, _size: RvSize, index: usize) -> Result<RvData, BusError> {
if self.hide_tag_from_cpu {
return Ok(0);
}
Ok(self.tag[index])
}
fn key_len(&self) -> usize {
match self.control.reg.read_as_enum(Control::MODE).unwrap() {
Control::MODE::Value::HMAC384 => 12,
Control::MODE::Value::HMAC512 => 16,
}
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.control.reg.set(val);
if self.control.reg.is_set(Control::INIT) || self.control.reg.is_set(Control::NEXT) {
// Reset the Ready and Valid status bits
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
let mode512 = self.control.reg.is_set(Control::MODE);
// If CSR mode is set, use the pre-defined key.
// Also reset the key_from_kv flag since the key is not read from the key-vault.
if self.control.reg.is_set(Control::CSR_MODE) {
self.key = self.csr_key;
self.key_from_kv = false;
}
if self.control.reg.is_set(Control::INIT) {
if mode512 {
self.hmac =
Box::new(Hmac512::<HMAC_KEY_SIZE_BYTES_512>::new(Hmac512Mode::Sha512))
} else {
self.hmac = Box::new(Hmac512::<HMAC_KEY_SIZE_384>::new(Hmac512Mode::Sha384))
}
// Initialize the HMAC engine with key and initial data block
if mode512 {
self.hmac.init(
&bytes_from_words_le::<[u32; 16]>(&self.key[..16].try_into().unwrap()),
&bytes_from_words_le(&self.block),
);
} else {
self.hmac.init(
&bytes_from_words_le::<[u32; 12]>(&self.key[..12].try_into().unwrap()),
&bytes_from_words_le(&self.block),
);
}
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(INIT_TICKS));
} else if self.control.reg.is_set(Control::NEXT) {
// Update a HMAC engine with a new block
self.hmac.update(&bytes_from_words_le(&self.block));
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(UPDATE_TICKS));
}
}
if self.control.reg.is_set(Control::ZEROIZE) {
// Zeroize the HMAC engine
self.zeroize();
}
Ok(())
}
/// On Write callback for `key_read_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_key_read_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the key control register
let key_read_ctrl = InMemoryRegister::<u32, KeyReadControl::Register>::new(val);
self.key_read_ctrl.reg.modify(
KeyReadControl::KEY_READ_EN.val(key_read_ctrl.read(KeyReadControl::KEY_READ_EN))
+ KeyReadControl::KEY_ID.val(key_read_ctrl.read(KeyReadControl::KEY_ID)),
);
if key_read_ctrl.is_set(KeyReadControl::KEY_READ_EN) {
self.key_read_status.reg.modify(
KeyReadStatus::READY::CLEAR
+ KeyReadStatus::VALID::CLEAR
+ KeyReadStatus::ERROR::CLEAR,
);
self.op_key_read_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
/// On Write callback for `block_read_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_block_read_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the block control register
let block_read_ctrl = InMemoryRegister::<u32, KeyReadControl::Register>::new(val);
self.block_read_ctrl.reg.modify(
KeyReadControl::KEY_READ_EN.val(block_read_ctrl.read(KeyReadControl::KEY_READ_EN))
+ KeyReadControl::KEY_ID.val(block_read_ctrl.read(KeyReadControl::KEY_ID)),
);
if block_read_ctrl.is_set(KeyReadControl::KEY_READ_EN) {
self.block_read_status.reg.modify(
KeyReadStatus::READY::CLEAR
+ KeyReadStatus::VALID::CLEAR
+ KeyReadStatus::ERROR::CLEAR,
);
self.op_block_read_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
/// On Write callback for `tag_write_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_tag_write_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the Tag control register
let tag_write_ctrl = InMemoryRegister::<u32, TagWriteControl::Register>::new(val);
self.tag_write_ctrl.reg.modify(
TagWriteControl::KEY_WRITE_EN.val(tag_write_ctrl.read(TagWriteControl::KEY_WRITE_EN))
+ TagWriteControl::KEY_ID.val(tag_write_ctrl.read(TagWriteControl::KEY_ID))
+ TagWriteControl::USAGE.val(tag_write_ctrl.read(TagWriteControl::USAGE)),
);
Ok(())
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
self.op_complete();
} else if self.timer.fired(&mut self.op_key_read_complete_action) {
self.key_read_complete();
} else if self.timer.fired(&mut self.op_block_read_complete_action) {
self.block_read_complete();
} else if self.timer.fired(&mut self.op_tag_write_complete_action) {
self.tag_write_complete();
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
// TODO: Reset registers
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
// TODO: Reset registers
}
fn op_complete(&mut self) {
// Retrieve the tag
let key_len = self.key_len();
// the hardware will not return the tag if HMAC512 is used with a truncated input from KV,
// and instead returns ready = true and valid = false.
if self.key_from_kv && key_len == 16 && self.key[12..16].iter().all(|&x| x == 0) {
self.status
.reg
.modify(Status::READY::SET + Status::VALID::CLEAR);
return;
}
// the hardware will not return the tag if HMAC512 is used with a 0 key from KV,
// and instead returns ready = true and valid = false.
if self.key_from_kv && self.key.iter().all(|&x| x == 0) {
self.status
.reg
.modify(Status::READY::SET + Status::VALID::CLEAR);
return;
}
self.hmac.tag(self.tag[..key_len].as_mut_bytes());
// Don't reveal the tag to the CPU if the inputs came from the
// key-vault.
self.hide_tag_from_cpu = self.block_from_kv || self.key_from_kv;
// Check if tag control is enabled.
if self
.tag_write_ctrl
.reg
.is_set(TagWriteControl::KEY_WRITE_EN)
{
self.tag_write_status.reg.modify(
TagWriteStatus::READY::CLEAR
+ TagWriteStatus::VALID::CLEAR
+ TagWriteStatus::ERROR::CLEAR,
);
self.op_tag_write_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
// Update Ready and Valid status bits
self.status
.reg
.modify(Status::READY::SET + Status::VALID::SET);
}
fn key_read_complete(&mut self) {
let key_id = self.key_read_ctrl.reg.read(KeyReadControl::KEY_ID);
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_key(true);
let result = self.key_vault.read_key(key_id, key_usage);
let (key_read_result, key) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => (KeyReadStatus::ERROR::KV_READ_FAIL.value, None),
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(KeyReadStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => (
KeyReadStatus::ERROR::KV_SUCCESS.value,
Some(result.unwrap()),
),
};
if let Some(key) = &key {
self.key_from_kv = true;
// HMAC mode is not known at this point. Thus, copying the entire
// key from the KV slot even though the actual key might be shorter.
// Peripherals using the key material will size it appropriately.
self.key[..HMAC_KEY_SIZE_DWORD_512]
.as_mut_bytes()
.copy_from_slice(key.as_bytes());
}
self.key_read_status.reg.modify(
KeyReadStatus::READY::SET
+ KeyReadStatus::VALID::SET
+ KeyReadStatus::ERROR.val(key_read_result),
);
}
fn block_read_complete(&mut self) {
let key_id = self.block_read_ctrl.reg.read(KeyReadControl::KEY_ID);
// Clear the block
self.block.fill(0);
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_data(true);
let error_code = match self.key_vault.read_key_as_data(key_id, key_usage) {
Err(BusError::LoadAccessFault)
| Err(BusError::LoadAddrMisaligned)
| Err(BusError::InstrAccessFault) => KeyReadStatus::ERROR::KV_READ_FAIL.value,
Err(BusError::StoreAccessFault) | Err(BusError::StoreAddrMisaligned) => {
KeyReadStatus::ERROR::KV_WRITE_FAIL.value
}
Ok(data) => {
self.format_block(data.as_bytes());
self.block_from_kv = true;
KeyReadStatus::ERROR::KV_SUCCESS.value
}
};
self.block_read_status.reg.modify(
KeyReadStatus::READY::SET
+ KeyReadStatus::VALID::SET
+ KeyReadStatus::ERROR.val(error_code),
);
}
/// Adds padding and total data size to the block.
/// Stores the formatted block in peripheral's internal block data structure.
///
/// # Arguments
///
/// * `data_len` - Size of the data
/// * `data` - Data to hash. This is in big-endian format.
///
/// # Error
///
/// * `None`
fn format_block(&mut self, data: &[u8]) {
let mut block_arr = [0u8; HMAC_BLOCK_SIZE];
block_arr[..data.len()].copy_from_slice(&data[..data.len()]);
block_arr.to_little_endian();
// Add block padding.
block_arr[data.len()] = 0b1000_0000;
// Add block length.
let len = ((HMAC_BLOCK_SIZE + data.len()) as u128) * 8;
block_arr[HMAC_BLOCK_SIZE - 16..].copy_from_slice(&len.to_be_bytes());
block_arr.to_big_endian();
self.block.as_mut_bytes().copy_from_slice(&block_arr);
}
fn tag_write_complete(&mut self) {
let key_id = self.tag_write_ctrl.reg.read(TagWriteControl::KEY_ID);
// Store the tag in the key-vault.
// Tag is in big-endian format and is stored in the same format.
let tag_write_result = match self
.key_vault
.write_key(
key_id,
&self.tag.as_bytes()[..self.key_len() * 4],
self.tag_write_ctrl.reg.read(TagWriteControl::USAGE),
)
.err()
{
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => TagWriteStatus::ERROR::KV_READ_FAIL.value,
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
TagWriteStatus::ERROR::KV_WRITE_FAIL.value
}
None => TagWriteStatus::ERROR::KV_SUCCESS.value,
};
self.tag_write_status.reg.modify(
TagWriteStatus::READY::SET
+ TagWriteStatus::VALID::SET
+ TagWriteStatus::ERROR.val(tag_write_result),
);
}
fn zeroize(&mut self) {
self.key.fill(0);
self.block.fill(0);
self.tag.fill(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::key_vault;
use caliptra_emu_bus::Bus;
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_types::RvAddr;
use tock_registers::registers::InMemoryRegister;
/// HMAC384 Tag Size
const HMAC_TAG_SIZE_384: usize = 48; // SHA384 produces 48-byte tags
const OFFSET_NAME0: RvAddr = 0x0;
const OFFSET_NAME1: RvAddr = 0x4;
const OFFSET_VERSION0: RvAddr = 0x8;
const OFFSET_VERSION1: RvAddr = 0xC;
const OFFSET_CONTROL: RvAddr = 0x10;
const OFFSET_STATUS: RvAddr = 0x18;
const OFFSET_KEY: RvAddr = 0x40;
const OFFSET_BLOCK: RvAddr = 0x80;
const OFFSET_TAG: RvAddr = 0x100;
const OFFSET_KEY_CONTROL: RvAddr = 0x600;
const OFFSET_KEY_STATUS: RvAddr = 0x604;
const OFFSET_BLOCK_CONTROL: RvAddr = 0x608;
const OFFSET_BLOCK_STATUS: RvAddr = 0x60c;
const OFFSET_TAG_CONTROL: RvAddr = 0x610;
const OFFSET_TAG_STATUS: RvAddr = 0x614;
#[test]
fn test_name() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
let name0 = hmac.read(RvSize::Word, OFFSET_NAME0).unwrap();
let name0 = String::from_utf8_lossy(&name0.to_le_bytes()).to_string();
assert_eq!(name0, "hmac");
let name1 = hmac.read(RvSize::Word, OFFSET_NAME1).unwrap();
let name1 = String::from_utf8_lossy(&name1.to_le_bytes()).to_string();
assert_eq!(name1, "sha2");
}
#[test]
fn test_version() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
let version0 = hmac.read(RvSize::Word, OFFSET_VERSION0).unwrap();
let version0 = String::from_utf8_lossy(&version0.to_le_bytes()).to_string();
assert_eq!(version0, "1.00");
let version1 = hmac.read(RvSize::Word, OFFSET_VERSION1).unwrap();
let version1 = String::from_utf8_lossy(&version1.to_le_bytes()).to_string();
assert_eq!(version1, "\0\0\0\0");
}
#[test]
fn test_control() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
assert_eq!(hmac.read(RvSize::Word, OFFSET_CONTROL).unwrap(), 0);
}
#[test]
fn test_status() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
assert_eq!(hmac.read(RvSize::Word, OFFSET_STATUS).unwrap(), 1);
}
#[test]
fn test_key() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
for addr in (OFFSET_KEY..(OFFSET_KEY + HMAC_KEY_SIZE_384 as u32)).step_by(4) {
assert_eq!(hmac.write(RvSize::Word, addr, 0xFF).ok(), Some(()));
assert_eq!(
hmac.read(RvSize::Word, addr).err(),
Some(BusError::LoadAccessFault)
);
}
}
#[test]
fn test_block() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
for addr in (OFFSET_BLOCK..(OFFSET_BLOCK + HMAC_BLOCK_SIZE as u32)).step_by(4) {
assert_eq!(hmac.write(RvSize::Word, addr, u32::MAX).ok(), Some(()));
assert_eq!(
hmac.read(RvSize::Word, addr),
Err(BusError::LoadAccessFault)
);
}
}
#[test]
fn test_tag() {
let mut hmac = HmacSha::new(&Clock::new(), KeyVault::new());
for addr in (OFFSET_TAG..(OFFSET_TAG + HMAC_TAG_SIZE_384 as u32)).step_by(4) {
assert_eq!(hmac.read(RvSize::Word, addr).ok(), Some(0));
assert_eq!(
hmac.write(RvSize::Word, addr, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
}
enum KeyVaultAction {
KeyFromVault(u32),
BlockFromVault(u32),
TagToVault(u32),
KeyReadDisallowed(bool),
KeyDisallowedForHMAC(bool),
BlockReadDisallowed(bool),
BlockDisallowedForHMAC(bool),
TagWriteFailTest(bool),
}
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
fn test_hmac(key: &mut [u8], data: &[u8], result: &[u8], keyvault_actions: &[KeyVaultAction]) {
let totalblocks = ((data.len() + 16) + HMAC_BLOCK_SIZE) / HMAC_BLOCK_SIZE;
let totalbytes = totalblocks * HMAC_BLOCK_SIZE;
let mut block_arr = vec![0; totalbytes];
let mut key_via_kv: bool = false;
let mut block_via_kv: bool = false;
let mut tag_to_kv: bool = false;
let mut key_id: u32 = u32::MAX;
let mut block_id: u32 = u32::MAX;
let mut tag_id: u32 = u32::MAX;
let mut tag_le: [u8; 64] = [0; 64];
let mut key_read_disallowed = false;
let mut key_disallowed_for_hmac = false;
let mut block_read_disallowed = false;
let mut tag_write_fail_test = false;
let mut block_disallowed_for_hmac = false;
for action in keyvault_actions.iter() {
match action {
KeyVaultAction::KeyFromVault(id) => {
key_via_kv = true;
key_id = *id;
}
KeyVaultAction::BlockFromVault(id) => {
block_via_kv = true;
block_id = *id;
}
KeyVaultAction::TagToVault(id) => {
tag_to_kv = true;
tag_id = *id;
}
KeyVaultAction::KeyReadDisallowed(val) => {
key_read_disallowed = *val;
}
KeyVaultAction::KeyDisallowedForHMAC(val) => {
key_disallowed_for_hmac = *val;
}
KeyVaultAction::BlockReadDisallowed(val) => {
block_read_disallowed = *val;
}
KeyVaultAction::BlockDisallowedForHMAC(val) => {
block_disallowed_for_hmac = *val;
}
KeyVaultAction::TagWriteFailTest(val) => {
tag_write_fail_test = *val;
}
}
}
if !block_via_kv {
// Compute the total bytes and total blocks required for the final message.
block_arr[..data.len()].copy_from_slice(data);
block_arr[data.len()] = 1 << 7;
let len: u128 = (HMAC_BLOCK_SIZE + data.len()) as u128;
let len = len * 8;
block_arr[totalbytes - 16..].copy_from_slice(&len.to_be_bytes());
block_arr.to_big_endian();
}
let clock = Clock::new();
key.to_big_endian();
let mut key_vault = KeyVault::new();
if key_via_kv {
key_vault.write_key(key_id, key, 0x3F).unwrap();
if key_read_disallowed {
let val_reg = InMemoryRegister::<u32, key_vault::KV_CONTROL::Register>::new(0);
val_reg.write(key_vault::KV_CONTROL::USE_LOCK.val(1)); // Key read disabled.
assert_eq!(
key_vault
.write(
RvSize::Word,
KeyVault::KEY_CONTROL_REG_OFFSET
+ (key_id * KeyVault::KEY_CONTROL_REG_WIDTH),
val_reg.get()
)
.ok(),
Some(())
);
} else if key_disallowed_for_hmac {
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_key(true);
let val_reg = InMemoryRegister::<u32, key_vault::KV_CONTROL::Register>::new(0);
val_reg.write(key_vault::KV_CONTROL::USAGE.val(!(u32::from(key_usage)))); // Key disallowed for hmac.
assert_eq!(
key_vault
.write(
RvSize::Word,
KeyVault::KEY_CONTROL_REG_OFFSET
+ (key_id * KeyVault::KEY_CONTROL_REG_WIDTH),
val_reg.get()
)
.ok(),
Some(())
);
}
}
if block_via_kv {
let mut data = data.to_vec();
data.to_big_endian(); // Keys are stored in big-endian format.
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_data(true);
key_vault
.write_key(block_id, &data, u32::from(key_usage))
.unwrap();
if block_read_disallowed {
let val_reg = InMemoryRegister::<u32, key_vault::KV_CONTROL::Register>::new(0);
val_reg.write(key_vault::KV_CONTROL::USE_LOCK.val(1)); // Key read disabled.
assert_eq!(
key_vault
.write(
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/mailbox.rs | sw-emulator/lib/periph/src/mailbox.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mailbox.rs
Abstract:
File contains MAILBOX implementation
--*/
use smlang::statemachine;
use caliptra_emu_bus::{AlignedRam, Bus, BusMmio, Clock, Timer};
use caliptra_emu_bus::{BusError, ReadOnlyRegister, ReadWriteRegister, WriteOnlyRegister};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use std::{cell::RefCell, rc::Rc};
use tock_registers::interfaces::Writeable;
use tock_registers::{register_bitfields, LocalRegisterCopy};
// Mailbox size when in subsystem mode.
const MBOX_SIZE_SUBSYSTEM: usize = 16 << 10;
// Mailbox size when in passive mode.
const MBOX_SIZE_PASSIVE: usize = 256 << 10;
register_bitfields! [
u32,
/// Control Register Fields
Status [
STATUS OFFSET(0) NUMBITS(4) [
CMD_BUSY = 0x0,
DATA_READY = 0x1,
CMD_COMPLETE = 0x2,
CMD_FAILURE = 0x3,
],
ECC_SINGLE_ERROR OFFSET(4) NUMBITS(1) [],
ECC_DOUBLE_ERROR OFFSET(5) NUMBITS(1) [],
MBOX_FSM_PS OFFSET(6) NUMBITS(3) [
MBOX_IDLE = 0x0,
MBOX_RDY_FOR_CMD = 0x1,
MBOX_RDY_FOR_DLEN = 0x3,
MBOX_RDY_FOR_DATA = 0x2,
MBOX_EXECUTE_UC = 0x6,
MBOX_EXECUTE_SOC = 0x4,
MBOX_ERROR = 0x7,
],
SOC_HAS_LOCK OFFSET(9) NUMBITS(1) [],
RSVD OFFSET(10) NUMBITS(22) [],
],
];
type StatusRegister = LocalRegisterCopy<u32, Status::Register>;
#[derive(Clone)]
pub struct MailboxRam {
ram: Rc<RefCell<AlignedRam>>,
}
impl MailboxRam {
pub fn new(subsystem_mode: bool) -> Self {
let mbox_len = if subsystem_mode {
MBOX_SIZE_SUBSYSTEM
} else {
MBOX_SIZE_PASSIVE
};
Self {
ram: Rc::new(RefCell::new(AlignedRam::new(vec![0u8; mbox_len]))),
}
}
}
impl Bus for MailboxRam {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.ram.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
self.ram.borrow_mut().write(size, addr, val)?;
Ok(())
}
}
impl Default for MailboxRam {
fn default() -> Self {
Self::new(false)
}
}
#[derive(Clone)]
pub struct MailboxExternal {
pub soc_user: MailboxRequester,
pub regs: Rc<RefCell<MailboxRegs>>,
}
impl MailboxExternal {
pub fn regs(&mut self) -> caliptra_registers::mbox::RegisterBlock<BusMmio<Self>> {
unsafe {
caliptra_registers::mbox::RegisterBlock::new_with_mmio(
std::ptr::null_mut::<u32>(),
BusMmio::new(self.clone()),
)
}
}
}
impl Bus for MailboxExternal {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
let mut regs = self.regs.borrow_mut();
regs.set_request(self.soc_user);
let result = regs.read(size, addr);
regs.set_request(MailboxRequester::Caliptra);
result
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
let mut regs = self.regs.borrow_mut();
regs.set_request(self.soc_user);
let result = regs.write(size, addr, val);
regs.set_request(MailboxRequester::Caliptra);
result
}
}
#[derive(Clone)]
pub struct MailboxInternal {
regs: Rc<RefCell<MailboxRegs>>,
}
/// Mailbox Peripheral
impl MailboxInternal {
pub fn new(clock: &Clock, ram: MailboxRam) -> Self {
Self {
regs: Rc::new(RefCell::new(MailboxRegs::new(clock, ram))),
}
}
pub fn regs(&mut self) -> caliptra_registers::mbox::RegisterBlock<BusMmio<Self>> {
unsafe {
caliptra_registers::mbox::RegisterBlock::new_with_mmio(
std::ptr::null_mut::<u32>(),
BusMmio::new(self.clone()),
)
}
}
pub fn mailbox_regs(&mut self) -> Rc<RefCell<MailboxRegs>> {
self.regs.clone()
}
pub fn as_external(&self, soc_user: MailboxRequester) -> MailboxExternal {
MailboxExternal {
soc_user,
regs: self.regs.clone(),
}
}
pub fn get_notif_irq(&mut self) -> bool {
let mut regs = self.regs.borrow_mut();
if regs.irq {
regs.irq = false;
return true;
}
false
}
}
impl Bus for MailboxInternal {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.regs
.borrow_mut()
.set_request(MailboxRequester::Caliptra);
self.regs.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
self.regs
.borrow_mut()
.set_request(MailboxRequester::Caliptra);
self.regs.borrow_mut().write(size, addr, val)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MailboxRequester {
Caliptra,
SocUser(u32),
}
impl From<u32> for MailboxRequester {
fn from(value: u32) -> Self {
match value {
0xFFFF_FFFF => MailboxRequester::Caliptra,
_ => MailboxRequester::SocUser(value),
}
}
}
impl From<MailboxRequester> for u32 {
fn from(val: MailboxRequester) -> Self {
match val {
MailboxRequester::Caliptra => 0xFFFF_FFFF,
MailboxRequester::SocUser(pauser) => pauser,
}
}
}
/// Mailbox Peripheral
#[derive(Bus)]
pub struct MailboxRegs {
/// MBOX_LOCK register
#[register(offset = 0x0000_0000, read_fn = read_lock)]
lock: ReadOnlyRegister<u32>,
/// MBOX_USER register
#[register(offset = 0x0000_0004, read_fn = read_user)]
user: ReadOnlyRegister<u32>,
/// MBOX_CMD register
#[register(offset = 0x0000_0008, write_fn = write_cmd, read_fn = read_cmd)]
_cmd: ReadWriteRegister<u32>,
/// MBOX_DLEN register
#[register(offset = 0x0000_000c, write_fn = write_dlen, read_fn = read_dlen)]
_dlen: ReadWriteRegister<u32>,
/// MBOX_DATAIN register
#[register(offset = 0x0000_0010, write_fn = write_din)]
data_in: WriteOnlyRegister<u32>,
/// MBOX_DATAOUT register
#[register(offset = 0x0000_0014, read_fn = read_dout)]
data_out: ReadOnlyRegister<u32>,
/// MBOX_EXECUTE register
#[register(offset = 0x0000_0018, write_fn = write_ex)]
execute: ReadWriteRegister<u32>,
/// MBOX_STATUS register
#[register(offset = 0x0000_001c, write_fn = write_status, read_fn = read_status)]
_status: ReadWriteRegister<u32>,
/// MBOX_UNLOCK register
#[register(offset = 0x0000_0020, write_fn = write_unlock, read_fn = read_unlock)]
_unlock: ReadWriteRegister<u32>,
/// MBOX_TAP_MODE register
#[register(offset = 0x0000_0024)]
_tap_mode: ReadWriteRegister<u32>,
/// State Machine
state_machine: StateMachine<Context>,
pub requester: MailboxRequester,
/// Trigger interrupt
irq: bool,
/// Timer
timer: Timer,
}
impl MailboxRegs {
/// LOCK Register Value
const LOCK_VAL: RvData = 0x0;
const USER_VAL: RvData = 0x0;
const CMD_VAL: RvData = 0x0;
const DLEN_VAL: RvData = 0x0;
const DATA_IN_VAL: RvData = 0x0;
const DATA_OUT_VAL: RvData = 0x0;
const EXEC_VAL: RvData = 0x0;
const STATUS_VAL: RvData = 0x0;
const UNLOCK_VAL: RvData = 0x0;
/// Create a new instance of Mailbox registers
pub fn new(clock: &Clock, ram: MailboxRam) -> Self {
Self {
lock: ReadOnlyRegister::new(Self::LOCK_VAL),
user: ReadOnlyRegister::new(Self::USER_VAL),
_cmd: ReadWriteRegister::new(Self::CMD_VAL),
_dlen: ReadWriteRegister::new(Self::DLEN_VAL),
data_in: WriteOnlyRegister::new(Self::DATA_IN_VAL),
data_out: ReadOnlyRegister::new(Self::DATA_OUT_VAL),
execute: ReadWriteRegister::new(Self::EXEC_VAL),
_status: ReadWriteRegister::new(Self::STATUS_VAL),
_unlock: ReadWriteRegister::new(Self::UNLOCK_VAL),
_tap_mode: ReadWriteRegister::new(0),
state_machine: StateMachine::new(Context::new(ram)),
requester: MailboxRequester::Caliptra,
irq: false,
timer: Timer::new(clock),
}
}
pub fn set_request(&mut self, requester: MailboxRequester) {
self.requester = requester;
}
// Todo: Implement read_lock callback fn
pub fn read_lock(&mut self, _size: RvSize) -> Result<u32, BusError> {
// If state is not idle mailbox is locked.
let result = match self.state_machine.state() {
States::Idle => Ok(0),
_ => Ok(1),
};
// Deliver event to the state machine.
let _ = self
.state_machine
.process_event(Events::RdLock(self.requester));
result
}
// Todo: Implement read_user callback fn
pub fn read_user(&self, _size: RvSize) -> Result<MailboxRequester, BusError> {
Ok(self.state_machine.context.user)
}
// Todo: Implement write cmd callback fn
pub fn write_cmd(&mut self, _size: RvSize, val: RvData) -> Result<(), BusError> {
let _ = self.state_machine.process_event(Events::CmdWrite(Cmd(val)));
Ok(())
}
// Todo: Implement read cmd callback fn
pub fn read_cmd(&self, _size: RvSize) -> Result<u32, BusError> {
Ok(self.state_machine.context.cmd)
}
// Todo: Implement write dlen callback fn
pub fn write_dlen(&mut self, _size: RvSize, val: RvData) -> Result<(), BusError> {
let _ = self
.state_machine
.process_event(Events::DlenWrite(DataLength(val)));
Ok(())
}
// Todo: Implement read dlen callback fn
pub fn read_dlen(&self, _size: RvSize) -> Result<u32, BusError> {
Ok(self.state_machine.context.dlen)
}
// Todo: Implement write din callback fn
pub fn write_din(&mut self, _size: RvSize, val: RvData) -> Result<(), BusError> {
let _ = self
.state_machine
.process_event(Events::DataWrite(DataIn(val)));
Ok(())
}
// Todo: Implement read dout callback fn
pub fn read_dout(&mut self, _size: RvSize) -> Result<u32, BusError> {
let mb = &mut self.state_machine;
let _ = mb.process_event(Events::DataRead);
Ok(mb.context.data_out)
}
/// Write to execute register
pub fn write_ex(&mut self, _size: RvSize, val: RvData) -> Result<(), BusError> {
// Only the lock owner can clear the execute bit.
if self.requester != self.state_machine.context.user {
let _ = self.state_machine.process_event(Events::Error);
return Ok(());
}
let event = {
match self.requester {
MailboxRequester::Caliptra => {
if val & 1 != 0 {
Events::UcExecSet
} else {
Events::UcExecClear
}
}
_ => {
if val & 1 != 0 {
Events::SocExecSet
} else {
Events::SocExecClear
}
}
}
};
// Notify soc_reg
self.irq = true;
self.timer.schedule_poll_in(1);
let _ = self.state_machine.process_event(event);
self.execute.reg.set(val);
Ok(())
}
// Todo: Implement write status callback fn
pub fn write_status(&mut self, _size: RvSize, val: RvData) -> Result<(), BusError> {
// Send event to state machine.
let _ = self.state_machine.process_event(Events::SetStatus);
let val = LocalRegisterCopy::<u32, Status::Register>::new(val);
self.state_machine
.context
.status
.write(Status::STATUS.val(val.read(Status::STATUS)));
Ok(())
}
// Todo: Implement read status callback fn
pub fn read_status(&self, _size: RvSize) -> Result<u32, BusError> {
let mut result = self.state_machine.context.status;
result.modify(match self.state_machine.state {
States::ExecUc => Status::MBOX_FSM_PS::MBOX_EXECUTE_UC,
States::ExecSoc => Status::MBOX_FSM_PS::MBOX_EXECUTE_SOC,
States::Idle => Status::MBOX_FSM_PS::MBOX_IDLE,
States::RdyForCmd => Status::MBOX_FSM_PS::MBOX_RDY_FOR_CMD,
States::RdyForData => Status::MBOX_FSM_PS::MBOX_RDY_FOR_DATA,
States::RdyForDlen => Status::MBOX_FSM_PS::MBOX_RDY_FOR_DLEN,
States::Error => Status::MBOX_FSM_PS::MBOX_ERROR,
});
Ok(result.get())
}
pub fn write_unlock(&mut self, _size: RvSize, _val: RvData) -> Result<(), BusError> {
let _ = self.state_machine.process_event(Events::WrUnlock);
Ok(())
}
pub fn read_unlock(&self, _size: RvSize) -> Result<u32, BusError> {
Ok(self.state_machine.context.unlock)
}
}
#[derive(PartialEq)]
/// Data length
pub struct DataLength(pub u32);
#[derive(PartialEq)]
/// Data In
pub struct DataIn(pub u32);
#[derive(PartialEq)]
/// Data length
pub struct Owner(pub u32);
#[derive(PartialEq)]
/// Data length
pub struct Cmd(pub u32);
statemachine! {
transitions: {
// CurrentState Event [guard] / action = NextState
//move from idle to rdy for command when lock is acquired.
*Idle + RdLock(MailboxRequester) [is_not_locked] / lock = RdyForCmd,
//move from rdy for cmd to rdy for dlen when cmd is written to.
RdyForCmd + CmdWrite(Cmd) / set_cmd = RdyForDlen,
RdyForCmd + WrUnlock / unlock_and_reset = Idle,
//move from rdy for dlen to rdy for data when dlen is written to.
RdyForDlen + DlenWrite(DataLength) / init_dlen = RdyForData,
RdyForDlen + WrUnlock = Idle,
RdyForData + DataWrite(DataIn) / enqueue = RdyForData,
RdyForData + WrUnlock / unlock_and_reset = Idle,
//move from rdy for data to execute uc when soc sets execute bit.
RdyForData + SocExecSet = ExecUc,
//move from rdy for data to execute soc when soc sets execute bit.
RdyForData + UcExecSet = ExecSoc,
ExecUc + DataRead / dequeue = ExecUc,
ExecUc + DlenWrite(DataLength) / init_dlen = ExecUc,
ExecUc + DataWrite(DataIn) / enqueue = ExecUc,
ExecUc + SocExecClear [is_locked] / unlock = Idle,
ExecUc + UcExecClear [is_locked] / unlock = Idle,
ExecUc + SetStatus = ExecSoc,
ExecUc + WrUnlock / unlock_and_reset = Idle,
ExecSoc + DataRead / dequeue = ExecSoc,
ExecSoc + DlenWrite(DataLength) / init_dlen = ExecSoc,
ExecSoc + DataWrite(DataIn) / enqueue = ExecSoc,
ExecSoc + UcExecClear [is_locked] / unlock = Idle,
ExecSoc + SocExecClear [is_locked] / unlock = Idle,
ExecSoc + Error = Error,
ExecSoc + SetStatus = ExecUc,
ExecSoc + WrUnlock / unlock_and_reset = Idle,
Error + WrUnlock / unlock_and_reset = Idle,
}
}
/// State machine extended variables.
pub struct Context {
/// lock state
pub locked: u32,
/// Who acquired the lock.
pub user: MailboxRequester,
/// number of data elements
pub dlen: u32,
/// Fifo storage
pub fifo: Fifo,
/// Mailbox Status
status: StatusRegister,
/// Command
pub cmd: u32,
// data_out
data_out: u32,
// unlock
pub unlock: u32,
}
impl Context {
fn new(ram: MailboxRam) -> Self {
Self {
locked: 0,
user: MailboxRequester::Caliptra,
dlen: 0,
status: LocalRegisterCopy::new(0),
fifo: Fifo::new(ram),
cmd: 0,
data_out: 0,
unlock: 0,
}
}
}
impl StateMachineContext for Context {
// guards
fn is_not_locked(&self, _user: &MailboxRequester) -> Result<bool, ()> {
if self.locked == 1 {
// no transition
Err(())
} else {
Ok(true)
}
}
fn is_locked(&self) -> Result<bool, ()> {
if self.locked != 0 {
Ok(true)
} else {
// no transition
Err(())
}
}
//fn is_not_busy(&mut self, event_data: &StatusRegister) -> Result<(), ()> {
// let status = event_data.read(Status::STATUS);
// if status != Status::STATUS::CMD_BUSY.value {
// Ok(())
// } else {
// no transition
// Err(())
// }
//}
// actions
fn init_dlen(&mut self, data_len: DataLength) -> Result<(), ()> {
self.fifo.reset();
self.dlen = data_len.0;
self.fifo.latch_dlen(self.dlen as usize);
Ok(())
}
fn set_cmd(&mut self, cmd: Cmd) -> Result<(), ()> {
self.cmd = cmd.0;
Ok(())
}
fn lock(&mut self, user: MailboxRequester) -> Result<(), ()> {
self.fifo.reset();
self.locked = 1;
self.user = user;
Ok(())
}
fn unlock(&mut self) -> Result<(), ()> {
self.locked = 0;
// Reset status
self.status.set(0);
Ok(())
}
fn dequeue(&mut self) -> Result<(), ()> {
self.data_out = self.fifo.dequeue().unwrap_or(0);
Ok(())
}
fn enqueue(&mut self, data_in: DataIn) -> Result<(), ()> {
self.fifo.enqueue(data_in.0);
Ok(())
}
fn unlock_and_reset(&mut self) -> Result<(), ()> {
self.unlock()?;
self.fifo.reset();
Ok(())
}
}
pub struct Fifo {
latched_dlen: u32,
capacity: usize,
read_index: usize,
write_index: usize,
mailbox_ram: MailboxRam,
}
impl Fifo {
pub fn new(ram: MailboxRam) -> Self {
let ram_size = ram.ram.borrow().data().len();
Fifo {
latched_dlen: 0,
capacity: ram_size,
read_index: 0,
write_index: 0,
mailbox_ram: ram,
}
}
pub fn latch_dlen(&mut self, dlen: usize) {
if dlen > self.capacity {
self.latched_dlen = self.capacity as u32;
return;
}
self.latched_dlen = dlen as u32;
}
pub fn enqueue(&mut self, element: u32) {
// On buffer full condition, ignore the write.
if self.write_index < self.capacity {
self.mailbox_ram
.write(RvSize::Word, self.write_index as u32, element)
.unwrap();
self.write_index += RvSize::Word as usize;
}
}
pub fn dequeue(&mut self) -> Result<u32, ()> {
if self.read_index >= self.latched_dlen as usize {
return Err(());
}
let element = self
.mailbox_ram
.read(RvSize::Word, self.read_index as u32)
.unwrap();
self.read_index += RvSize::Word as usize;
Ok(element)
}
pub fn reset(&mut self) {
self.read_index = 0;
self.write_index = 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
pub fn get_mailbox() -> MailboxInternal {
// Acquire lock
MailboxInternal::new(&Clock::new(), MailboxRam::default())
}
#[test]
fn test_sm_arc_rdyfordata_unlock() {
// Acquire lock
let mut mb = get_mailbox();
let uc_regs = mb.regs();
assert!(!uc_regs.lock().read().lock());
// Confirm it is locked
assert!(uc_regs.lock().read().lock());
assert_eq!(uc_regs.user().read(), 0xFFFF_FFFF);
// Write command
uc_regs.cmd().write(|_| 0x55);
// Confirm it is locked
assert_eq!(mb.regs.borrow().state_machine.context.locked, 1);
// Release lock
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::WrUnlock);
// Check transition to idle
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::Idle
));
}
#[test]
fn test_sm_arc_rdyforcmd_unlock() {
let mb = get_mailbox();
assert_eq!(mb.regs.borrow().state_machine.context().locked, 0);
assert_eq!(mb.regs.borrow().state_machine.context().dlen, 0);
// Acquire lock
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::RdLock(MailboxRequester::Caliptra));
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::RdyForCmd
));
assert_eq!(mb.regs.borrow().state_machine.context().locked, 1);
// Release lock
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::WrUnlock);
assert_eq!(mb.regs.borrow().state_machine.context().locked, 0);
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::Idle
));
}
#[test]
fn test_soc_to_caliptra_lock() {
let mut caliptra = MailboxInternal::new(&Clock::new(), MailboxRam::default());
let mut soc = caliptra.as_external(MailboxRequester::SocUser(1u32));
let soc_regs = soc.regs();
assert!(!soc_regs.lock().read().lock());
// Confirm it is locked
assert!(soc_regs.lock().read().lock());
// Confirm caliptra has lock
let caliptra_has_lock = caliptra.regs().lock().read().lock();
assert!(caliptra_has_lock);
}
#[test]
fn test_send_receive() {
let request_to_send: [u32; 4] = [0x1111_1111, 0x2222_2222, 0x3333_3333, 0x4444_4444];
let mut caliptra = MailboxInternal::new(&Clock::new(), MailboxRam::default());
let mut soc = caliptra.as_external(MailboxRequester::SocUser(1u32));
let soc_regs = soc.regs();
let uc_regs = caliptra.regs();
assert!(!soc_regs.lock().read().lock());
// Confirm it is locked
assert!(soc_regs.lock().read().lock());
assert_eq!(
MailboxRequester::SocUser(soc_regs.user().read()),
MailboxRequester::SocUser(1u32)
);
// Write command
soc_regs.cmd().write(|_| 0x55);
// Confirm it is locked
assert_eq!(soc.regs.borrow().state_machine.context.locked, 1);
let dlen = request_to_send.len() as u32;
let dlen = dlen * 4;
// Write dlen
soc_regs.dlen().write(|_| dlen);
// Confirm it is locked
assert_eq!(soc.regs.borrow().state_machine.context.locked, 1);
for data_in in request_to_send.iter() {
// Write datain
soc_regs.datain().write(|_| *data_in);
// Confirm it is locked
assert_eq!(soc.regs.borrow().state_machine.context.locked, 1);
}
soc_regs.status().write(|w| w.status(|w| w.data_ready()));
// Write exec
soc_regs.execute().write(|w| w.execute(true));
// Confirm it is locked
assert_eq!(soc.regs.borrow().state_machine.context.locked, 1);
assert!(matches!(
soc.regs.borrow().state_machine.state(),
States::ExecUc
));
assert_eq!(
u32::from(uc_regs.status().read()),
(Status::STATUS::DATA_READY + Status::MBOX_FSM_PS::MBOX_EXECUTE_UC).value
);
assert_eq!(uc_regs.cmd().read(), 0x55);
let dlen = uc_regs.dlen().read();
assert_eq!(dlen, (request_to_send.len() * 4) as u32);
request_to_send.iter().for_each(|data_in| {
// Read dataout
let data_out = uc_regs.dataout().read();
// compare with queued data.
assert_eq!(*data_in, data_out);
});
uc_regs.status().write(|w| w.status(|w| w.cmd_complete()));
// Requester resets exec register
soc_regs.execute().write(|w| w.execute(false));
// Confirm it is unlocked
assert_eq!(caliptra.regs.borrow().state_machine.context.locked, 0);
assert!(matches!(
caliptra.regs.borrow().state_machine.state(),
States::Idle
));
}
#[test]
fn test_sm_init() {
let mb = get_mailbox();
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::Idle
));
assert_eq!(mb.regs.borrow().state_machine.context().locked, 0);
}
#[test]
fn test_sm_lock() {
let mb = get_mailbox();
assert_eq!(mb.regs.borrow().state_machine.context().locked, 0);
assert_eq!(mb.regs.borrow().state_machine.context().dlen, 0);
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::RdLock(MailboxRequester::Caliptra));
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::RdyForCmd
));
assert_eq!(mb.regs.borrow().state_machine.context().locked, 1);
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::CmdWrite(Cmd(0x55)));
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::RdyForDlen
));
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::DlenWrite(DataLength(0x55)));
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::RdyForData
));
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::UcExecSet);
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::ExecSoc
));
let _ = mb
.regs
.borrow_mut()
.state_machine
.process_event(Events::UcExecClear);
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::Idle
));
assert_eq!(mb.regs.borrow().state_machine.context().locked, 0);
}
#[test]
fn test_send_receive_max_limit() {
// Acquire lock
let mut mb = get_mailbox();
let uc_regs = mb.regs();
assert!(!uc_regs.lock().read().lock());
// Confirm it is locked
assert!(uc_regs.lock().read().lock());
let user = uc_regs.user().read();
assert_eq!(MailboxRequester::from(user), MailboxRequester::Caliptra);
// Write command
uc_regs.cmd().write(|_| 0x55);
// Write dlen
uc_regs.dlen().write(|_| (MBOX_SIZE_PASSIVE + 4) as u32);
for data_in in (0..MBOX_SIZE_PASSIVE).step_by(4) {
// Write datain
uc_regs.datain().write(|_| data_in as u32);
}
// Write an additional DWORD. This should be a no-op.
uc_regs.datain().write(|_| 0xDEADBEEF);
uc_regs.status().write(|w| w.status(|w| w.data_ready()));
uc_regs.execute().write(|w| w.execute(true));
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::ExecSoc
));
assert_eq!(
u32::from(uc_regs.status().read()),
(Status::STATUS::DATA_READY + Status::MBOX_FSM_PS::MBOX_EXECUTE_SOC).value
);
assert_eq!(uc_regs.cmd().read(), 0x55);
assert_eq!(uc_regs.dlen().read(), (MBOX_SIZE_PASSIVE + 4) as u32);
for data_in in (0..MBOX_SIZE_PASSIVE).step_by(4) {
// Read dataout
let data_out = uc_regs.dataout().read();
// compare with queued data.
assert_eq!(data_in as u32, data_out);
}
// Read an additional DWORD. This should return zero
assert_eq!(uc_regs.dataout().read(), 0);
uc_regs.status().write(|w| w.status(|w| w.cmd_complete()));
// Receiver resets exec register
uc_regs.execute().write(|w| w.execute(false));
// Confirm it is unlocked
assert_eq!(mb.regs.borrow().state_machine.context.locked, 0);
assert!(matches!(
mb.regs.borrow().state_machine.state(),
States::Idle
));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/lib.rs | sw-emulator/lib/periph/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains exports for for Caliptra Emulator Peripheral library.
--*/
#[macro_use]
extern crate arrayref;
mod abr;
mod aes;
mod aes_clp;
mod asym_ecc384;
mod csrng;
pub mod dma;
mod doe;
mod emu_ctrl;
mod hash_sha256;
mod hash_sha3;
mod hash_sha512;
mod helpers;
mod hmac;
mod iccm;
mod key_vault;
mod mailbox;
pub mod mci;
mod root_bus;
mod sha512_acc;
pub mod soc_reg;
mod uart;
pub use aes::Aes;
pub use aes_clp::AesClp;
pub use asym_ecc384::AsymEcc384;
pub use csrng::Csrng;
pub use dma::Dma;
pub use doe::Doe;
pub use emu_ctrl::EmuCtrl;
pub use hash_sha256::HashSha256;
pub use hash_sha3::HashSha3;
pub use hash_sha512::HashSha512;
pub use hmac::HmacSha;
pub use iccm::Iccm;
pub use key_vault::KeyUsage;
pub use key_vault::KeyVault;
pub use mailbox::{MailboxExternal, MailboxInternal, MailboxRam, MailboxRequester};
pub use mci::Mci;
pub use root_bus::{
ActionCb, CaliptraRootBus, CaliptraRootBusArgs, DownloadIdevidCsrCb, ReadyForFwCb,
SocToCaliptraBus, TbServicesCb, UploadUpdateFwCb,
};
pub use sha512_acc::Sha512Accelerator;
pub use soc_reg::SocRegistersInternal;
pub use uart::Uart;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/mci.rs | sw-emulator/lib/periph/src/mci.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mci.rs
Abstract:
File contains implementation of MCI
--*/
use std::{cell::RefCell, rc::Rc, sync::mpsc};
use bitfield::size_of;
use caliptra_emu_bus::{Bus, BusError, Device, Event, EventData};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use sha2::{Digest, Sha384};
const SS_MANUF_DBG_UNLOCK_FUSE_SIZE: usize = 48;
const SS_MANUF_DBG_UNLOCK_NUMBER_OF_FUSES: usize = 8;
const NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK: u32 = 0x2;
#[derive(Bus)]
pub struct MciRegs {
pub event_sender: Option<mpsc::Sender<Event>>,
#[register(offset = 0x0)]
pub hw_capabilities: u32,
#[register(offset = 0x4)]
pub fw_capabilities: u32,
#[register(offset = 0x8)]
pub cap_lock: u32,
#[register(offset = 0xc)]
pub hw_rev_id: u32,
#[register_array(offset = 0x10)]
pub fw_rev_id: [u32; 2],
#[register(offset = 0x18)]
pub hw_config0: u32,
#[register(offset = 0x1c)]
pub hw_config1: u32,
#[register(offset = 0x20)]
pub mcu_ifu_axi_user: u32,
#[register(offset = 0x24)]
pub mcu_lsu_axi_user: u32,
#[register(offset = 0x28)]
pub mcu_sram_config_axi_user: u32,
#[register(offset = 0x2c)]
pub mci_soc_config_axi_user: u32,
#[register(offset = 0x30)]
pub flow_status: u32,
#[register(offset = 0x34)]
pub hw_flow_status: u32,
#[register(offset = 0x38)]
pub reset_reason: u32,
#[register(offset = 0x3c)]
pub reset_status: u32,
#[register(offset = 0x40)]
pub security_state: u32,
#[register(offset = 0x50)]
pub hw_error_fatal: u32,
#[register(offset = 0x54)]
pub agg_error_fatal: u32,
#[register(offset = 0x58)]
pub hw_error_non_fatal: u32,
#[register(offset = 0x5c)]
pub agg_error_non_fatal: u32,
#[register(offset = 0x60)]
pub fw_error_fatal: u32,
#[register(offset = 0x64)]
pub fw_error_non_fatal: u32,
#[register(offset = 0x68)]
pub hw_error_enc: u32,
#[register(offset = 0x6c)]
pub fw_error_enc: u32,
#[register_array(offset = 0x70)]
pub fw_extended_error_info: [u32; 8],
#[register(offset = 0x90)]
pub internal_hw_error_fatal_mask: u32,
#[register(offset = 0x94)]
pub internal_hw_error_non_fatal_mask: u32,
#[register(offset = 0x98)]
pub internal_agg_error_fatal_mask: u32,
#[register(offset = 0x9c)]
pub internal_agg_error_non_fatal_mask: u32,
#[register(offset = 0xa0)]
pub internal_fw_error_fatal_mask: u32,
#[register(offset = 0xa4)]
pub internal_fw_error_non_fatal_mask: u32,
#[register(offset = 0xb0)]
pub wdt_timer1_en: u32,
#[register(offset = 0xb4)]
pub wdt_timer1_ctrl: u32,
#[register_array(offset = 0xb8)]
pub wdt_timer1_timeout_period: [u32; 2],
#[register(offset = 0xc0)]
pub wdt_timer2_en: u32,
#[register(offset = 0xc4)]
pub wdt_timer2_ctrl: u32,
#[register_array(offset = 0xc8)]
pub wdt_timer2_timeout_period: [u32; 2],
#[register(offset = 0xd0)]
pub wdt_status: u32,
#[register_array(offset = 0xd4)]
pub wdt_cfg: [u32; 2],
#[register(offset = 0xe0)]
pub mcu_timer_config: u32,
#[register(offset = 0xe4)]
pub mcu_rv_mtime_l: u32,
#[register(offset = 0xe8)]
pub mcu_rv_mtime_h: u32,
#[register(offset = 0xec)]
pub mcu_rv_mtimecmp_l: u32,
#[register(offset = 0xf0)]
pub mcu_rv_mtimecmp_h: u32,
#[register(offset = 0x100)]
pub reset_request: u32,
#[register(offset = 0x104)]
pub mci_bootfsm_go: u32,
#[register(offset = 0x108)]
pub cptra_boot_go: u32,
#[register(offset = 0x10c)]
pub fw_sram_exec_region_size: u32,
#[register(offset = 0x110)]
pub mcu_nmi_vector: u32,
#[register(offset = 0x114)]
pub mcu_reset_vector: u32,
#[register_array(offset = 0x180)]
pub mbox0_valid_axi_user: [u32; 5],
#[register_array(offset = 0x1a0)]
pub mbox0_axi_user_lock: [u32; 5],
#[register_array(offset = 0x1c0)]
pub mbox1_valid_axi_user: [u32; 5],
#[register_array(offset = 0x1e0)]
pub mbox1_axi_user_lock: [u32; 5],
#[register_array(offset = 0x300)]
pub soc_dft_en: [u32; 2],
#[register_array(offset = 0x308)]
pub soc_hw_debug_en: [u32; 2],
#[register_array(offset = 0x310)]
pub soc_prod_debug_state: [u32; 2],
#[register(offset = 0x318)]
pub fc_fips_zerozation: u32,
#[register_array(offset = 0x400)]
pub generic_input_wires: [u32; 2],
#[register_array(offset = 0x408)]
pub generic_output_wires: [u32; 2],
#[register(offset = 0x410)]
pub debug_in: u32,
#[register(offset = 0x414)]
pub debug_out: u32,
#[register(offset = 0x418)]
pub ss_debug_intent: u32,
#[register(offset = 0x440)]
pub ss_config_done_sticky: u32,
#[register(offset = 0x444)]
pub ss_config_done: u32,
#[register_array(offset = 0x480)]
pub prod_debug_unlock_pk_hash_reg: [u32; 96],
#[register_array(offset = 0xa00)]
fuses: [u32; SS_MANUF_DBG_UNLOCK_FUSE_SIZE / size_of::<u32>()
* SS_MANUF_DBG_UNLOCK_NUMBER_OF_FUSES],
#[register(offset = 0x1000)]
pub intr_block_rf_global_intr_en_r: u32,
#[register(offset = 0x1004)]
pub intr_block_rf_error0_intr_en_r: u32,
#[register(offset = 0x1008)]
pub intr_block_rf_error1_intr_en_r: u32,
#[register(offset = 0x100c)]
pub intr_block_rf_notif0_intr_en_r: u32,
#[register(offset = 0x1010)]
pub intr_block_rf_notif1_intr_en_r: u32,
#[register(offset = 0x1014)]
pub intr_block_rf_error_global_intr_r: u32,
#[register(offset = 0x1018)]
pub intr_block_rf_notif_global_intr_r: u32,
#[register(offset = 0x101c)]
pub intr_block_rf_error0_internal_intr_r: u32,
#[register(offset = 0x1020)]
pub intr_block_rf_error1_internal_intr_r: u32,
#[register(offset = 0x1024)]
pub intr_block_rf_notif0_internal_intr_r: u32,
#[register(offset = 0x1028)]
pub intr_block_rf_notif1_internal_intr_r: u32,
#[register(offset = 0x102c)]
pub intr_block_rf_error0_intr_trig_r: u32,
#[register(offset = 0x1030)]
pub intr_block_rf_error1_intr_trig_r: u32,
#[register(offset = 0x1034, write_fn = on_write_intr_block_rf_notif0_intr_trig_r)]
pub intr_block_rf_notif0_intr_trig_r: u32,
#[register(offset = 0x1038)]
pub intr_block_rf_notif1_intr_trig_r: u32,
#[register(offset = 0x1100)]
pub intr_block_rf_error_internal_intr_count_r: u32,
#[register(offset = 0x1104)]
pub intr_block_rf_error_mbox0_ecc_unc_intr_count_r: u32,
#[register(offset = 0x1108)]
pub intr_block_rf_error_mbox1_ecc_unc_intr_count_r: u32,
#[register(offset = 0x110c)]
pub intr_block_rf_error_mcu_sram_dmi_axi_collision_intr_count_r: u32,
#[register(offset = 0x1110)]
pub intr_block_rf_error_wdt_timer1_timeout_intr_count_r: u32,
#[register(offset = 0x1114)]
pub intr_block_rf_error_wdt_timer2_timeout_intr_count_r: u32,
#[register(offset = 0x1118)]
pub intr_block_rf_error_agg_error_fatal0_intr_count_r: u32,
#[register(offset = 0x111c)]
pub intr_block_rf_error_agg_error_fatal1_intr_count_r: u32,
#[register(offset = 0x1120)]
pub intr_block_rf_error_agg_error_fatal2_intr_count_r: u32,
#[register(offset = 0x1124)]
pub intr_block_rf_error_agg_error_fatal3_intr_count_r: u32,
#[register(offset = 0x1128)]
pub intr_block_rf_error_agg_error_fatal4_intr_count_r: u32,
#[register(offset = 0x112c)]
pub intr_block_rf_error_agg_error_fatal5_intr_count_r: u32,
#[register(offset = 0x1130)]
pub intr_block_rf_error_agg_error_fatal6_intr_count_r: u32,
#[register(offset = 0x1134)]
pub intr_block_rf_error_agg_error_fatal7_intr_count_r: u32,
#[register(offset = 0x1138)]
pub intr_block_rf_error_agg_error_fatal8_intr_count_r: u32,
#[register(offset = 0x113c)]
pub intr_block_rf_error_agg_error_fatal9_intr_count_r: u32,
#[register(offset = 0x1140)]
pub intr_block_rf_error_agg_error_fatal10_intr_count_r: u32,
#[register(offset = 0x1144)]
pub intr_block_rf_error_agg_error_fatal11_intr_count_r: u32,
#[register(offset = 0x1148)]
pub intr_block_rf_error_agg_error_fatal12_intr_count_r: u32,
#[register(offset = 0x114c)]
pub intr_block_rf_error_agg_error_fatal13_intr_count_r: u32,
#[register(offset = 0x1150)]
pub intr_block_rf_error_agg_error_fatal14_intr_count_r: u32,
#[register(offset = 0x1154)]
pub intr_block_rf_error_agg_error_fatal15_intr_count_r: u32,
#[register(offset = 0x1158)]
pub intr_block_rf_error_agg_error_fatal16_intr_count_r: u32,
#[register(offset = 0x115c)]
pub intr_block_rf_error_agg_error_fatal17_intr_count_r: u32,
#[register(offset = 0x1160)]
pub intr_block_rf_error_agg_error_fatal18_intr_count_r: u32,
#[register(offset = 0x1164)]
pub intr_block_rf_error_agg_error_fatal19_intr_count_r: u32,
#[register(offset = 0x1168)]
pub intr_block_rf_error_agg_error_fatal20_intr_count_r: u32,
#[register(offset = 0x116c)]
pub intr_block_rf_error_agg_error_fatal21_intr_count_r: u32,
#[register(offset = 0x1170)]
pub intr_block_rf_error_agg_error_fatal22_intr_count_r: u32,
#[register(offset = 0x1174)]
pub intr_block_rf_error_agg_error_fatal23_intr_count_r: u32,
#[register(offset = 0x1178)]
pub intr_block_rf_error_agg_error_fatal24_intr_count_r: u32,
#[register(offset = 0x117c)]
pub intr_block_rf_error_agg_error_fatal25_intr_count_r: u32,
#[register(offset = 0x1180)]
pub intr_block_rf_error_agg_error_fatal26_intr_count_r: u32,
#[register(offset = 0x1184)]
pub intr_block_rf_error_agg_error_fatal27_intr_count_r: u32,
#[register(offset = 0x1188)]
pub intr_block_rf_error_agg_error_fatal28_intr_count_r: u32,
#[register(offset = 0x118c)]
pub intr_block_rf_error_agg_error_fatal29_intr_count_r: u32,
#[register(offset = 0x1190)]
pub intr_block_rf_error_agg_error_fatal30_intr_count_r: u32,
#[register(offset = 0x1194)]
pub intr_block_rf_error_agg_error_fatal31_intr_count_r: u32,
}
impl MciRegs {
pub const SS_MANUF_DBG_UNLOCK_FUSE_OFFSET: usize = 0xa00;
pub const SS_MANUF_DBG_UNLOCK_NUMBER_OF_FUSES: usize = SS_MANUF_DBG_UNLOCK_NUMBER_OF_FUSES;
pub fn new(key_pairs: Vec<(&[u8; 96], &[u8; 2592])>) -> Self {
Self {
event_sender: None,
hw_capabilities: 0,
fw_capabilities: 0,
cap_lock: 0,
hw_rev_id: 0,
fw_rev_id: [0; 2],
hw_config0: 0,
hw_config1: 0,
mcu_ifu_axi_user: 0,
mcu_lsu_axi_user: 0,
mcu_sram_config_axi_user: 0,
mci_soc_config_axi_user: 0,
flow_status: 0,
hw_flow_status: 0,
reset_reason: 0,
reset_status: 0x2, // MCU on reset
security_state: 0,
hw_error_fatal: 0,
agg_error_fatal: 0,
hw_error_non_fatal: 0,
agg_error_non_fatal: 0,
fw_error_fatal: 0,
fw_error_non_fatal: 0,
hw_error_enc: 0,
fw_error_enc: 0,
fw_extended_error_info: [0; 8],
internal_hw_error_fatal_mask: 0,
internal_hw_error_non_fatal_mask: 0,
internal_agg_error_fatal_mask: 0,
internal_agg_error_non_fatal_mask: 0,
internal_fw_error_fatal_mask: 0,
internal_fw_error_non_fatal_mask: 0,
wdt_timer1_en: 0,
wdt_timer1_ctrl: 0,
wdt_timer1_timeout_period: [0xffff_ffff; 2],
wdt_timer2_en: 0,
wdt_timer2_ctrl: 0,
wdt_timer2_timeout_period: [0xffff_ffff; 2],
wdt_status: 0,
wdt_cfg: [0; 2],
mcu_timer_config: 0,
mcu_rv_mtime_l: 0,
mcu_rv_mtime_h: 0,
mcu_rv_mtimecmp_l: 0,
mcu_rv_mtimecmp_h: 0,
reset_request: 0,
mci_bootfsm_go: 0,
cptra_boot_go: 0,
fw_sram_exec_region_size: 0,
mcu_nmi_vector: 0,
mcu_reset_vector: 0,
mbox0_valid_axi_user: [0; 5],
mbox0_axi_user_lock: [0; 5],
mbox1_valid_axi_user: [0; 5],
mbox1_axi_user_lock: [0; 5],
soc_dft_en: [0; 2],
soc_hw_debug_en: [0; 2],
soc_prod_debug_state: [0; 2],
fc_fips_zerozation: 0,
generic_input_wires: [0; 2],
generic_output_wires: [0; 2],
debug_in: 0,
debug_out: 0,
ss_debug_intent: 0,
ss_config_done_sticky: 0,
ss_config_done: 0,
prod_debug_unlock_pk_hash_reg: [0; 96],
fuses: {
let mut fuses = [0; SS_MANUF_DBG_UNLOCK_FUSE_SIZE / size_of::<u32>()
* SS_MANUF_DBG_UNLOCK_NUMBER_OF_FUSES];
key_pairs.iter().enumerate().for_each(|(i, (ecc, mldsa))| {
// Create a single hasher for the concatenated keys
let mut hasher = Sha384::new();
hasher.update(ecc);
hasher.update(mldsa);
let hash = hasher.finalize();
// Copy hash into fuses array (64 bytes / 16 u32s)
let base_idx = i * (SS_MANUF_DBG_UNLOCK_FUSE_SIZE / size_of::<u32>());
hash.chunks(4).enumerate().for_each(|(j, chunk)| {
// Program the hash in hardware format i.e. little endian.
let value = u32::from_be_bytes(chunk.try_into().unwrap());
fuses[base_idx + j] = value;
});
});
fuses
},
intr_block_rf_global_intr_en_r: 0,
intr_block_rf_error0_intr_en_r: 0,
intr_block_rf_error1_intr_en_r: 0,
intr_block_rf_notif0_intr_en_r: 0,
intr_block_rf_notif1_intr_en_r: 0,
intr_block_rf_error_global_intr_r: 0,
intr_block_rf_notif_global_intr_r: 0,
intr_block_rf_error0_internal_intr_r: 0,
intr_block_rf_error1_internal_intr_r: 0,
intr_block_rf_notif0_internal_intr_r: 0,
intr_block_rf_notif1_internal_intr_r: 0,
intr_block_rf_error0_intr_trig_r: 0,
intr_block_rf_error1_intr_trig_r: 0,
intr_block_rf_notif0_intr_trig_r: 0,
intr_block_rf_notif1_intr_trig_r: 0,
intr_block_rf_error_internal_intr_count_r: 0,
intr_block_rf_error_mbox0_ecc_unc_intr_count_r: 0,
intr_block_rf_error_mbox1_ecc_unc_intr_count_r: 0,
intr_block_rf_error_mcu_sram_dmi_axi_collision_intr_count_r: 0,
intr_block_rf_error_wdt_timer1_timeout_intr_count_r: 0,
intr_block_rf_error_wdt_timer2_timeout_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal0_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal1_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal2_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal3_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal4_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal5_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal6_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal7_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal8_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal9_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal10_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal11_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal12_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal13_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal14_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal15_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal16_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal17_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal18_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal19_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal20_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal21_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal22_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal23_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal24_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal25_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal26_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal27_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal28_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal29_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal30_intr_count_r: 0,
intr_block_rf_error_agg_error_fatal31_intr_count_r: 0,
}
}
fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
println!("[MCI] Registering outgoing events");
self.event_sender = Some(sender);
}
fn cptra_request_mcu_reset(&mut self) {
self.intr_block_rf_notif0_internal_intr_r |= NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK;
if let Some(sender) = &self.event_sender {
sender
.send(Event::new(
Device::CaliptraCore,
Device::MCU,
EventData::MciInterrupt { asserted: true },
))
.unwrap();
}
}
fn on_write_intr_block_rf_notif0_intr_trig_r(
&mut self,
_size: RvSize,
val: RvData,
) -> Result<(), BusError> {
if val & NOTIF_CPTRA_MCU_RESET_REQ_STS_MASK != 0 {
self.cptra_request_mcu_reset();
}
Ok(())
}
}
#[derive(Clone)]
pub struct Mci {
pub regs: Rc<RefCell<MciRegs>>,
}
impl Mci {
/// Create a new instance of SHA-512 Accelerator
pub fn new(key_pairs: Vec<(&[u8; 96], &[u8; 2592])>) -> Self {
Self {
regs: Rc::new(RefCell::new(MciRegs::new(key_pairs))),
}
}
pub fn cptra_request_mcu_reset(&self) {
self.regs.borrow_mut().cptra_request_mcu_reset();
}
}
impl Bus for Mci {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.regs.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
self.regs.borrow_mut().write(size, addr, val)
}
fn poll(&mut self) {
self.regs.borrow_mut().poll();
}
fn warm_reset(&mut self) {
self.regs.borrow_mut().warm_reset();
}
fn update_reset(&mut self) {
self.regs.borrow_mut().update_reset();
}
fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
println!("[MCI] Registering outgoing events");
self.regs
.borrow_mut()
.register_outgoing_events(sender.clone());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/hash_sha512.rs | sw-emulator/lib/periph/src/hash_sha512.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hash_sha512.rs
Abstract:
File contains SHA512 peripheral implementation.
--*/
use crate::helpers::words_from_bytes_le;
use crate::key_vault::KeyUsage;
use crate::KeyVault;
use caliptra_emu_bus::{
ActionHandle, Bus, BusError, Clock, ReadOnlyRegister, ReadWriteMemory, ReadWriteRegister,
Timer, WriteOnlyRegister,
};
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_crypto::{Sha512, Sha512Mode};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use std::cell::RefCell;
use std::rc::Rc;
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use tock_registers::registers::InMemoryRegister;
use zerocopy::IntoBytes;
register_bitfields! [
u32,
/// Control Register Fields
Control [
INIT OFFSET(0) NUMBITS(1) [],
NEXT OFFSET(1) NUMBITS(1) [],
MODE OFFSET(2) NUMBITS(2) [],
ZEROIZE OFFSET(4) NUMBITS(1) [],
LAST OFFSET(5) NUMBITS(1) [],
RESTORE OFFSET(6) NUMBITS(1) [],
],
/// Status Register Fields
Status[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
],
/// Block Read Control Register Fields
BlockReadControl[
KEY_READ_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
PCR_HASH_EXTEND OFFSET(6) NUMBITS(1) [],
],
/// Block Read Status Register Fields
BlockReadStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
KV_SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL= 2,
],
],
/// Hash Write Control Register Fields
HashWriteControl[
KEY_WRITE_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
USAGE OFFSET(6) NUMBITS(6) [],
],
/// Hash Write Status Register Fields
HashWriteStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
KV_SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL= 2,
],
],
/// PCR Gen Hash Control Register Fields
PcrHashControl[
START OFFSET(0) NUMBITS(1) [],
],
/// PCR Gen Hash Status Register Fields
PcrHashStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
],
];
const SHA512_BLOCK_SIZE: usize = 128;
const SHA512_BLOCK_SIZE_WORDS: usize = 128 >> 2;
const SHA512_HASH_SIZE: usize = 64;
/// The number of CPU clock cycles it takes to perform initialization action.
const INIT_TICKS: u64 = 1000;
/// The number of CPU clock cycles it takes to perform the hash update action.
const UPDATE_TICKS: u64 = 1000;
/// The number of CPU clock cycles read and write keys from key vault
const KEY_RW_TICKS: u64 = 100;
fn sha512_block_words_from_bytes_le(
arr: &[u8; SHA512_BLOCK_SIZE],
) -> [u32; SHA512_BLOCK_SIZE_WORDS] {
let mut result = [0u32; SHA512_BLOCK_SIZE_WORDS];
for i in 0..result.len() {
result[i] = u32::from_le_bytes(arr[i * 4..][..4].try_into().unwrap())
}
result
}
fn sha512_block_bytes_from_words_le(
arr: &[u32; SHA512_BLOCK_SIZE_WORDS],
) -> [u8; SHA512_BLOCK_SIZE] {
let mut result = [0u8; SHA512_BLOCK_SIZE];
for i in 0..arr.len() {
result[i * 4..][..4].copy_from_slice(&arr[i].to_le_bytes());
}
result
}
/// SHA-512 Peripheral
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct HashSha512Regs {
/// Name 0 register
#[register(offset = 0x0000_0000)]
name0: ReadOnlyRegister<u32>,
/// Name 1 register
#[register(offset = 0x0000_0004)]
name1: ReadOnlyRegister<u32>,
/// Version 0 register
#[register(offset = 0x0000_0008)]
version0: ReadOnlyRegister<u32>,
/// Version 1 register
#[register(offset = 0x0000_000C)]
version1: ReadOnlyRegister<u32>,
/// Control register
#[register(offset = 0x0000_0010, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
/// Status register
#[register(offset = 0x0000_0018)]
status: ReadOnlyRegister<u32, Status::Register>,
/// SHA512 Block Memory
#[register_array(offset = 0x0000_0080, write_fn = write_block)]
block: [u32; SHA512_BLOCK_SIZE_WORDS],
/// SHA512 Hash Memory
#[peripheral(offset = 0x0000_0100, len = 0x40)]
hash: ReadWriteMemory<SHA512_HASH_SIZE>,
/// Block Read Control register
#[register(offset = 0x0000_0600, write_fn = on_write_block_read_control)]
block_read_ctrl: ReadWriteRegister<u32, BlockReadControl::Register>,
/// Block Read Status register
#[register(offset = 0x0000_0604)]
block_read_status: ReadOnlyRegister<u32, BlockReadStatus::Register>,
/// Hash Write Control register
#[register(offset = 0x0000_0608, write_fn = on_write_hash_write_control)]
hash_write_ctrl: ReadWriteRegister<u32, HashWriteControl::Register>,
/// Hash Write Status register
#[register(offset = 0x0000_060c)]
hash_write_status: ReadOnlyRegister<u32, HashWriteStatus::Register>,
/// Nonce for PCR Gen Hash Function
#[register_array(offset = 0x0000_0610, read_fn = read_access_fault)]
pcr_gen_hash_nonce: [u32; 8],
/// Control register for PCR Gen Hash Function
#[register(offset = 0x0000_0630, write_fn = on_write_pcr_hash_control)]
pcr_hash_control: WriteOnlyRegister<u32, PcrHashControl::Register>,
/// Status register for PCR Gen Hash Function
#[register(offset = 0x0000_0634)]
pcr_hash_status: ReadOnlyRegister<u32, PcrHashStatus::Register>,
/// 16 32-bit registers storing the 512-bit digest output.
#[register_array(offset = 0x0000_0638, write_fn = write_access_fault)]
pcr_hash_digest: [u32; SHA512_HASH_SIZE / 4],
/// SHA512 engine
sha512: Sha512,
/// Key Vault
key_vault: KeyVault,
timer: Timer,
/// Operation complete action
op_complete_action: Option<ActionHandle>,
/// Block read complete action
op_block_read_complete_action: Option<ActionHandle>,
/// Hash write complete action
op_hash_write_complete_action: Option<ActionHandle>,
/// Pcr Gen Hash complete action
op_pcr_gen_hash_complete_action: Option<ActionHandle>,
pcr_present: bool,
}
impl HashSha512Regs {
/// NAME0 Register Value
const NAME0_VAL: RvData = 0x323135; // 512
/// NAME1 Register Value
const NAME1_VAL: RvData = 0x32616873; // sha2
/// VERSION0 Register Value
const VERSION0_VAL: RvData = 0x30302E31; // 1.0
/// VERSION1 Register Value
const VERSION1_VAL: RvData = 0x00000000;
/// Create a new instance of SHA-512 Engine
pub fn new(clock: &Clock, key_vault: KeyVault) -> Self {
Self {
sha512: Sha512::new(Sha512Mode::Sha512), // Default SHA512 mode
name0: ReadOnlyRegister::new(Self::NAME0_VAL),
name1: ReadOnlyRegister::new(Self::NAME1_VAL),
version0: ReadOnlyRegister::new(Self::VERSION0_VAL),
version1: ReadOnlyRegister::new(Self::VERSION1_VAL),
control: ReadWriteRegister::new(0),
status: ReadOnlyRegister::new(Status::READY::SET.value),
block_read_ctrl: ReadWriteRegister::new(0),
block_read_status: ReadOnlyRegister::new(BlockReadStatus::READY::SET.value),
hash_write_ctrl: ReadWriteRegister::new(0),
hash_write_status: ReadOnlyRegister::new(HashWriteStatus::READY::SET.value),
pcr_gen_hash_nonce: Default::default(),
pcr_hash_control: WriteOnlyRegister::new(0),
pcr_hash_status: ReadOnlyRegister::new(PcrHashStatus::READY::SET.value),
pcr_hash_digest: Default::default(),
block: Default::default(),
hash: ReadWriteMemory::new(),
key_vault,
timer: Timer::new(clock),
op_complete_action: None,
op_block_read_complete_action: None,
op_hash_write_complete_action: None,
op_pcr_gen_hash_complete_action: None,
pcr_present: false,
}
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.control.reg.set(val);
// Reset the pcr_present flag.
self.pcr_present = false;
if self.control.reg.is_set(Control::RESTORE) {
// Restore the hash state.
self.sha512.set_hash(self.hash.data());
}
if self.control.reg.is_set(Control::INIT) || self.control.reg.is_set(Control::NEXT) {
// Reset the Ready and Valid status bits
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
if self.control.reg.is_set(Control::INIT) {
// Initialize the SHA512 engine with the mode.
let mut mode = Sha512Mode::Sha512;
let modebits = self.control.reg.read(Control::MODE);
match modebits {
0 => {
mode = Sha512Mode::Sha224;
}
1 => {
mode = Sha512Mode::Sha256;
}
2 => {
mode = Sha512Mode::Sha384;
}
3 => {
mode = Sha512Mode::Sha512;
}
_ => Err(BusError::StoreAccessFault)?,
}
self.sha512.reset(mode);
// Update the SHA512 engine with a new block
self.sha512
.update(&sha512_block_bytes_from_words_le(&self.block));
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(INIT_TICKS));
} else if self.control.reg.is_set(Control::NEXT) {
// Update the SHA512 engine with a new block
self.sha512
.update(&sha512_block_bytes_from_words_le(&self.block));
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(UPDATE_TICKS));
}
}
if self.control.reg.is_set(Control::ZEROIZE) {
self.zeroize();
}
Ok(())
}
/// On Write callback for `block` registers
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
fn write_block(&mut self, _size: RvSize, word_index: usize, val: u32) -> Result<(), BusError> {
// If pcr_present, skip updating the first 48 bytes in the block registers
// as these contain the PCR retrieved from the PCR vault.
if !self.pcr_present || word_index >= 12 {
self.block[word_index] = val;
}
Ok(())
}
/// On Write callback for `block_read_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_block_read_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the block read control register.
let block_read_ctrl = InMemoryRegister::<u32, BlockReadControl::Register>::new(val);
self.block_read_ctrl.reg.modify(
BlockReadControl::KEY_READ_EN.val(block_read_ctrl.read(BlockReadControl::KEY_READ_EN))
+ BlockReadControl::KEY_ID.val(block_read_ctrl.read(BlockReadControl::KEY_ID))
+ BlockReadControl::PCR_HASH_EXTEND
.val(block_read_ctrl.read(BlockReadControl::PCR_HASH_EXTEND)),
);
if block_read_ctrl.is_set(BlockReadControl::KEY_READ_EN) {
self.block_read_status.reg.modify(
BlockReadStatus::READY::CLEAR
+ BlockReadStatus::VALID::CLEAR
+ BlockReadStatus::ERROR::CLEAR,
);
self.op_block_read_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
/// On Write callback for `hash_write_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_hash_write_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the hash control register
let hash_write_ctrl = InMemoryRegister::<u32, HashWriteControl::Register>::new(val);
self.hash_write_ctrl.reg.modify(
HashWriteControl::KEY_WRITE_EN
.val(hash_write_ctrl.read(HashWriteControl::KEY_WRITE_EN))
+ HashWriteControl::KEY_ID.val(hash_write_ctrl.read(HashWriteControl::KEY_ID))
+ HashWriteControl::USAGE.val(hash_write_ctrl.read(HashWriteControl::USAGE)),
);
Ok(())
}
/// On Write callback for `pcr_hash_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_pcr_hash_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Bail out if not ready
if !self.pcr_hash_status.reg.is_set(PcrHashStatus::READY) {
return Ok(());
}
// Set the Pcr Gen Hash Control register
self.pcr_hash_control.reg.set(val);
// Clear the status bits
self.pcr_hash_status
.reg
.modify(PcrHashStatus::VALID::CLEAR + PcrHashStatus::READY::CLEAR);
self.op_pcr_gen_hash_complete_action = Some(self.timer.schedule_poll_in(UPDATE_TICKS));
Ok(())
}
fn read_access_fault(&self, _size: RvSize, _index: usize) -> Result<RvData, BusError> {
Err(BusError::LoadAccessFault)
}
fn write_access_fault(
&self,
_size: RvSize,
_index: usize,
_val: RvData,
) -> Result<(), BusError> {
Err(BusError::StoreAccessFault)
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
self.op_complete();
} else if self.timer.fired(&mut self.op_block_read_complete_action) {
self.block_read_complete();
} else if self.timer.fired(&mut self.op_hash_write_complete_action) {
self.hash_write_complete();
} else if self.timer.fired(&mut self.op_pcr_gen_hash_complete_action) {
self.pcr_hash_op_complete();
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
// TODO: Reset registers
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
// TODO: Reset registers
}
fn op_complete(&mut self) {
// Retrieve the hash
self.sha512.copy_hash(self.hash.data_mut());
// Check if hash write control is enabled.
if self
.hash_write_ctrl
.reg
.is_set(HashWriteControl::KEY_WRITE_EN)
{
self.hash_write_status.reg.modify(
HashWriteStatus::VALID::CLEAR
+ HashWriteStatus::READY::CLEAR
+ HashWriteStatus::ERROR::CLEAR,
);
self.op_hash_write_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
} else if self.control.reg.is_set(Control::LAST)
&& self
.block_read_ctrl
.reg
.is_set(BlockReadControl::PCR_HASH_EXTEND)
{
// Copy the hash to the PCR if this is the last block and PCR_HASH_EXTEND is set.
let pcr_id = self.block_read_ctrl.reg.read(BlockReadControl::KEY_ID);
self.key_vault
.write_pcr(pcr_id, array_ref![self.hash.data(), 0, KeyVault::PCR_SIZE])
.unwrap();
self.block_read_ctrl
.reg
.modify(BlockReadControl::PCR_HASH_EXTEND::CLEAR);
}
// Update Ready and Valid status bits
self.status
.reg
.modify(Status::READY::SET + Status::VALID::SET);
}
fn block_read_complete(&mut self) {
let key_id = self.block_read_ctrl.reg.read(BlockReadControl::KEY_ID);
let pcr_hash_extend = self
.block_read_ctrl
.reg
.read(BlockReadControl::PCR_HASH_EXTEND);
// Clear the block
self.block.fill(0);
let result: Result<[u8; KeyVault::PCR_SIZE], BusError> = if pcr_hash_extend == 0 {
let key_usage = KeyUsage::default();
match self.key_vault.read_key(key_id, key_usage) {
Err(x) => Err(x),
Ok(x) => Ok(x[..KeyVault::PCR_SIZE].try_into().unwrap()),
}
} else {
Ok(self.key_vault.read_pcr(key_id))
};
let (block_read_result, data) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => {
(BlockReadStatus::ERROR::KV_READ_FAIL.value, None)
}
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(BlockReadStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => (BlockReadStatus::ERROR::KV_SUCCESS.value, result.ok()),
};
if let Some(data) = data {
if pcr_hash_extend != 0 {
// Copy the PCR (48 bytes) to the block registers.
self.block[..KeyVault::PCR_SIZE / 4].copy_from_slice(&words_from_bytes_le(
&<[u8; KeyVault::PCR_SIZE]>::try_from(&data[..KeyVault::PCR_SIZE]).unwrap(),
));
self.pcr_present = true;
} else {
self.format_block(&data);
}
}
self.block_read_status.reg.modify(
BlockReadStatus::VALID::SET
+ BlockReadStatus::READY::SET
+ BlockReadStatus::ERROR.val(block_read_result),
);
}
/// Adds padding and total data size to the block.
/// Stores the formatted block in peripheral's internal block data structure.
///
/// # Arguments
///
/// * `data` - Data to hash. This is in big-endian format.
///
/// # Error
///
/// * `None`
fn format_block(&mut self, data: &[u8]) {
let mut block_arr = [0u8; SHA512_BLOCK_SIZE];
block_arr[..data.len()].copy_from_slice(&data[..data.len()]);
block_arr.to_little_endian();
// Add block padding.
block_arr[data.len()] = 0b1000_0000;
// Add block length.
let len = (data.len() as u128) * 8;
block_arr[SHA512_BLOCK_SIZE - 16..].copy_from_slice(&len.to_be_bytes());
block_arr.to_big_endian();
self.block = sha512_block_words_from_bytes_le(&block_arr[..].try_into().unwrap());
}
fn hash_write_complete(&mut self) {
let key_id = self.hash_write_ctrl.reg.read(HashWriteControl::KEY_ID);
// Store the key config and the key in the key-vault.
let hash_write_result = match self
.key_vault
.write_key(
key_id,
array_ref![self.hash.data(), 0, KeyVault::KEY_SIZE],
self.hash_write_ctrl.reg.read(HashWriteControl::USAGE),
)
.err()
{
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => HashWriteStatus::ERROR::KV_READ_FAIL.value,
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
HashWriteStatus::ERROR::KV_WRITE_FAIL.value
}
None => HashWriteStatus::ERROR::KV_SUCCESS.value,
};
self.hash_write_status.reg.modify(
HashWriteStatus::READY::SET
+ HashWriteStatus::VALID::SET
+ HashWriteStatus::ERROR.val(hash_write_result),
);
}
fn pcr_hash_op_complete(&mut self) {
const PCR_COUNT: usize = 32;
const PCR_SIZE: usize = 48;
const NONCE_SIZE: usize = 32;
self.sha512.reset(Sha512Mode::Sha512);
for pcr_id in 0..PCR_COUNT {
let mut pcr = self.key_vault.read_pcr(pcr_id.try_into().unwrap());
pcr.to_big_endian();
self.sha512.update_bytes(&pcr, None);
}
self.sha512
.update_bytes(self.pcr_gen_hash_nonce.as_bytes(), None);
self.sha512
.finalize((PCR_COUNT * PCR_SIZE + NONCE_SIZE).try_into().unwrap());
self.sha512.copy_hash(self.pcr_hash_digest.as_mut_bytes());
self.pcr_hash_status
.reg
.modify(PcrHashStatus::READY::SET + PcrHashStatus::VALID::SET);
}
#[cfg(test)]
pub fn hash(&self) -> &[u8] {
&self.hash.data()[..self.sha512.hash_len()]
}
fn zeroize(&mut self) {
self.block.fill(0);
self.hash.data_mut().fill(0);
}
}
#[derive(Clone)]
pub struct HashSha512 {
regs: Rc<RefCell<HashSha512Regs>>,
}
impl HashSha512 {
/// Create a new instance of Hash SHA-512
pub fn new(clock: &Clock, key_vault: KeyVault) -> Self {
Self {
regs: Rc::new(RefCell::new(HashSha512Regs::new(clock, key_vault))),
}
}
/// Export the PCR hash digest
pub fn pcr_hash_digest(&self) -> [u8; 64] {
self.regs
.borrow()
.pcr_hash_digest
.as_bytes()
.try_into()
.unwrap()
}
}
impl Bus for HashSha512 {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.regs.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
self.regs.borrow_mut().write(size, addr, val)
}
fn poll(&mut self) {
self.regs.borrow_mut().poll();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::key_vault;
use caliptra_emu_bus::Bus;
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_types::RvAddr;
use tock_registers::registers::InMemoryRegister;
const OFFSET_NAME0: RvAddr = 0x0;
const OFFSET_NAME1: RvAddr = 0x4;
const OFFSET_VERSION0: RvAddr = 0x8;
const OFFSET_VERSION1: RvAddr = 0xC;
const OFFSET_CONTROL: RvAddr = 0x10;
const OFFSET_STATUS: RvAddr = 0x18;
const OFFSET_BLOCK: RvAddr = 0x80;
const OFFSET_HASH: RvAddr = 0x100;
const OFFSET_BLOCK_CONTROL: RvAddr = 0x600;
const OFFSET_BLOCK_STATUS: RvAddr = 0x604;
const OFFSET_HASH_CONTROL: RvAddr = 0x608;
const OFFSET_HASH_STATUS: RvAddr = 0x60c;
const SHA384_HASH_SIZE: usize = 48;
#[test]
fn test_name_read() {
let mut sha512 = HashSha512Regs::new(&Clock::new(), KeyVault::new());
let name0 = sha512.read(RvSize::Word, OFFSET_NAME0).unwrap();
let mut name0 = String::from_utf8_lossy(&name0.to_le_bytes()).to_string();
name0.pop();
assert_eq!(name0, "512");
let name1 = sha512.read(RvSize::Word, OFFSET_NAME1).unwrap();
let name1 = String::from_utf8_lossy(&name1.to_le_bytes()).to_string();
assert_eq!(name1, "sha2");
}
#[test]
fn test_version_read() {
let mut sha512 = HashSha512Regs::new(&Clock::new(), KeyVault::new());
let version0 = sha512.read(RvSize::Word, OFFSET_VERSION0).unwrap();
let version0 = String::from_utf8_lossy(&version0.to_le_bytes()).to_string();
assert_eq!(version0, "1.00");
let version1 = sha512.read(RvSize::Word, OFFSET_VERSION1).unwrap();
let version1 = String::from_utf8_lossy(&version1.to_le_bytes()).to_string();
assert_eq!(version1, "\0\0\0\0");
}
#[test]
fn test_control_read() {
let mut sha512 = HashSha512Regs::new(&Clock::new(), KeyVault::new());
assert_eq!(sha512.read(RvSize::Word, OFFSET_CONTROL).unwrap(), 0);
}
#[test]
fn test_status_read() {
let mut sha512 = HashSha512Regs::new(&Clock::new(), KeyVault::new());
assert_eq!(sha512.read(RvSize::Word, OFFSET_STATUS).unwrap(), 1);
}
#[test]
fn test_block_read_write() {
let mut sha512 = HashSha512Regs::new(&Clock::new(), KeyVault::new());
for addr in (OFFSET_BLOCK..(OFFSET_BLOCK + SHA512_BLOCK_SIZE as u32)).step_by(4) {
assert_eq!(sha512.write(RvSize::Word, addr, u32::MAX).ok(), Some(()));
assert_eq!(sha512.read(RvSize::Word, addr).ok(), Some(u32::MAX));
}
}
#[test]
fn test_hash_read_write() {
let mut sha512 = HashSha512Regs::new(&Clock::new(), KeyVault::new());
for addr in (OFFSET_HASH..(OFFSET_HASH + SHA512_HASH_SIZE as u32)).step_by(4) {
assert_eq!(sha512.read(RvSize::Word, addr).ok(), Some(0));
assert_eq!(sha512.write(RvSize::Word, addr, 0xFF).err(), None);
}
}
enum KeyVaultAction {
BlockFromVault(u32),
HashToVault(u32),
BlockReadDisallowed(bool),
BlockDisallowedForSHA(bool),
HashWriteFailTest(bool),
}
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
fn test_sha(
data: &[u8],
expected: &[u8],
mode: Sha512Mode,
keyvault_actions: &[KeyVaultAction],
) {
let mut block_via_kv: bool = false;
let mut block_id: u32 = u32::MAX;
let mut hash_to_kv: bool = false;
let mut hash_id: u32 = u32::MAX;
// Compute the total bytes and total blocks required for the final message.
let totalblocks = ((data.len() + 16) + SHA512_BLOCK_SIZE) / SHA512_BLOCK_SIZE;
let totalbytes = totalblocks * SHA512_BLOCK_SIZE;
let mut block_arr = vec![0; totalbytes];
let mut block_read_disallowed = false;
let mut hash_write_fail_test = false;
let mut block_disallowed_for_sha = false;
for action in keyvault_actions.iter() {
match action {
KeyVaultAction::BlockFromVault(id) => {
block_via_kv = true;
block_id = *id;
}
KeyVaultAction::HashToVault(id) => {
hash_to_kv = true;
hash_id = *id;
}
KeyVaultAction::BlockReadDisallowed(val) => {
block_read_disallowed = *val;
}
KeyVaultAction::HashWriteFailTest(val) => {
hash_write_fail_test = *val;
}
KeyVaultAction::BlockDisallowedForSHA(val) => {
block_disallowed_for_sha = *val;
}
}
}
if block_via_kv {
assert!(data.len() % 4 == 0);
assert!(data.len() <= (SHA512_BLOCK_SIZE - (16 + 1)));
} else {
block_arr[..data.len()].copy_from_slice(data);
block_arr[data.len()] = 1 << 7;
let len: u128 = data.len() as u128;
let len = len * 8;
block_arr[totalbytes - 16..].copy_from_slice(&len.to_be_bytes());
block_arr.to_big_endian();
}
let clock = Clock::new();
let mut key_vault = KeyVault::new();
// Add the test block to the key-vault.
if block_via_kv {
let mut block: [u8; KeyVault::KEY_SIZE] = [0; KeyVault::KEY_SIZE];
block[..data.len()].copy_from_slice(data);
block.to_big_endian(); // Keys are stored in big-endian format.
let key_usage = KeyUsage::default();
key_vault
.write_key(block_id, &block, u32::from(key_usage))
.unwrap();
if block_read_disallowed {
let val_reg = InMemoryRegister::<u32, key_vault::KV_CONTROL::Register>::new(0);
val_reg.write(key_vault::KV_CONTROL::USE_LOCK.val(1)); // Key read disabled.
assert_eq!(
key_vault
.write(
RvSize::Word,
KeyVault::KEY_CONTROL_REG_OFFSET
+ (block_id * KeyVault::KEY_CONTROL_REG_WIDTH),
val_reg.get()
)
.ok(),
Some(())
);
} else if block_disallowed_for_sha {
let val_reg = InMemoryRegister::<u32, key_vault::KV_CONTROL::Register>::new(0);
val_reg.write(key_vault::KV_CONTROL::USAGE.val(!(u32::from(key_usage)))); // Block disallowed for SHA use.
assert_eq!(
key_vault
.write(
RvSize::Word,
KeyVault::KEY_CONTROL_REG_OFFSET
+ (block_id * KeyVault::KEY_CONTROL_REG_WIDTH),
val_reg.get()
)
.ok(),
Some(())
);
}
}
// For negative hash write test, make the key-slot uneditable.
if hash_write_fail_test {
assert!(hash_to_kv);
let val_reg = InMemoryRegister::<u32, key_vault::KV_CONTROL::Register>::new(0);
val_reg.write(key_vault::KV_CONTROL::WRITE_LOCK.val(1)); // Key write disabled.
assert_eq!(
key_vault
.write(
RvSize::Word,
KeyVault::KEY_CONTROL_REG_OFFSET
+ (hash_id * KeyVault::KEY_CONTROL_REG_WIDTH),
val_reg.get()
)
.ok(),
Some(())
);
}
let mut sha512 = HashSha512Regs::new(&clock, key_vault);
if hash_to_kv {
// Instruct hash to be written to the key-vault.
let key_usage = KeyUsage::default();
let hash_ctrl = InMemoryRegister::<u32, HashWriteControl::Register>::new(0);
hash_ctrl.modify(
HashWriteControl::KEY_ID.val(hash_id)
+ HashWriteControl::KEY_WRITE_EN.val(1)
+ HashWriteControl::USAGE.val(u32::from(key_usage)),
);
assert_eq!(
sha512
.write(RvSize::Word, OFFSET_HASH_CONTROL, hash_ctrl.get())
.ok(),
Some(())
);
}
// Process each block via the SHA engine.
for idx in 0..totalblocks {
if !block_via_kv {
for i in (0..SHA512_BLOCK_SIZE).step_by(4) {
assert_eq!(
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/iccm.rs | sw-emulator/lib/periph/src/iccm.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
iccm.rs
Abstract:
File contains ICCM Implementation
--*/
use caliptra_emu_bus::Bus;
use caliptra_emu_bus::BusError;
use caliptra_emu_bus::Clock;
use caliptra_emu_bus::Ram;
use caliptra_emu_bus::Timer;
use caliptra_emu_bus::TimerAction;
use caliptra_emu_types::RvAddr;
use caliptra_emu_types::RvData;
use caliptra_emu_types::RvSize;
use std::cell::Cell;
use std::{cell::RefCell, rc::Rc};
#[derive(Clone)]
pub struct Iccm {
iccm: Rc<IccmImpl>,
}
const ICCM_SIZE_BYTES: usize = 256 * 1024;
impl Iccm {
pub fn lock(&mut self) {
self.iccm.locked.set(true);
}
pub fn unlock(&mut self) {
self.iccm.locked.set(false);
}
pub fn new(clock: &Clock) -> Self {
Self {
iccm: Rc::new(IccmImpl::new(clock)),
}
}
pub fn ram(&self) -> &RefCell<Ram> {
&self.iccm.ram
}
}
struct IccmImpl {
ram: RefCell<Ram>,
locked: Cell<bool>,
timer: Timer,
}
impl IccmImpl {
pub fn new(clock: &Clock) -> Self {
Self {
ram: RefCell::new(Ram::new(vec![0; ICCM_SIZE_BYTES])),
locked: Cell::new(false),
timer: clock.timer(),
}
}
}
impl Bus for Iccm {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.iccm.ram.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
// NMIs don't fire immediately; a couple instructions is a fairly typicaly delay on VeeR.
const NMI_DELAY: u64 = 2;
// From RISC-V_VeeR_EL2_PRM.pdf
const NMI_CAUSE_DBUS_STORE_ERROR: u32 = 0xf000_0000;
if size != RvSize::Word || (addr & 0x3) != 0 {
self.iccm.timer.schedule_action_in(
NMI_DELAY,
TimerAction::Nmi {
mcause: NMI_CAUSE_DBUS_STORE_ERROR,
},
);
return Ok(());
}
if self.iccm.locked.get() {
self.iccm.timer.schedule_action_in(
NMI_DELAY,
TimerAction::Nmi {
mcause: NMI_CAUSE_DBUS_STORE_ERROR,
},
);
return Ok(());
}
self.iccm.ram.borrow_mut().write(size, addr, val)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn next_action(clock: &Clock) -> Option<TimerAction> {
let mut actions = clock.increment(4);
match actions.len() {
0 => None,
1 => actions.drain().next(),
_ => panic!("More than one action scheduled; unexpected"),
}
}
#[test]
fn test_unlocked_write() {
let clock = Clock::new();
let mut iccm = Iccm::new(&clock);
for word_offset in (0u32..ICCM_SIZE_BYTES as u32).step_by(4) {
assert_eq!(iccm.read(RvSize::Word, word_offset).unwrap(), 0);
assert_eq!(
iccm.write(RvSize::Word, word_offset, u32::MAX).ok(),
Some(())
);
assert_eq!(iccm.read(RvSize::Word, word_offset).ok(), Some(u32::MAX));
}
assert_eq!(next_action(&clock), None);
}
#[test]
fn test_locked_write() {
let clock = Clock::new();
let mut iccm = Iccm::new(&clock);
iccm.lock();
for word_offset in (0u32..ICCM_SIZE_BYTES as u32).step_by(4) {
assert_eq!(iccm.read(RvSize::Word, word_offset).unwrap(), 0);
assert!(iccm.write(RvSize::Word, word_offset, u32::MAX).is_ok());
assert_eq!(
next_action(&clock),
Some(TimerAction::Nmi {
mcause: 0xf000_0000
})
);
}
assert_eq!(next_action(&clock), None);
}
#[test]
fn test_byte_write() {
let clock = Clock::new();
let mut iccm = Iccm::new(&clock);
assert_eq!(iccm.write(RvSize::Byte, 0, 42), Ok(()));
assert_eq!(
next_action(&clock),
Some(TimerAction::Nmi {
mcause: 0xf000_0000
})
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/aes_clp.rs | sw-emulator/lib/periph/src/aes_clp.rs | // Licensed under the Apache-2.0 license
use crate::hmac::{KeyReadControl, KeyReadStatus, TagWriteControl, TagWriteStatus, KEY_RW_TICKS};
use crate::{KeyUsage, KeyVault};
use caliptra_emu_bus::{
ActionHandle, BusError, Clock, Event, ReadOnlyRegister, ReadWriteRegister, Timer,
};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::mpsc;
use tock_registers::interfaces::{ReadWriteable, Readable};
use tock_registers::registers::InMemoryRegister;
use zerocopy::IntoBytes;
#[derive(Debug, PartialEq)]
pub enum AesKeyReleaseState {
Ready,
/// Destination KV has been set
Armed,
/// 64 bytes of data have been decrypted.
/// Signal ready for copy to KV.
Complete,
}
pub struct AesKeyReleaseOp {
/// Key release has been requested
/// OCP LOCK Rule:
/// If AES ECB Decrypt & Output KV == 23
pub state: AesKeyReleaseState,
/// AES Decryption result
/// Per OCP spec MUST be 64 bytes (MEK size)
pub output: [u8; 64],
// Data staged
// When 64 bytes have been staged, signal completion.
pub staged_data: usize,
}
impl Default for AesKeyReleaseOp {
fn default() -> Self {
Self {
state: AesKeyReleaseState::Ready,
output: [0; 64],
staged_data: 0,
}
}
}
impl AesKeyReleaseOp {
pub fn clear(&mut self) {
self.staged_data = 0;
self.state = AesKeyReleaseState::Ready;
}
pub fn load_data(&mut self, aes_block: &[u32; 4]) {
if self.state != AesKeyReleaseState::Armed {
return;
}
self.output[self.staged_data..self.staged_data + 16].clone_from_slice(aes_block.as_bytes());
self.staged_data += 16;
if self.staged_data == self.output.len() {
self.state = AesKeyReleaseState::Complete;
}
}
}
/// AES peripheral implementation
#[derive(Bus)]
#[poll_fn(poll)]
pub struct AesClp {
// AES Component Name registers
#[register(offset = 0x0)]
aes_name_0: ReadOnlyRegister<u32>,
#[register(offset = 0x4)]
aes_name_1: ReadOnlyRegister<u32>,
// AES Component Version registers
#[register(offset = 0x8)]
aes_version_0: ReadOnlyRegister<u32>,
#[register(offset = 0xC)]
aes_version_1: ReadOnlyRegister<u32>,
// Entropy Interface Seed registers
#[register_array(offset = 0x110, item_size = 4, len = 9)]
entropy_if_seed: [u32; 9],
// AES Key Vault Control registers
#[register(offset = 0x200, write_fn = on_write_key_read_control)]
aes_kv_rd_key_ctrl: ReadWriteRegister<u32, KeyReadControl::Register>,
#[register(offset = 0x204)]
aes_kv_rd_key_status: ReadOnlyRegister<u32, KeyReadStatus::Register>,
#[register(offset = 0x208, write_fn = on_write_key_write_control)]
aes_kv_wr_key_ctrl: ReadWriteRegister<u32, TagWriteControl::Register>,
#[register(offset = 0x20c)]
aes_kv_wr_status: ReadOnlyRegister<u32, TagWriteStatus::Register>,
/// Timer
timer: Timer,
/// Key Vault
key_vault: KeyVault,
/// Key read complete action
op_key_read_complete_action: Option<ActionHandle>,
/// Key write complete action
op_key_write_complete_action: Option<ActionHandle>,
key: Rc<RefCell<Option<[u8; 32]>>>,
key_destination: Rc<RefCell<AesKeyReleaseOp>>,
}
impl AesClp {
/// Create a new AES CLP peripheral instance
pub fn new(
clock: &Clock,
key_vault: KeyVault,
key: Rc<RefCell<Option<[u8; 32]>>>,
key_destination: Rc<RefCell<AesKeyReleaseOp>>,
) -> Self {
Self {
timer: Timer::new(clock),
key_vault,
// Initialize with default values
aes_name_0: ReadOnlyRegister::new(0x41455300), // "AES\0"
aes_name_1: ReadOnlyRegister::new(0x434C5000), // "CLP\0"
aes_version_0: ReadOnlyRegister::new(0x00000001), // Version 1.0
aes_version_1: ReadOnlyRegister::new(0x00000000),
entropy_if_seed: [0; 9],
aes_kv_rd_key_ctrl: ReadWriteRegister::new(0),
aes_kv_rd_key_status: ReadOnlyRegister::new(KeyReadStatus::READY::SET.value),
aes_kv_wr_key_ctrl: ReadWriteRegister::new(0),
aes_kv_wr_status: ReadOnlyRegister::new(KeyReadStatus::READY::SET.value),
op_key_read_complete_action: None,
op_key_write_complete_action: None,
key,
key_destination,
}
}
/// On Write callback for `key_read_control` register
pub fn on_write_key_read_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the key control register
let key_read_ctrl = InMemoryRegister::<u32, KeyReadControl::Register>::new(val);
self.aes_kv_rd_key_ctrl.reg.modify(
KeyReadControl::KEY_READ_EN.val(key_read_ctrl.read(KeyReadControl::KEY_READ_EN))
+ KeyReadControl::KEY_ID.val(key_read_ctrl.read(KeyReadControl::KEY_ID)),
);
if key_read_ctrl.is_set(KeyReadControl::KEY_READ_EN) {
self.aes_kv_rd_key_status.reg.modify(
KeyReadStatus::READY::CLEAR
+ KeyReadStatus::VALID::CLEAR
+ KeyReadStatus::ERROR::CLEAR,
);
self.op_key_read_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
fn key_read_complete(&mut self) {
let key_id = self.aes_kv_rd_key_ctrl.reg.read(KeyReadControl::KEY_ID);
let mut key_usage = KeyUsage::default();
key_usage.set_aes_key(true);
let result = self.key_vault.read_key(key_id, key_usage);
let (key_read_result, key) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => (KeyReadStatus::ERROR::KV_READ_FAIL.value, None),
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(KeyReadStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => (
KeyReadStatus::ERROR::KV_SUCCESS.value,
Some(result.unwrap()),
),
};
if let Some(key) = &key {
*self.key.borrow_mut() = Some(key.to_vec()[..32].try_into().unwrap());
// make sure the AES peripheral picks up the new key
self.timer.schedule_poll_in(1);
}
self.aes_kv_rd_key_status.reg.modify(
KeyReadStatus::READY::SET
+ KeyReadStatus::VALID::SET
+ KeyReadStatus::ERROR.val(key_read_result),
);
}
/// On Write callback for `key_write_control` register
pub fn on_write_key_write_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// TODO(clundin): Check soc reg for `ocp_lock_in_progress` true. If false this should be an
// error? Or Should never release the KV?
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the key control register
let key_write_ctrl = InMemoryRegister::<u32, TagWriteControl::Register>::new(val);
self.aes_kv_wr_key_ctrl.reg.modify(
TagWriteControl::KEY_WRITE_EN.val(key_write_ctrl.read(TagWriteControl::KEY_WRITE_EN))
+ TagWriteControl::KEY_ID.val(key_write_ctrl.read(TagWriteControl::KEY_ID)),
);
if key_write_ctrl.is_set(TagWriteControl::KEY_WRITE_EN) {
self.aes_kv_wr_status.reg.modify(
TagWriteStatus::READY::CLEAR
+ TagWriteStatus::VALID::CLEAR
+ TagWriteStatus::ERROR::CLEAR,
);
let mut key_op = self.key_destination.borrow_mut();
key_op.state = AesKeyReleaseState::Armed;
self.op_key_write_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
fn key_write_complete(&mut self) {
// TODO(clundin): Check soc reg for `ocp_lock_in_progress` true. If false this should be an
// error? Or Should never release the KV?
let key_id = self.aes_kv_wr_key_ctrl.reg.read(TagWriteControl::KEY_ID);
let mut key_usage = KeyUsage::default();
key_usage.set_aes_key(true);
// AES Engine has not completed decryption.
// Schedule another poll.
let mut key_op = self.key_destination.borrow_mut();
if key_op.state != AesKeyReleaseState::Complete {
self.op_key_write_complete_action =
Some(self.timer.schedule_poll_in(KEY_RW_TICKS * 10000));
return;
};
let result = self
.key_vault
.write_key(key_id, &key_op.output, key_usage.into());
key_op.clear();
// TODO(clundin): Check Key here?
let (key_write_result, _key) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => (KeyReadStatus::ERROR::KV_READ_FAIL.value, None),
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(KeyReadStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => {
result.unwrap();
(KeyReadStatus::ERROR::KV_SUCCESS.value, Some(()))
}
};
self.aes_kv_wr_status.reg.modify(
TagWriteStatus::READY::SET
+ TagWriteStatus::VALID::SET
+ TagWriteStatus::ERROR.val(key_write_result),
);
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_key_read_complete_action) {
self.key_read_complete();
}
if self.timer.fired(&mut self.op_key_write_complete_action) {
self.key_write_complete();
}
}
/// Handle incoming events
pub fn incoming_event(&mut self, _event: Rc<Event>) {
// No event handling needed for now
}
/// Register for outgoing events
pub fn register_outgoing_events(&mut self, _sender: mpsc::Sender<Event>) {
// No events to register for now
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Aes;
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvAddr;
use tock_registers::interfaces::Writeable;
use tock_registers::registers::InMemoryRegister;
const AES_KEY_SHARE0_OFFSET: RvAddr = 0x4;
const AES_KEY_SHARE1_OFFSET: RvAddr = 0x24;
const AES_DATA_IN_OFFSET: RvAddr = 0x54;
const AES_CTRL_SHADOWED_OFFSET: RvAddr = 0x74;
const AES_CLP_KV_WR_KEY_CTRL_OFFSET: RvAddr = 0x208;
const AES_CLP_KV_WR_STATUS_OFFSET: RvAddr = 0x20c;
const AES_KEY: [u8; 32] = [
0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77,
0x81, 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14,
0xDF, 0xF4,
];
// AES Ciphertext to be decrypted. (64 bytes)
const CIPHER_TEXT: [u8; 64] = [
0xE5, 0x68, 0xF6, 0x81, 0x94, 0xCF, 0x76, 0xD6, 0x17, 0x4D, 0x4C, 0xC0, 0x43, 0x10, 0xA8,
0x54, 0xE5, 0x68, 0xF6, 0x81, 0x94, 0xCF, 0x76, 0xD6, 0x17, 0x4D, 0x4C, 0xC0, 0x43, 0x10,
0xA8, 0x54, 0xE5, 0x68, 0xF6, 0x81, 0x94, 0xCF, 0x76, 0xD6, 0x17, 0x4D, 0x4C, 0xC0, 0x43,
0x10, 0xA8, 0x54, 0xE5, 0x68, 0xF6, 0x81, 0x94, 0xCF, 0x76, 0xD6, 0x17, 0x4D, 0x4C, 0xC0,
0x43, 0x10, 0xA8, 0x54,
];
const PLAIN_TEXT: [u8; 64] = [0; 64];
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
#[test]
fn test_aes_key_release() {
let clock = Clock::new();
let key_vault = KeyVault::new();
let aes_key = Rc::new(RefCell::new(None));
let aes_destination = Rc::new(RefCell::new(AesKeyReleaseOp::default()));
let mut aes = Aes::new(aes_key.clone(), aes_destination.clone());
let mut aes_clp = AesClp::new(
&clock,
key_vault.clone(),
aes_key.clone(),
aes_destination.clone(),
);
// 1. Configure AES
// Write Key
for i in (0..AES_KEY.len()).step_by(4) {
aes.write(
RvSize::Word,
AES_KEY_SHARE0_OFFSET + i as u32,
make_word(i, &AES_KEY),
)
.unwrap();
aes.write(RvSize::Word, AES_KEY_SHARE1_OFFSET + i as u32, 0)
.unwrap();
}
// Configure AES for ECB Decryption
let ctrl = InMemoryRegister::<u32, crate::aes::Ctrl::Register>::new(0);
ctrl.write(
crate::aes::Ctrl::OP::DECRYPT
+ crate::aes::Ctrl::MODE::ECB
+ crate::aes::Ctrl::KEY_LEN::KEY_256
+ crate::aes::Ctrl::MANUAL_OPERATION::ENABLED,
);
aes.write(RvSize::Word, AES_CTRL_SHADOWED_OFFSET, ctrl.get())
.unwrap();
// 2. Configure AesClp to write to KV slot 23
let dest_key_id = 23;
let key_write_ctrl = InMemoryRegister::<u32, TagWriteControl::Register>::new(0);
key_write_ctrl
.write(TagWriteControl::KEY_ID.val(dest_key_id) + TagWriteControl::KEY_WRITE_EN.val(1));
aes_clp
.write(
RvSize::Word,
AES_CLP_KV_WR_KEY_CTRL_OFFSET,
key_write_ctrl.get(),
)
.unwrap();
// Verify AesKeyReleaseOp is Armed
assert_eq!(aes_destination.borrow().state, AesKeyReleaseState::Armed);
// 3. Load 64 bytes of data into AES
for chunk in CIPHER_TEXT.chunks(16) {
for i in (0..chunk.len()).step_by(4) {
aes.write(
RvSize::Word,
AES_DATA_IN_OFFSET + i as u32,
make_word(i, chunk),
)
.unwrap();
}
}
// Verify AesKeyReleaseOp is Complete
assert_eq!(aes_destination.borrow().state, AesKeyReleaseState::Complete);
assert_eq!(aes_destination.borrow().output, PLAIN_TEXT);
// 4. Step clock to let AesClp write to KeyVault
// AesClp checks for completion in poll()
clock.increment_and_process_timer_actions(KEY_RW_TICKS + 10, &mut aes_clp);
// 5. Verify KeyVault content
let mut key_usage = KeyUsage::default();
key_usage.set_aes_key(true);
let kv_key = key_vault.read_key(dest_key_id, key_usage).unwrap();
assert_eq!(kv_key, PLAIN_TEXT);
let status = aes_clp
.read(RvSize::Word, AES_CLP_KV_WR_STATUS_OFFSET)
.unwrap();
let status_reg = InMemoryRegister::<u32, TagWriteStatus::Register>::new(status);
assert!(status_reg.is_set(TagWriteStatus::VALID));
assert_eq!(
status_reg.read(TagWriteStatus::ERROR),
TagWriteStatus::ERROR::KV_SUCCESS.value
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/helpers.rs | sw-emulator/lib/periph/src/helpers.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
helpers.rs
Abstract:
File contains helper functions
--*/
#![allow(unused)]
use std::ops::{Index, IndexMut, RangeFrom};
pub trait U32Array: AsRef<[u32]> {
const BYTE_LEN: usize;
type ByteArray: AsMut<[u8]>;
// Required because Default isn't implemented for [u8; 64]
fn default_result() -> Self::ByteArray;
}
pub trait U32ArrayBytes: AsRef<[u8]> {
const WORD_LEN: usize;
type WordArray: AsMut<[u32]>;
// Required because Default isn't implemented for [u32; 64 and higher]
fn default_result() -> Self::WordArray;
}
macro_rules! u32_array_impl {
($word_len:literal) => {
impl U32Array for [u32; $word_len] {
const BYTE_LEN: usize = $word_len * 4;
type ByteArray = [u8; $word_len * 4];
fn default_result() -> Self::ByteArray {
[0u8; $word_len * 4]
}
}
impl U32ArrayBytes for [u8; $word_len * 4] {
const WORD_LEN: usize = $word_len;
type WordArray = [u32; $word_len];
fn default_result() -> Self::WordArray {
[0u32; $word_len]
}
}
};
}
u32_array_impl!(0);
u32_array_impl!(1);
u32_array_impl!(2);
u32_array_impl!(3);
u32_array_impl!(4);
u32_array_impl!(5);
u32_array_impl!(6);
u32_array_impl!(7);
u32_array_impl!(8);
u32_array_impl!(9);
u32_array_impl!(10);
u32_array_impl!(11);
u32_array_impl!(12);
u32_array_impl!(13);
u32_array_impl!(14);
u32_array_impl!(15);
u32_array_impl!(16);
u32_array_impl!(32);
u32_array_impl!(392);
u32_array_impl!(648);
u32_array_impl!(792);
u32_array_impl!(1157);
u32_array_impl!(1224);
pub fn words_from_bytes_le<A: U32ArrayBytes>(arr: &A) -> A::WordArray {
let mut result = A::default_result();
for i in 0..result.as_mut().len() {
result.as_mut()[i] = u32::from_le_bytes(arr.as_ref()[i * 4..][..4].try_into().unwrap())
}
result
}
pub fn words_from_bytes_be<A: U32ArrayBytes>(arr: &A) -> A::WordArray {
let mut result = A::default_result();
for i in 0..result.as_mut().len() {
result.as_mut()[i] = u32::from_be_bytes(arr.as_ref()[i * 4..][..4].try_into().unwrap())
}
result
}
pub fn words_from_bytes_be_vec(arr: &[u8]) -> Vec<u32> {
assert_eq!(arr.len() % 4, 0);
let mut result = vec![0u32; arr.len() / 4];
for i in 0..result.len() {
result[i] = u32::from_be_bytes(arr[i * 4..][..4].try_into().unwrap())
}
result
}
pub fn words_from_bytes_le_vec(arr: &[u8]) -> Vec<u32> {
assert_eq!(arr.len() % 4, 0);
let mut result = vec![0u32; arr.len() / 4];
for i in 0..result.len() {
result[i] = u32::from_le_bytes(arr[i * 4..][..4].try_into().unwrap())
}
result
}
pub fn bytes_from_words_le<A: U32Array>(arr: &A) -> A::ByteArray {
let mut result = A::default_result();
for i in 0..arr.as_ref().len() {
result.as_mut()[i * 4..][..4].copy_from_slice(&arr.as_ref()[i].to_le_bytes());
}
result
}
pub fn bytes_from_words_be<A: U32Array>(arr: &A) -> A::ByteArray {
let mut result = A::default_result();
for i in 0..arr.as_ref().len() {
result.as_mut()[i * 4..][..4].copy_from_slice(&arr.as_ref()[i].to_be_bytes());
}
result
}
pub fn bytes_swap_word_endian<A: U32ArrayBytes>(
arr: &A,
) -> <<A as U32ArrayBytes>::WordArray as U32Array>::ByteArray
where
<A as U32ArrayBytes>::WordArray: U32Array,
{
bytes_from_words_le(&words_from_bytes_be(arr))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_words_from_bytes_le() {
assert_eq!(
[
0xeb457996, 0x70cdc537, 0x95684f6f, 0xde320a3e, 0xbe5a8d48, 0xd25c3fe1, 0x47051dda,
0x2fcb1d61, 0x5abaabff, 0xd041c30e, 0x1a18b955, 0x117495d4,
],
words_from_bytes_le(&[
0x96, 0x79, 0x45, 0xeb, 0x37, 0xc5, 0xcd, 0x70, 0x6f, 0x4f, 0x68, 0x95, 0x3e, 0x0a,
0x32, 0xde, 0x48, 0x8d, 0x5a, 0xbe, 0xe1, 0x3f, 0x5c, 0xd2, 0xda, 0x1d, 0x05, 0x47,
0x61, 0x1d, 0xcb, 0x2f, 0xff, 0xab, 0xba, 0x5a, 0x0e, 0xc3, 0x41, 0xd0, 0x55, 0xb9,
0x18, 0x1a, 0xd4, 0x95, 0x74, 0x11
])
);
assert_eq!(
[
0x6d533aa5, 0xb8066955, 0xb1d55284, 0xe44aade8, 0x279ad4d2, 0xde9de661, 0x13fba077,
0x76a6efd,
],
words_from_bytes_le(&[
0xa5, 0x3a, 0x53, 0x6d, 0x55, 0x69, 0x06, 0xb8, 0x84, 0x52, 0xd5, 0xb1, 0xe8, 0xad,
0x4a, 0xe4, 0xd2, 0xd4, 0x9a, 0x27, 0x61, 0xe6, 0x9d, 0xde, 0x77, 0xa0, 0xfb, 0x13,
0xfd, 0x6e, 0x6a, 0x7
])
);
}
#[test]
pub fn test_words_from_bytes_be() {
assert_eq!(
[
0x967945eb, 0x37c5cd70, 0x6f4f6895, 0x3e0a32de, 0x488d5abe, 0xe13f5cd2, 0xda1d0547,
0x611dcb2f, 0xffabba5a, 0x0ec341d0, 0x55b9181a, 0xd4957411,
],
words_from_bytes_be(&[
0x96, 0x79, 0x45, 0xeb, 0x37, 0xc5, 0xcd, 0x70, 0x6f, 0x4f, 0x68, 0x95, 0x3e, 0x0a,
0x32, 0xde, 0x48, 0x8d, 0x5a, 0xbe, 0xe1, 0x3f, 0x5c, 0xd2, 0xda, 0x1d, 0x05, 0x47,
0x61, 0x1d, 0xcb, 0x2f, 0xff, 0xab, 0xba, 0x5a, 0x0e, 0xc3, 0x41, 0xd0, 0x55, 0xb9,
0x18, 0x1a, 0xd4, 0x95, 0x74, 0x11
])
);
assert_eq!(
[
0xa53a536d, 0x556906b8, 0x8452d5b1, 0xe8ad4ae4, 0xd2d49a27, 0x61e69dde, 0x77a0fb13,
0xfd6e6a07,
],
words_from_bytes_be(&[
0xa5, 0x3a, 0x53, 0x6d, 0x55, 0x69, 0x06, 0xb8, 0x84, 0x52, 0xd5, 0xb1, 0xe8, 0xad,
0x4a, 0xe4, 0xd2, 0xd4, 0x9a, 0x27, 0x61, 0xe6, 0x9d, 0xde, 0x77, 0xa0, 0xfb, 0x13,
0xfd, 0x6e, 0x6a, 0x7
])
);
assert_eq!(
vec![
0xa53a536d, 0x556906b8, 0x8452d5b1, 0xe8ad4ae4, 0xd2d49a27, 0x61e69dde, 0x77a0fb13,
0xfd6e6a07,
],
words_from_bytes_be_vec(&[
0xa5, 0x3a, 0x53, 0x6d, 0x55, 0x69, 0x06, 0xb8, 0x84, 0x52, 0xd5, 0xb1, 0xe8, 0xad,
0x4a, 0xe4, 0xd2, 0xd4, 0x9a, 0x27, 0x61, 0xe6, 0x9d, 0xde, 0x77, 0xa0, 0xfb, 0x13,
0xfd, 0x6e, 0x6a, 0x7
])
);
}
#[test]
pub fn test_bytes_from_words_le() {
assert_eq!(
[
0x96, 0x79, 0x45, 0xeb, 0x37, 0xc5, 0xcd, 0x70, 0x6f, 0x4f, 0x68, 0x95, 0x3e, 0x0a,
0x32, 0xde, 0x48, 0x8d, 0x5a, 0xbe, 0xe1, 0x3f, 0x5c, 0xd2, 0xda, 0x1d, 0x05, 0x47,
0x61, 0x1d, 0xcb, 0x2f, 0xff, 0xab, 0xba, 0x5a, 0x0e, 0xc3, 0x41, 0xd0, 0x55, 0xb9,
0x18, 0x1a, 0xd4, 0x95, 0x74, 0x11
],
bytes_from_words_le(&[
0xeb457996, 0x70cdc537, 0x95684f6f, 0xde320a3e, 0xbe5a8d48, 0xd25c3fe1, 0x47051dda,
0x2fcb1d61, 0x5abaabff, 0xd041c30e, 0x1a18b955, 0x117495d4,
])
);
assert_eq!(
[
0xa5, 0x3a, 0x53, 0x6d, 0x55, 0x69, 0x06, 0xb8, 0x84, 0x52, 0xd5, 0xb1, 0xe8, 0xad,
0x4a, 0xe4, 0xd2, 0xd4, 0x9a, 0x27, 0x61, 0xe6, 0x9d, 0xde, 0x77, 0xa0, 0xfb, 0x13,
0xfd, 0x6e, 0x6a, 0x7
],
bytes_from_words_le(&[
0x6d533aa5, 0xb8066955, 0xb1d55284, 0xe44aade8, 0x279ad4d2, 0xde9de661, 0x13fba077,
0x76a6efd,
])
);
}
#[test]
pub fn test_bytes_from_words_be() {
assert_eq!(
[
0xeb, 0x45, 0x79, 0x96, 0x70, 0xcd, 0xc5, 0x37, 0x95, 0x68, 0x4f, 0x6f, 0xde, 0x32,
0x0a, 0x3e, 0xbe, 0x5a, 0x8d, 0x48, 0xd2, 0x5c, 0x3f, 0xe1, 0x47, 0x05, 0x1d, 0xda,
0x2f, 0xcb, 0x1d, 0x61, 0x5a, 0xba, 0xab, 0xff, 0xd0, 0x41, 0xc3, 0x0e, 0x1a, 0x18,
0xb9, 0x55, 0x11, 0x74, 0x95, 0xd4
],
bytes_from_words_be(&[
0xeb457996, 0x70cdc537, 0x95684f6f, 0xde320a3e, 0xbe5a8d48, 0xd25c3fe1, 0x47051dda,
0x2fcb1d61, 0x5abaabff, 0xd041c30e, 0x1a18b955, 0x117495d4,
])
);
assert_eq!(
[
0x6d, 0x53, 0x3a, 0xa5, 0xb8, 0x06, 0x69, 0x55, 0xb1, 0xd5, 0x52, 0x84, 0xe4, 0x4a,
0xad, 0xe8, 0x27, 0x9a, 0xd4, 0xd2, 0xde, 0x9d, 0xe6, 0x61, 0x13, 0xfb, 0xa0, 0x77,
0x07, 0x6a, 0x6e, 0xfd
],
bytes_from_words_be(&[
0x6d533aa5, 0xb8066955, 0xb1d55284, 0xe44aade8, 0x279ad4d2, 0xde9de661, 0x13fba077,
0x76a6efd,
])
);
}
#[test]
pub fn test_bytes_swap_word_endian() {
assert_eq!(
[
0xeb, 0x45, 0x79, 0x96, 0x70, 0xcd, 0xc5, 0x37, 0x95, 0x68, 0x4f, 0x6f, 0xde, 0x32,
0x0a, 0x3e, 0xbe, 0x5a, 0x8d, 0x48, 0xd2, 0x5c, 0x3f, 0xe1, 0x47, 0x05, 0x1d, 0xda,
0x2f, 0xcb, 0x1d, 0x61, 0x5a, 0xba, 0xab, 0xff, 0xd0, 0x41, 0xc3, 0x0e, 0x1a, 0x18,
0xb9, 0x55, 0x11, 0x74, 0x95, 0xd4
],
bytes_swap_word_endian(&[
0x96, 0x79, 0x45, 0xeb, 0x37, 0xc5, 0xcd, 0x70, 0x6f, 0x4f, 0x68, 0x95, 0x3e, 0x0a,
0x32, 0xde, 0x48, 0x8d, 0x5a, 0xbe, 0xe1, 0x3f, 0x5c, 0xd2, 0xda, 0x1d, 0x05, 0x47,
0x61, 0x1d, 0xcb, 0x2f, 0xff, 0xab, 0xba, 0x5a, 0x0e, 0xc3, 0x41, 0xd0, 0x55, 0xb9,
0x18, 0x1a, 0xd4, 0x95, 0x74, 0x11
])
);
assert_eq!(
[
0x6d, 0x53, 0x3a, 0xa5, 0xb8, 0x06, 0x69, 0x55, 0xb1, 0xd5, 0x52, 0x84, 0xe4, 0x4a,
0xad, 0xe8, 0x27, 0x9a, 0xd4, 0xd2, 0xde, 0x9d, 0xe6, 0x61, 0x13, 0xfb, 0xa0, 0x77,
0x07, 0x6a, 0x6e, 0xfd
],
bytes_swap_word_endian(&[
0xa5, 0x3a, 0x53, 0x6d, 0x55, 0x69, 0x06, 0xb8, 0x84, 0x52, 0xd5, 0xb1, 0xe8, 0xad,
0x4a, 0xe4, 0xd2, 0xd4, 0x9a, 0x27, 0x61, 0xe6, 0x9d, 0xde, 0x77, 0xa0, 0xfb, 0x13,
0xfd, 0x6e, 0x6a, 0x7
])
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/hash_sha3.rs | sw-emulator/lib/periph/src/hash_sha3.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha3.rs
Abstract:
File contains SHA3 peripheral implementation.
--*/
use caliptra_emu_bus::{BusError, ReadOnlyRegister, ReadWriteRegister};
use caliptra_emu_crypto::Sha3;
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
enum CmdType {
Start = 0x1D,
Process = 0x2E,
Run = 0x31,
Done = 0x16,
}
impl From<CmdType> for u32 {
fn from(mode: CmdType) -> Self {
mode as Self
}
}
impl From<u32> for CmdType {
fn from(value: u32) -> Self {
match value {
0x1D => CmdType::Start,
0x2E => CmdType::Process,
0x31 => CmdType::Run,
0x16 => CmdType::Done,
_ => panic!("Invalid command type"),
}
}
}
enum Endianness {
Little = 0x0,
Big = 0x1,
}
impl From<Endianness> for u32 {
fn from(mode: Endianness) -> Self {
mode as Self
}
}
impl From<u32> for Endianness {
fn from(value: u32) -> Self {
match value {
0x0 => Endianness::Little,
0x1 => Endianness::Big,
_ => panic!("Invalid endianness"),
}
}
}
fn digest_to_state(input: [u8; 200]) -> [u32; 50] {
let mut output = [0u32; 50];
for (i, chunk) in input.chunks(4).enumerate() {
let mut array = [0u8; 4];
array.copy_from_slice(chunk);
output[i] = u32::from_be_bytes(array);
}
output
}
register_bitfields! [
u32,
/// Alert Test Register Fields
AlertTest [
RECOV_OPERATION_ERR OFFSET(0) NUMBITS(1) [],
FATAL_FAULT_ERR OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// Cfg Write Enable Register Fields
CfgRegWen [
EN OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Cfg Shadowed Register Fields
CfgShadowed [
RSVD1 OFFSET(0) NUMBITS(1) [],
KSTRENGTH OFFSET(1) NUMBITS(3) [],
MODE OFFSET(4) NUMBITS(2) [],
RSVD2 OFFSET(6) NUMBITS(2) [],
MSG_ENDIANNESS OFFSET(8) NUMBITS(1) [],
STATE_ENDIANNESS OFFSET(9) NUMBITS(1) [],
RSVD3 OFFSET(10) NUMBITS(22) [],
],
/// Command Register Fields
Cmd [
CMD OFFSET(0) NUMBITS(6) [],
RSVD1 OFFSET(6) NUMBITS(4) [],
ERR_PROCESSED OFFSET(10) NUMBITS(1) [],
RSVD2 OFFSET(11) NUMBITS(21) [],
],
/// Status Register Fields
Status [
SHA3_IDLE OFFSET(0) NUMBITS(1) [],
SHA3_ABSORB OFFSET(1) NUMBITS(1) [],
SHA3_SQUEEZE OFFSET(2) NUMBITS(1) [],
RSVD1 OFFSET(3) NUMBITS(5) [],
FIFO_DEPTH OFFSET(8) NUMBITS(5) [],
RSVD2 OFFSET(13) NUMBITS(1) [],
FIFO_EMPTY OFFSET(14) NUMBITS(1) [],
FIFO_FULL OFFSET(15) NUMBITS(1) [],
ALERT_FATAL_FAULT OFFSET(16) NUMBITS(1) [],
ALERT_RECOV_CTRL_UPDATE_ERR OFFSET(17) NUMBITS(1) [],
RSVD3 OFFSET(18) NUMBITS(14) [],
],
/// Err Code Register Fields
ErrCode [
ERR_CODE OFFSET(0) NUMBITS(32) [],
],
];
const SHA3_STATE_MEMORY_SIZE: usize = 1600 / 32;
/// SHA3 Peripheral
#[derive(Bus)]
pub struct HashSha3 {
/// Name 0 register
#[register(offset = 0x0000_0000)]
name0: ReadOnlyRegister<u32>,
/// Name 1 register
#[register(offset = 0x0000_0004)]
name1: ReadOnlyRegister<u32>,
/// Version 0 register
#[register(offset = 0x0000_0008)]
version0: ReadOnlyRegister<u32>,
/// Version 1 register
#[register(offset = 0x0000_000C)]
version1: ReadOnlyRegister<u32>,
/// Alert test register
#[register(offset = 0x0000_000C, write_fn = on_write_alert_test)]
alert_test: ReadWriteRegister<u32, AlertTest::Register>,
/// CFG_REGWEN register
#[register(offset = 0x0000_0010)]
cfg_regwen: ReadOnlyRegister<u32, CfgRegWen::Register>,
/// CFG_SHADOWED register
#[register(offset = 0x0000_0014, write_fn = on_write_cfg_shadowed)]
cfg_shadowed: ReadWriteRegister<u32, CfgShadowed::Register>,
/// CMD register
#[register(offset = 0x0000_0018, write_fn = on_write_cmd)]
cmd: ReadWriteRegister<u32, Cmd::Register>,
/// STATUS register
#[register(offset = 0x0000_001C)]
status: ReadOnlyRegister<u32, Status::Register>,
/// ERR_CODE memory
#[register(offset = 0x0000_004c)]
err_code: ReadOnlyRegister<u32, ErrCode::Register>,
/// STATE memory
#[register_array(offset = 0x0000_0400)]
state: [u32; SHA3_STATE_MEMORY_SIZE],
/// MSG_FIFO memory.
/// Separate peripheral since it can handle writes at any offset and for bytes or words,
/// which is not supported by register or register_array.
#[peripheral(offset = 0x0000_0800, len = 0x100)]
msg_fifo: MsgFifo,
/// SHA3 engine
sha3: Sha3,
}
struct MsgFifo {
data: Vec<u8>,
swap_endianness: bool,
}
impl caliptra_emu_bus::Bus for MsgFifo {
fn read(&mut self, _size: RvSize, _addr: RvAddr) -> Result<RvData, BusError> {
Ok(0)
}
fn write(&mut self, size: RvSize, _addr: RvAddr, val: RvData) -> Result<(), BusError> {
match size {
RvSize::Byte => {
self.data.push(val as u8);
}
RvSize::HalfWord => {
// TODO: it's not clear what endianness means for halfword writes
let val = val as u16;
let val = if self.swap_endianness {
val.to_le_bytes()
} else {
val.to_be_bytes()
};
self.data.extend_from_slice(&val);
}
RvSize::Word => {
let val = if self.swap_endianness {
val.to_le_bytes()
} else {
val.to_be_bytes()
};
self.data.extend_from_slice(&val);
}
RvSize::Invalid => panic!("Invalid size"),
}
Ok(())
}
}
impl Default for HashSha3 {
fn default() -> Self {
Self::new()
}
}
impl HashSha3 {
/// NAME0 Register Value
const NAME0_VAL: RvData = 0x63616d68; // hmac
/// NAME1 Register Value
const NAME1_VAL: RvData = 0x33616873; // sha3
/// VERSION0 Register Value
const VERSION0_VAL: RvData = 0x30302E31; // 1.0
/// VERSION1 Register Value
const VERSION1_VAL: RvData = 0x00000000;
/// Create a new instance of HMAC-SHA-384 Engine
///
/// # Arguments
///
/// * `clock` - Clock
/// * `key_vault` - Key Vault
///
/// # Returns
///
/// * `Self` - Instance of HMAC-SHA-384 Engine
pub fn new() -> Self {
Self {
sha3: Sha3::new(),
name0: ReadOnlyRegister::new(Self::NAME0_VAL),
name1: ReadOnlyRegister::new(Self::NAME1_VAL),
version0: ReadOnlyRegister::new(Self::VERSION0_VAL),
version1: ReadOnlyRegister::new(Self::VERSION1_VAL),
alert_test: ReadWriteRegister::new(0),
cfg_regwen: ReadOnlyRegister::new(1),
cfg_shadowed: ReadWriteRegister::new(0),
cmd: ReadWriteRegister::new(0),
status: ReadOnlyRegister::new(
(Status::SHA3_IDLE::SET + Status::FIFO_EMPTY::SET).into(),
),
err_code: ReadOnlyRegister::new(0),
state: [0; SHA3_STATE_MEMORY_SIZE],
msg_fifo: MsgFifo {
data: Vec::new(),
swap_endianness: false,
},
}
}
/// On Write callback for `alert test` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_alert_test(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.alert_test.reg.set(val);
let fatal_fault = self.alert_test.reg.read(AlertTest::FATAL_FAULT_ERR);
let recov_err = self.alert_test.reg.read(AlertTest::RECOV_OPERATION_ERR);
self.status.reg.modify(
Status::ALERT_RECOV_CTRL_UPDATE_ERR.val(recov_err)
+ Status::ALERT_FATAL_FAULT.val(fatal_fault),
);
Ok(())
}
/// On Write callback for `configuration` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_cfg_shadowed(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// TODO: Figure out how to implement the "two subsequent writes" feature.
self.cfg_shadowed.reg.set(val);
let mode = self.cfg_shadowed.reg.read(CfgShadowed::MODE);
let strength = self.cfg_shadowed.reg.read(CfgShadowed::KSTRENGTH);
self.sha3.set_hasher(mode.into(), strength.into());
self.msg_fifo.swap_endianness =
self.cfg_shadowed.reg.read(CfgShadowed::STATE_ENDIANNESS) == Endianness::Big.into();
Ok(())
}
/// On Write callback for `cmd` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_cmd(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.cmd.reg.set(val);
let cmd: CmdType = self.cmd.reg.read(Cmd::CMD).into();
match cmd {
CmdType::Start => {
// change to abosrb state
self.status.reg.modify(Status::SHA3_ABSORB::SET);
}
CmdType::Process => {
// change to squeeze state
self.status.reg.modify(Status::SHA3_SQUEEZE::SET);
let res = self.sha3.update(&self.msg_fifo.data);
if !res {
Err(BusError::StoreAccessFault)?
}
let res = self.sha3.finalize();
self.msg_fifo.data.clear();
if !res {
Err(BusError::StoreAccessFault)?
}
self.state = digest_to_state(self.sha3.digest());
}
CmdType::Run => todo!(),
CmdType::Done => {
self.state.fill(0);
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use caliptra_emu_bus::Bus;
use caliptra_emu_crypto::{Sha3Mode, Sha3Strength};
use caliptra_emu_types::RvAddr;
use tock_registers::registers::InMemoryRegister;
const OFFSET_NAME0: RvAddr = 0x0;
const OFFSET_NAME1: RvAddr = 0x4;
const OFFSET_VERSION0: RvAddr = 0x8;
const OFFSET_VERSION1: RvAddr = 0xC;
const OFFSET_CFG_SHADOWED: RvAddr = 0x14;
const OFFSET_STATUS: RvAddr = 0x1C;
#[ignore] // disabled as the RTL does not seem to have these registers
#[test]
fn test_name() {
let mut sha3 = HashSha3::new();
let name0 = sha3.read(RvSize::Word, OFFSET_NAME0).unwrap();
let name0 = String::from_utf8_lossy(&name0.to_le_bytes()).to_string();
assert_eq!(name0, "hmac");
let name1 = sha3.read(RvSize::Word, OFFSET_NAME1).unwrap();
let name1 = String::from_utf8_lossy(&name1.to_le_bytes()).to_string();
assert_eq!(name1, "sha3");
}
#[ignore] // disabled as the RTL does not seem to have these registers
#[test]
fn test_version() {
let mut sha3 = HashSha3::new();
let version0 = sha3.read(RvSize::Word, OFFSET_VERSION0).unwrap();
let version0 = String::from_utf8_lossy(&version0.to_le_bytes()).to_string();
assert_eq!(version0, "1.00");
let version1 = sha3.read(RvSize::Word, OFFSET_VERSION1).unwrap();
let version1 = String::from_utf8_lossy(&version1.to_le_bytes()).to_string();
assert_eq!(version1, "\0\0\0\0");
}
#[test]
fn test_status() {
let mut sha3 = HashSha3::new();
let status = InMemoryRegister::<u32, Status::Register>::new(
sha3.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
assert!(status.is_set(Status::SHA3_IDLE));
assert!(status.is_set(Status::FIFO_EMPTY));
assert!(!status.is_set(Status::FIFO_FULL));
assert_eq!(status.read(Status::FIFO_DEPTH), 0);
}
#[test]
fn test_cfg_shadowed() {
let mut sha3 = HashSha3::new();
sha3.write(
RvSize::Word,
OFFSET_CFG_SHADOWED,
(CfgShadowed::KSTRENGTH.val(Sha3Strength::L256.into())
+ CfgShadowed::MODE.val(Sha3Mode::SHAKE.into()))
.into(),
)
.unwrap();
let cfg = InMemoryRegister::<u32, CfgShadowed::Register>::new(
sha3.read(RvSize::Word, OFFSET_CFG_SHADOWED).unwrap(),
);
assert_eq!(cfg.read(CfgShadowed::KSTRENGTH), Sha3Strength::L256.into());
assert_eq!(cfg.read(CfgShadowed::MODE), Sha3Mode::SHAKE.into());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/soc_reg.rs | sw-emulator/lib/periph/src/soc_reg.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
soc_reg.rs
Abstract:
File contains SOC Register implementation
--*/
use crate::helpers::{bytes_from_words_be, words_from_bytes_be};
use crate::mailbox::MailboxRequester;
use crate::root_bus::ReadyForFwCbArgs;
use crate::Mci;
use crate::{CaliptraRootBusArgs, Iccm, MailboxInternal};
use caliptra_emu_bus::BusError::{LoadAccessFault, StoreAccessFault};
use caliptra_emu_bus::{
ActionHandle, Bus, BusError, ReadOnlyRegister, ReadWriteRegister, Register, Timer, TimerAction,
};
use caliptra_emu_cpu::{IntSource, Irq};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use caliptra_hw_model_types::EtrngResponse;
use caliptra_registers::soc_ifc::regs::CptraHwConfigReadVal;
use caliptra_registers::soc_ifc_trng::regs::{CptraTrngStatusReadVal, CptraTrngStatusWriteVal};
use std::cell::RefCell;
use std::rc::Rc;
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use tock_registers::registers::InMemoryRegister;
// Second parameter is schedule(ticks_from_now: u64, cb: Box<dyn FnOnce(&mut
// Mailbox)>), which is called to schedule firmware writing in the future
type ReadyForFwCallback = Box<dyn FnMut(ReadyForFwCbArgs)>;
type UploadUpdateFwCallback = Box<dyn FnMut(&mut MailboxInternal)>;
type BootFsmGoCallback = Box<dyn FnMut()>;
type DownloadIdevidCsrCallback =
Box<dyn FnMut(&mut MailboxInternal, &mut InMemoryRegister<u32, DebugManufService::Register>)>;
mod constants {
#![allow(unused)]
pub const CPTRA_HW_ERROR_FATAL_START: u32 = 0x0;
pub const CPTRA_HW_ERROR_NON_FATAL_START: u32 = 0x4;
pub const CPTRA_FW_ERROR_FATAL_START: u32 = 0x8;
pub const CPTRA_FW_ERROR_NON_FATAL_START: u32 = 0xc;
pub const CPTRA_HW_ERROR_ENC_START: u32 = 0x10;
pub const CPTRA_FW_ERROR_ENC_START: u32 = 0x14;
pub const CPTRA_FW_EXTENDED_ERROR_INFO_START: u32 = 0x18;
pub const CPTRA_FW_EXTENDED_ERROR_INFO_SIZE: usize = 32;
pub const CPTRA_BOOT_STATUS_START: u32 = 0x38;
pub const CPTRA_FLOW_STATUS_START: u32 = 0x3c;
pub const CPTRA_RESET_REASON_START: u32 = 0x40;
pub const CPTRA_SECURITY_STATE_START: u32 = 0x44;
pub const CPTRA_MBOX_VALID_PAUSER_START: u32 = 0x48;
pub const CPTRA_MBOX_VALID_PAUSER_SIZE: usize = 20;
pub const CPTRA_MBOX_PAUSER_LOCK_START: u32 = 0x5c;
pub const CPTRA_MBOX_PAUSER_LOCK_SIZE: usize = 20;
pub const CPTRA_TRNG_VALID_PAUSER_START: u32 = 0x70;
pub const CPTRA_TRNG_PAUSER_LOCK_START: u32 = 0x74;
pub const CPTRA_TRNG_DATA_START: u32 = 0x78;
pub const CPTRA_TRNG_DATA_SIZE: usize = 48;
pub const CPTRA_TRNG_CTRL_START: u32 = 0xa8;
pub const CPTRA_TRNG_STATUS_START: u32 = 0xac;
pub const CPTRA_FUSE_WR_DONE_START: u32 = 0xb0;
pub const CPTRA_TIMER_CONFIG_START: u32 = 0xb4;
pub const CPTRA_BOOTFSM_GO_START: u32 = 0xb8;
pub const CPTRA_DBG_MANUF_SERVICE_REG_START: u32 = 0xbc;
pub const CPTRA_CLK_GATING_EN_START: u32 = 0xc0;
pub const CPTRA_GENERIC_INPUT_WIRES_START: u32 = 0xc4;
pub const CPTRA_GENERIC_INPUT_WIRES_SIZE: usize = 8;
pub const CPTRA_GENERIC_OUTPUT_WIRES_START: u32 = 0xcc;
pub const CPTRA_GENERIC_OUTPUT_WIRES_SIZE: usize = 8;
pub const FUSE_UDS_SEED_SIZE: usize = 64;
pub const FUSE_FIELD_ENTROPY_SIZE: usize = 32;
pub const SS_STRAP_GENERIC_SIZE: usize = 16;
pub const CPTRA_WDT_TIMER1_EN_START: u32 = 0xe4;
pub const CPTRA_WDT_TIMER1_CTRL_START: u32 = 0xe8;
pub const CPTRA_WDT_TIMER1_TIMEOUT_PERIOD_START: u32 = 0xec;
pub const CPTRA_WDT_TIMER2_EN_START: u32 = 0xf4;
pub const CPTRA_WDT_TIMER2_CTRL_START: u32 = 0xf8;
pub const CPTRA_WDT_TIMER2_TIMEOUT_PERIOD_START: u32 = 0xfc;
pub const CPTRA_WDT_STATUS_START: u32 = 0x104;
pub const CPTRA_FUSE_VALID_PAUSER_START: u32 = 0x108;
pub const CPTRA_OWNER_PK_HASH_START: u32 = 0x140;
pub const CPTRA_OWNER_PK_HASH_SIZE: usize = 48;
pub const CPTRA_FUSE_PAUSER_LOCK_START: u32 = 0x10c;
pub const FUSE_VENDOR_PK_HASH_START: u32 = 0x260;
pub const FUSE_VENDOR_PK_HASH_SIZE: usize = 48;
pub const FUSE_FMC_SVN_START: u32 = 0x2b4;
pub const FUSE_RUNTIME_SVN_START: u32 = 0x2b8;
pub const FUSE_RUNTIME_SVN_SIZE: usize = 16;
pub const FUSE_ANTI_ROLLBACK_DISABLE_START: u32 = 0x2c8;
pub const FUSE_IDEVID_CERT_ATTR_START: u32 = 0x2cc;
pub const FUSE_IDEVID_CERT_ATTR_SIZE: usize = 96;
pub const FUSE_IDEVID_MANUF_HSM_ID_START: u32 = 0x32c;
pub const FUSE_IDEVID_MANUF_HSM_ID_SIZE: usize = 16;
pub const FUSE_MANUF_DBG_UNLOCK_TOKEN_START: u32 = 0x34c;
pub const FUSE_HEK_SEED_START: u32 = 0x3c0;
pub const FUSE_HEK_SEED_SIZE: usize = 32;
pub const FUSE_MANUF_DBG_UNLOCK_TOKEN_SIZE_BYTES: usize = 64;
pub const SOC_MANIFEST_SVN_SIZE: usize = 16;
pub const INTERNAL_OBF_KEY_SIZE: usize = 32;
pub const INTERNAL_HEK_SEED_SIZE: usize = 32;
pub const INTERNAL_ICCM_LOCK_START: u32 = 0x620;
pub const INTERNAL_FW_UPDATE_RESET_START: u32 = 0x624;
pub const INTERNAL_FW_UPDATE_RESET_WAIT_CYCLES_START: u32 = 0x628;
pub const INTERNAL_NMI_VECTOR_START: u32 = 0x62c;
}
use constants::*;
register_bitfields! [
u32,
/// Flow Status
FlowStatus [
STATUS OFFSET(0) NUMBITS(23) [],
LDEVID_CERT_READY OFFSET(23) NUMBITS(1) [],
IDEVID_CSR_READY OFFSET(24) NUMBITS(1) [],
BOOT_FSM_PS OFFSET(25) NUMBITS(3) [],
READY_FOR_FW OFFSET(28) NUMBITS(1) [],
READY_FOR_RT OFFSET(29) NUMBITS(1) [],
READY_FOR_FUSES OFFSET(30) NUMBITS(1) [],
MBOX_FLOW_DONE OFFSET(31) NUMBITS(1) [],
],
/// Security State
SecurityState [
LIFE_CYCLE OFFSET(0) NUMBITS(2) [
UNPROVISIONED = 0b00,
MANUFACTURING = 0b01,
PRODUCTION = 0b11,
],
DEBUG_LOCKED OFFSET(2) NUMBITS(1) [],
SCAN_MODE OFFSET(3) NUMBITS(1) [],
RSVD OFFSET(4) NUMBITS(28) [],
],
/// Key Manifest Public Key Mask
VendorPubKeyMask [
MASK OFFSET(0) NUMBITS(4) [],
RSVD OFFSET(4) NUMBITS(28) [],
],
/// Anti Rollback Disable
AntiRollbackDisable [
DISABLE OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// ICCM Lock
IccmLock [
LOCK OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Firmware Update Reset
FwUpdateReset [
CORE_RST OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Firmware Update Reset Wait Cycles
FwUpdateResetWaitCycles [
WAIT_CYCLES OFFSET(0) NUMBITS(8) [],
RSVD OFFSET(8) NUMBITS(24) [],
],
/// Debug Manufacturing Service Register
pub DebugManufService [
REQ_IDEVID_CSR OFFSET(0) NUMBITS(1) [],
REQ_LDEVID_CERT OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// Reset Reason
ResetReason [
FW_UPD_RESET OFFSET(0) NUMBITS(1) [],
WARM_RESET OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// WDT Enable
WdtEnable [
TIMER_EN OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// WDT Control
WdtControl [
TIMER_RESTART OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// WDT Status
WdtStatus [
T1_TIMEOUT OFFSET(0) NUMBITS(1) [],
T2_TIMEOUT OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// Cap Lock
CapLock [
LOCK OFFSET(0) NUMBITS(1) [],
],
/// SoC Stepping ID
SocSteppingId [
SOC_STEPPING_ID OFFSET(0) NUMBITS(16) [],
RSVD OFFSET(16) NUMBITS(16) [],
],
/// Per-Type Interrupt Enable Register
GlobalIntrEn [
ERROR_EN OFFSET(0) NUMBITS(1) [],
NOTIF_EN OFFSET(1) NUMBITS(1) [],
],
/// Per-Event Interrupt Enable Register
ErrorIntrEn [
ERROR_INTERNAL_EN OFFSET(0) NUMBITS(1) [],
ERROR_INV_DEV_EN OFFSET(1) NUMBITS(1) [],
ERROR_CMD_FAIL_EN OFFSET(2) NUMBITS(1) [],
ERROR_BAD_FUSE_EN OFFSET(3) NUMBITS(1) [],
ERROR_ICCM_BLOCKED_EN OFFSET(4) NUMBITS(1) [],
ERROR_MBOX_ECC_UNC_EN OFFSET(5) NUMBITS(1) [],
ERROR_WDT_TIMER1_TIMEOUT_EN OFFSET(6) NUMBITS(1) [],
ERROR_WDT_TIMER2_TIMEOUT_EN OFFSET(7) NUMBITS(1) [],
RSVD OFFSET(8) NUMBITS(24) [],
],
/// Per-Event Interrupt Enable Register
NotifIntrEn [
NOTIF_CMD_AVAIL_EN OFFSET(0) NUMBITS(1) [],
NOTIF_MBOX_ECC_COR_EN OFFSET(1) NUMBITS(1) [],
NOTIF_DEBUG_LOCKED_EN OFFSET(2) NUMBITS(1) [],
NOTIF_SCAN_MODE_EN OFFSET(3) NUMBITS(1) [],
NOTIF_SOC_REQ_LOCK_EN OFFSET(4) NUMBITS(1) [],
NOTIF_GEN_IN_TOGGLE_EN OFFSET(5) NUMBITS(1) [],
RSVD OFFSET(6) NUMBITS(26) [],
],
/// Interrupt Status Aggregation Register
ErrorGlobalIntr [
AGG_STS OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Interrupt Status Aggregation Register
NotifGlobalIntr [
AGG_STS OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// ErrorIntrT
ErrorIntrT [
ERROR_INTERNAL_STS OFFSET(0) NUMBITS(1) [],
ERROR_INV_DEV_STS OFFSET(1) NUMBITS(1) [],
ERROR_CMD_FAIL_STS OFFSET(2) NUMBITS(1) [],
ERROR_BAD_FUSE_STS OFFSET(3) NUMBITS(1) [],
ERROR_ICCM_BLOCKED_STS OFFSET(4) NUMBITS(1) [],
ERROR_MBOX_ECC_UNC_STS OFFSET(5) NUMBITS(1) [],
ERROR_WDT_TIMER1_TIMEOUT_STS OFFSET(6) NUMBITS(1) [],
ERROR_WDT_TIMER2_TIMEOUT_STS OFFSET(7) NUMBITS(1) [],
RSVD OFFSET(8) NUMBITS(24) [],
],
/// NotifIntrT
NotifIntrT [
NOTIF_CMD_AVAIL_STS OFFSET(0) NUMBITS(1) [],
NOTIF_MBOX_ECC_COR_STS OFFSET(1) NUMBITS(1) [],
NOTIF_DEBUG_LOCKED_STS OFFSET(2) NUMBITS(1) [],
NOTIF_SCAN_MODE_STS OFFSET(3) NUMBITS(1) [],
NOTIF_SOC_REQ_LOCK_STS OFFSET(4) NUMBITS(1) [],
NOTIF_GEN_IN_TOGGLE_STS OFFSET(5) NUMBITS(1) [],
RSVD OFFSET(6) NUMBITS(26) [],
],
/// Interrupt Trigger Register
ErrIntrTrigT [
ERROR_INTERNAL_TRIG OFFSET(0) NUMBITS(1) [],
ERROR_INV_DEV_TRIG OFFSET(1) NUMBITS(1) [],
ERROR_CMD_FAIL_TRIG OFFSET(2) NUMBITS(1) [],
ERROR_BAD_FUSE_TRIG OFFSET(3) NUMBITS(1) [],
ERROR_ICCM_BLOCKED_TRIG OFFSET(4) NUMBITS(1) [],
ERROR_MBOX_ECC_UNC_TRIG OFFSET(5) NUMBITS(1) [],
ERROR_WDT_TIMER1_TIMEOUT_TRIG OFFSET(6) NUMBITS(1) [],
ERROR_WDT_TIMER2_TIMEOUT_TRIG OFFSET(7) NUMBITS(1) [],
RSVD OFFSET(8) NUMBITS(24) [],
],
/// Interrupt Trigger Register
NotifIntrTrigT [
NOTIF_CMD_AVAIL_TRIG OFFSET(0) NUMBITS(1) [],
NOTIF_MBOX_ECC_COR_TRIG OFFSET(1) NUMBITS(1) [],
NOTIF_DEBUG_LOCKED_TRIG OFFSET(2) NUMBITS(1) [],
NOTIF_SCAN_MODE_TRIG OFFSET(3) NUMBITS(1) [],
NOTIF_SOC_REQ_LOCK_TRIG OFFSET(4) NUMBITS(1) [],
NOTIF_GEN_IN_TOGGLE_TRIG OFFSET(5) NUMBITS(1) [],
RSVD OFFSET(6) NUMBITS(26) [],
],
/// Debug intent
SsDebugIntent [
DEBUG_INTENT OFFSET(0) NUMBITS(1) [],
],
/// Subsystem Debug Manufacturing Service Request Register
SsDbgManufServiceRegReq [
MANUF_DBG_UNLOCK_REQ OFFSET(0) NUMBITS(1) [],
PROD_DBG_UNLOCK_REQ OFFSET(1) NUMBITS(1) [],
UDS_PROGRAM_REQ OFFSET(2) NUMBITS(1) [],
RSVD OFFSET(3) NUMBITS(29) [],
],
/// Subsystem Debug Manufacturing Service Response Register
SsDbgManufServiceRegRsp [
MANUF_DBG_UNLOCK_SUCCESS OFFSET(0) NUMBITS(1) [],
MANUF_DBG_UNLOCK_FAIL OFFSET(1) NUMBITS(1) [],
MANUF_DBG_UNLOCK_IN_PROGRESS OFFSET(2) NUMBITS(1) [],
PROD_DBG_UNLOCK_SUCCESS OFFSET(3) NUMBITS(1) [],
PROD_DBG_UNLOCK_FAIL OFFSET(4) NUMBITS(1) [],
PROD_DBG_UNLOCK_IN_PROGRESS OFFSET(5) NUMBITS(1) [],
UDS_PROGRAM_SUCCESS OFFSET(6) NUMBITS(1) [],
UDS_PROGRAM_FAIL OFFSET(7) NUMBITS(1) [],
UDS_PROGRAM_IN_PROGRESS OFFSET(8) NUMBITS(1) [],
RSVD OFFSET(9) NUMBITS(23) [],
],
/// Hardware Configuration
HwConfig [
ITRNG_EN OFFSET(0) NUMBITS(1) [],
FUSE_GRANULARITY_64BIT OFFSET(1) NUMBITS(1) [],
RSVD_EN OFFSET(2) NUMBITS(3) [],
LMS_ACC_EN OFFSET(4) NUMBITS(1) [],
ACTIVE_MODE_EN OFFSET(5) NUMBITS(1) [],
OCP_LOCK_EN OFFSET(6) NUMBITS(1) [],
RSVD OFFSET(8) NUMBITS(25) [],
],
];
/// SOC Register peripheral
#[derive(Clone)]
pub struct SocRegistersInternal {
regs: Rc<RefCell<SocRegistersImpl>>,
}
/// Caliptra Register Start Address
const CALIPTRA_REG_START_ADDR: u32 = 0x00;
/// Caliptra Register End Address
const CALIPTRA_REG_END_ADDR: u32 = 0x820;
/// Caliptra Fuse start address
const FUSE_START_ADDR: u32 = 0x200;
/// Caliptra Fuse end address
const FUSE_END_ADDR: u32 = 0x340;
impl SocRegistersInternal {
/// Create an instance of SOC register peripheral
pub fn new(mailbox: MailboxInternal, iccm: Iccm, mci: Mci, args: CaliptraRootBusArgs) -> Self {
Self {
regs: Rc::new(RefCell::new(SocRegistersImpl::new(
mailbox, iccm, mci, args,
))),
}
}
pub fn is_debug_locked(&self) -> bool {
let reg = &self.regs.borrow().cptra_security_state.reg;
reg.read(SecurityState::DEBUG_LOCKED) != 0
}
/// Get Unique device secret
pub fn uds(&self) -> [u8; FUSE_UDS_SEED_SIZE] {
if self.is_debug_locked() {
bytes_from_words_be(&self.regs.borrow().fuse_uds_seed)
} else {
[0xff_u8; FUSE_UDS_SEED_SIZE]
}
}
// Get field entropy
pub fn field_entropy(&self) -> [u8; FUSE_FIELD_ENTROPY_SIZE] {
if self.is_debug_locked() {
bytes_from_words_be(&self.regs.borrow().fuse_field_entropy)
} else {
[0xff_u8; FUSE_FIELD_ENTROPY_SIZE]
}
}
/// Get deobfuscation engine key
pub fn doe_key(&self) -> [u8; INTERNAL_OBF_KEY_SIZE] {
if self.is_debug_locked() {
bytes_from_words_be(&self.regs.borrow().internal_obf_key)
} else {
[0xff_u8; INTERNAL_OBF_KEY_SIZE]
}
}
/// Get HEK seed
pub fn doe_hek_seed(&self) -> [u8; INTERNAL_HEK_SEED_SIZE] {
if self.is_debug_locked() {
bytes_from_words_be(&self.regs.borrow().fuse_hek_seed)
} else {
[0xff_u8; INTERNAL_HEK_SEED_SIZE]
}
}
/// Clear secrets
pub fn clear_secrets(&mut self) {
self.regs.borrow_mut().clear_secrets();
}
pub fn set_hw_config(&mut self, val: CptraHwConfigReadVal) {
self.regs.borrow_mut().cptra_hw_config = ReadWriteRegister {
reg: InMemoryRegister::<u32, HwConfig::Register>::new(val.into()),
};
}
pub fn set_generic_input_wires(&mut self, val: &[u32; CPTRA_GENERIC_INPUT_WIRES_SIZE / 4]) {
self.regs.borrow_mut().cptra_generic_input_wires = *val;
}
pub fn get_generic_input_wires(&self) -> [u32; CPTRA_GENERIC_INPUT_WIRES_SIZE / 4] {
self.regs.borrow().cptra_generic_input_wires
}
pub fn set_uds_seed(&mut self, seed: &[u32; FUSE_UDS_SEED_SIZE / 4]) {
self.regs.borrow_mut().fuse_uds_seed = *seed;
}
pub fn set_hek_seed(&mut self, seed: &[u32; FUSE_HEK_SEED_SIZE / 4]) {
self.regs.borrow_mut().fuse_hek_seed = *seed;
}
pub fn set_strap_generic(&mut self, val: &[u32; SS_STRAP_GENERIC_SIZE / 4]) {
self.regs.borrow_mut().ss_strap_generic = *val;
}
pub fn external_regs(&self) -> SocRegistersExternal {
SocRegistersExternal {
regs: self.regs.clone(),
}
}
}
impl Bus for SocRegistersInternal {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match addr {
CALIPTRA_REG_START_ADDR..=CALIPTRA_REG_END_ADDR => {
self.regs.borrow_mut().read(size, addr)
}
_ => Err(LoadAccessFault),
}
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match addr {
FUSE_START_ADDR..=FUSE_END_ADDR => {
// Microcontroller can't ever write to fuse registers
Err(StoreAccessFault)
}
CALIPTRA_REG_START_ADDR..=CALIPTRA_REG_END_ADDR => {
self.regs.borrow_mut().write(size, addr, val)
}
_ => Err(StoreAccessFault),
}
}
fn poll(&mut self) {
self.regs.borrow_mut().poll();
let mut regs = self.regs.borrow_mut();
if regs.mailbox.get_notif_irq() {
regs.notif_internal_intr_r
.reg
.modify(NotifIntrT::NOTIF_CMD_AVAIL_STS.val(1));
regs.notif_global_intr_r
.reg
.modify(NotifGlobalIntr::AGG_STS.val(1));
}
if regs.global_intr_en_r.reg.is_set(GlobalIntrEn::ERROR_EN)
&& regs.error_intr_en_r.reg.get() & regs.error_internal_intr_r.reg.get() != 0
{
regs.err_irq.set_level(true);
}
if regs.global_intr_en_r.reg.is_set(GlobalIntrEn::NOTIF_EN)
&& regs.notif_intr_en_r.reg.get() & regs.notif_internal_intr_r.reg.get() != 0
{
regs.notif_irq.set_level(true);
}
}
fn warm_reset(&mut self) {
self.regs.borrow_mut().bus_warm_reset();
}
fn update_reset(&mut self) {
self.regs.borrow_mut().bus_update_reset();
}
}
pub struct SocRegistersExternal {
regs: Rc<RefCell<SocRegistersImpl>>,
}
impl Bus for SocRegistersExternal {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match addr {
CALIPTRA_REG_START_ADDR..=CALIPTRA_REG_END_ADDR => {
self.regs.borrow_mut().read(size, addr)
}
_ => Err(LoadAccessFault),
}
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match addr {
FUSE_START_ADDR..=FUSE_END_ADDR => {
if self.regs.borrow_mut().fuses_can_be_written {
self.regs.borrow_mut().write(size, addr, val)
} else {
Err(StoreAccessFault)
}
}
CALIPTRA_REG_START_ADDR..=CALIPTRA_REG_END_ADDR => {
self.regs.borrow_mut().write(size, addr, val)
}
_ => Err(StoreAccessFault),
}
}
fn poll(&mut self) {
// Do nothing; external interface can't control time
}
fn warm_reset(&mut self) {
// Do nothing; external interface can't control reset
}
fn update_reset(&mut self) {
// Do nothing; external interface can't control reset
}
}
/// SOC Register implementation
#[derive(Bus)]
#[poll_fn(bus_poll)]
struct SocRegistersImpl {
#[register(offset = 0x0000)]
cptra_hw_error_fatal: ReadWriteRegister<u32>,
#[register(offset = 0x0004)]
cptra_hw_error_non_fatal: ReadWriteRegister<u32>,
#[register(offset = 0x0008)]
cptra_fw_error_fatal: ReadWriteRegister<u32>,
#[register(offset = 0x000c)]
cptra_fw_error_non_fatal: ReadWriteRegister<u32>,
#[register(offset = 0x0010)]
cptra_hw_error_enc: ReadWriteRegister<u32>,
#[register(offset = 0x0014)]
cptra_fw_error_enc: ReadWriteRegister<u32>,
#[register_array(offset = 0x0018)]
cptra_fw_extended_error_info: [u32; CPTRA_FW_EXTENDED_ERROR_INFO_SIZE / 4],
#[register(offset = 0x0038)]
cptra_boot_status: ReadWriteRegister<u32>,
#[register(offset = 0x003c, write_fn = on_write_flow_status)]
cptra_flow_status: ReadWriteRegister<u32, FlowStatus::Register>,
#[register(offset = 0x0040)]
cptra_reset_reason: ReadOnlyRegister<u32, ResetReason::Register>,
#[register(offset = 0x0044)]
cptra_security_state: ReadOnlyRegister<u32, SecurityState::Register>,
// TODO: Functionality for mbox pauser regs needs to be implemented
#[register_array(offset = 0x0048)]
cptra_mbox_valid_axi_user: [u32; CPTRA_MBOX_VALID_PAUSER_SIZE / 4],
#[register_array(offset = 0x005c)]
cptra_mbox_axi_user_lock: [u32; CPTRA_MBOX_PAUSER_LOCK_SIZE / 4],
#[register(offset = 0x0070)]
cptra_trng_valid_axi_user: ReadWriteRegister<u32>,
#[register(offset = 0x0074)]
cptra_trng_axi_user_lock: ReadWriteRegister<u32>,
#[register_array(offset = 0x0078)]
cptra_trng_data: [u32; CPTRA_TRNG_DATA_SIZE / 4],
#[register(offset = 0x00a8, write_fn = on_write_trng_status)]
cptra_trng_ctrl: u32,
#[register(offset = 0x00ac, write_fn = on_write_trng_status)]
cptra_trng_status: u32,
#[register(offset = 0x00b0, write_fn = on_write_fuse_wr_done)]
cptra_fuse_wr_done: u32,
#[register(offset = 0x00b4)]
cptra_timer_config: ReadWriteRegister<u32>,
#[register(offset = 0x00b8, write_fn = on_write_bootfsm_go)]
cptra_bootfsm_go: u32,
#[register(offset = 0x00bc)]
cptra_dbg_manuf_service_reg: ReadWriteRegister<u32, DebugManufService::Register>,
#[register(offset = 0x00c0)]
cptra_clk_gating_en: ReadOnlyRegister<u32>,
#[register_array(offset = 0x00c4)]
cptra_generic_input_wires: [u32; CPTRA_GENERIC_INPUT_WIRES_SIZE / 4],
#[register_array(offset = 0x00cc, write_fn = on_write_generic_output_wires)]
cptra_generic_output_wires: [u32; CPTRA_GENERIC_OUTPUT_WIRES_SIZE / 4],
#[register(offset = 0x00d4)]
cptra_hw_rev_id: ReadOnlyRegister<u32>,
#[register_array(offset = 0x00d8)]
cptra_fw_rev_id: [u32; 2],
#[register(offset = 0x00e0, write_fn = write_disabled)]
cptra_hw_config: ReadWriteRegister<u32, HwConfig::Register>,
#[register(offset = 0x00e4, write_fn = on_write_wdt_timer1_en)]
cptra_wdt_timer1_en: ReadWriteRegister<u32, WdtEnable::Register>,
#[register(offset = 0x00e8, write_fn = on_write_wdt_timer1_ctrl)]
cptra_wdt_timer1_ctrl: ReadWriteRegister<u32, WdtControl::Register>,
#[register_array(offset = 0x00ec)]
cptra_wdt_timer1_timeout_period: [u32; 2],
#[register(offset = 0x00f4, write_fn = on_write_wdt_timer2_en)]
cptra_wdt_timer2_en: ReadWriteRegister<u32, WdtEnable::Register>,
#[register(offset = 0x00f8, write_fn = on_write_wdt_timer2_ctrl)]
cptra_wdt_timer2_ctrl: ReadWriteRegister<u32, WdtControl::Register>,
#[register_array(offset = 0x00fc)]
cptra_wdt_timer2_timeout_period: [u32; 2],
#[register(offset = 0x0104)]
cptra_wdt_status: ReadOnlyRegister<u32, WdtStatus::Register>,
// TODO: Functionality for fuse pauser regs needs to be implemented
#[register(offset = 0x0108)]
cptra_fuse_valid_axi_user: ReadWriteRegister<u32>,
#[register(offset = 0x010c)]
cptra_fuse_axi_user_lock: ReadWriteRegister<u32>,
#[register_array(offset = 0x110)]
cptra_wdt_cfg: [u32; 2],
#[register(offset = 0x0118)]
cptra_i_trng_entropy_config_0: u32,
#[register(offset = 0x011c)]
cptra_i_trng_entropy_config_1: u32,
#[register_array(offset = 0x0120)]
cptra_rsvd_reg: [u32; 2],
#[register(offset = 0x128)]
cptra_hw_capabilities: u32,
#[register(offset = 0x12c)]
cptra_fw_capabilities: u32,
#[register(offset = 0x130)]
cptra_cap_lock: ReadWriteRegister<u32, CapLock::Register>,
// TODO implement lock
#[register_array(offset = 0x140)]
cptra_owner_pk_hash: [u32; CPTRA_OWNER_PK_HASH_SIZE / 4],
#[register(offset = 0x170)]
cptra_owner_pk_hash_lock: u32,
#[register_array(offset = 0x0200)]
fuse_uds_seed: [u32; FUSE_UDS_SEED_SIZE / 4],
#[register_array(offset = 0x0240)]
fuse_field_entropy: [u32; FUSE_FIELD_ENTROPY_SIZE / 4],
#[register_array(offset = 0x0260)]
fuse_vendor_pk_hash: [u32; FUSE_VENDOR_PK_HASH_SIZE / 4],
#[register(offset = 0x0290)]
fuse_ecc_revocation: u32,
#[register(offset = 0x02b4)]
fuse_fmc_svn: u32,
#[register_array(offset = 0x02b8)]
fuse_runtime_svn: [u32; FUSE_RUNTIME_SVN_SIZE / 4],
#[register(offset = 0x02c8)]
fuse_anti_rollback_disable: u32,
#[register_array(offset = 0x02cc)]
fuse_idevid_cert_attr: [u32; FUSE_IDEVID_CERT_ATTR_SIZE / 4],
#[register_array(offset = 0x032c)]
fuse_idevid_manuf_hsm_id: [u32; FUSE_IDEVID_MANUF_HSM_ID_SIZE / 4],
#[register(offset = 0x340)]
fuse_lms_revocation: u32,
#[register(offset = 0x344)]
fuse_mldsa_revocation: u32,
#[register(offset = 0x348)]
fuse_soc_stepping_id: ReadWriteRegister<u32, SocSteppingId::Register>,
#[register_array(offset = 0x34c)]
fuse_manuf_dbg_unlock_token: [u32; FUSE_MANUF_DBG_UNLOCK_TOKEN_SIZE_BYTES / 4],
#[register(offset = 0x38c)]
fuse_pqc_key_type: u32,
#[register_array(offset = 0x390)]
fuse_soc_manifest_svn: [u32; SOC_MANIFEST_SVN_SIZE / 4],
#[register(offset = 0x3a0)]
fuse_soc_manifest_max_svn: u32,
#[register_array(offset = 0x3c0)]
fuse_hek_seed: [u32; FUSE_HEK_SEED_SIZE / 4],
// writable from MCU
#[register(offset = 0x500)]
ss_caliptra_base_addr_l: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x504)]
ss_caliptra_base_addr_h: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x508)]
ss_recovery_mci_base_addr_l: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x50c)]
ss_recovery_mci_base_addr_h: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x510)]
ss_recovery_ifc_base_addr_l: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x514)]
ss_recovery_ifc_base_addr_h: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x518)]
ss_otp_fc_base_addr_l: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x51c)]
ss_otp_fc_base_addr_h: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x520)]
ss_uds_seed_base_addr_l: ReadWriteRegister<u32>,
// writable from MCU
#[register(offset = 0x524)]
ss_uds_seed_base_addr_h: ReadWriteRegister<u32>,
#[register(offset = 0x528)]
ss_prod_debug_unlock_auth_pk_hash_reg_bank_offset: ReadOnlyRegister<u32>,
#[register(offset = 0x52c)]
ss_num_of_prod_debug_unlock_auth_pk_hashes: ReadOnlyRegister<u32>,
#[register(offset = 0x530)]
ss_debug_intent: ReadOnlyRegister<u32, SsDebugIntent::Register>,
#[register(offset = 0x534)]
ss_caliptra_dma_axi_user: u32,
#[register(offset = 0x540)]
ss_key_release_base_addr_l: u32,
#[register(offset = 0x544)]
ss_key_release_base_addr_h: u32,
#[register(offset = 0x548)]
ss_key_release_size: u32,
#[register(offset = 0x54c, write_fn = on_write_ss_ocp_lock_ctrl)]
ss_ocp_lock_ctrl: u32,
#[register_array(offset = 0x5a0, write_fn = on_write_ss_strap_generic)]
ss_strap_generic: [u32; 4],
#[register(offset = 0x5c0)]
ss_dbg_manuf_service_reg_req: ReadWriteRegister<u32, SsDbgManufServiceRegReq::Register>,
#[register(offset = 0x5c4)]
ss_dbg_manuf_service_reg_rsp: ReadWriteRegister<u32, SsDbgManufServiceRegRsp::Register>,
#[register_array(offset = 0x5c8)]
ss_soc_dbg_unlock_level: [u32; 2],
#[register_array(offset = 0x5d0, write_fn = on_write_ss_generic_fw_exec_ctrl)]
ss_generic_fw_exec_ctrl: [u32; 4],
/// INTERNAL_OBF_KEY Register
internal_obf_key: [u32; 8],
/// INTERNAL_ICCM_LOCK Register
#[register(offset = 0x0620, write_fn = on_write_iccm_lock)]
internal_iccm_lock: ReadWriteRegister<u32, IccmLock::Register>,
/// INTERNAL_FW_UPDATE_RESET Register
#[register(offset = 0x0624, write_fn = on_write_internal_fw_update_reset)]
internal_fw_update_reset: ReadWriteRegister<u32, FwUpdateReset::Register>,
/// INTERNAL_FW_UPDATE_RESET_WAIT_CYCLES Register
#[register(offset = 0x0628)]
internal_fw_update_reset_wait_cycles: ReadWriteRegister<u32, FwUpdateResetWaitCycles::Register>,
/// INTERNAL_NMI_VECTOR Register
#[register(offset = 0x062c, write_fn = on_write_internal_nmi_vector)]
internal_nmi_vector: ReadWriteRegister<u32>,
/// GLOBAL_INTR_EN_R Register
#[register(offset = 0x0800)]
global_intr_en_r: ReadWriteRegister<u32, GlobalIntrEn::Register>,
/// ERROR_INTR_EN_R Register
#[register(offset = 0x0804)]
error_intr_en_r: ReadWriteRegister<u32, ErrorIntrEn::Register>,
/// NOTIF_INTR_EN_R Register
#[register(offset = 0x0808)]
notif_intr_en_r: ReadWriteRegister<u32, NotifIntrEn::Register>,
/// ERROR_GLOBAL_INTR_R Register
#[register(offset = 0x080c)]
error_global_intr_r: ReadWriteRegister<u32, ErrorGlobalIntr::Register>,
/// NOTIF_GLOBAL_INTR_R Register
#[register(offset = 0x0810)]
notif_global_intr_r: ReadWriteRegister<u32, NotifGlobalIntr::Register>,
/// ERROR_INTERNAL_INTR_R Register
#[register(offset = 0x0814)]
error_internal_intr_r: ReadWriteRegister<u32, ErrorIntrT::Register>,
/// NOTIF_INTERNAL_INTR_R Register
#[register(offset = 0x818, write_fn = on_write_notif_internal_intr)]
notif_internal_intr_r: ReadWriteRegister<u32, NotifIntrT::Register>,
/// ERROR_INTR_TRIG Register
#[register(offset = 0x81c)]
error_intr_trig_r: ReadWriteRegister<u32, ErrIntrTrigT::Register>,
/// NOTIF_INTR_TRIG Register
#[register(offset = 0x820, write_fn = on_write_notif_intr_trig)]
notif_intr_trig_r: ReadWriteRegister<u32, NotifIntrTrigT::Register>,
/// Mailbox
mailbox: MailboxInternal,
/// MCU
mci: Mci,
/// ICCM
iccm: Iccm,
/// Timer
timer: Timer,
err_irq: Irq,
notif_irq: Irq,
/// Firmware Write Complete action
op_fw_write_complete_action: Option<ActionHandle>,
#[allow(clippy::type_complexity)]
op_fw_write_complete_cb: Option<Box<dyn FnOnce(&mut MailboxInternal)>>,
/// Firmware Read Complete action
op_fw_read_complete_action: Option<ActionHandle>,
/// IDEVID CSR Read Complete action
op_idevid_csr_read_complete_action: Option<ActionHandle>,
/// Reset Trigger action
op_reset_trigger_action: Option<ActionHandle>,
/// test bench services callback
tb_services_cb: Box<dyn FnMut(u8)>,
ready_for_fw_cb: ReadyForFwCallback,
upload_update_fw: UploadUpdateFwCallback,
bootfsm_go_cb: BootFsmGoCallback,
fuses_can_be_written: bool,
download_idevid_csr_cb: DownloadIdevidCsrCallback,
/// WDT Timer1 Expired action
op_wdt_timer1_expired_action: Option<ActionHandle>,
/// WDT Timer2 Expired action
op_wdt_timer2_expired_action: Option<ActionHandle>,
etrng_responses: Box<dyn Iterator<Item = EtrngResponse>>,
pending_etrng_response: Option<EtrngResponse>,
op_pending_etrng_response_action: Option<ActionHandle>,
}
impl SocRegistersImpl {
/// Default unique device secret
const UDS: [u8; FUSE_UDS_SEED_SIZE] = [
0xF5, 0x8C, 0x4C, 0x4, 0xD6, 0xE5, 0xF1, 0xBA, 0x77, 0x9E, 0xAB, 0xFB, 0x5F, 0x7B, 0xFB,
0xD6, 0x9C, 0xFC, 0x4E, 0x96, 0x7E, 0xDB, 0x80, 0x8D, 0x67, 0x9F, 0x77, 0x7B, 0xC6, 0x70,
0x2C, 0x7D, 0x39, 0xF2, 0x33, 0x69, 0xA9, 0xD9, 0xBA, 0xCF, 0xA5, 0x30, 0xE2, 0x63, 0x4,
0x23, 0x14, 0x61, 0x3B, 0x4, 0x38, 0x96, 0xCF, 0xE1, 0x95, 0x74, 0xFC, 0xA0, 0xA, 0xCC,
0x2A, 0x5C, 0x31, 0xCD,
];
/// The number of CPU clock cycles it takes to read the firmware from the mailbox.
const FW_READ_TICKS: u64 = 0;
/// The number of CPU clock cycles it takes to read the IDEVID CSR from the mailbox.
const IDEVID_CSR_READ_TICKS: u64 = 100;
const CALIPTRA_HW_CONFIG_SUBSYSTEM_MODE: u32 = 1 << 5;
const CALIPTRA_HW_CONFIG_OCP_LOCK_MODE: u32 = 1 << 6;
pub fn new(
mailbox: MailboxInternal,
iccm: Iccm,
mci: Mci,
mut args: CaliptraRootBusArgs,
) -> Self {
let clock = &args.clock.clone();
let pic = &args.pic.clone();
let flow_status = InMemoryRegister::<u32, FlowStatus::Register>::new(0);
flow_status.write(FlowStatus::READY_FOR_FUSES.val(1));
let cptra_offset = 0x3000_0000u64;
let rri_offset = crate::dma::axi_root_bus::AxiRootBus::RECOVERY_REGISTER_INTERFACE_OFFSET;
let otc_fc_offset = crate::dma::axi_root_bus::AxiRootBus::OTC_FC_OFFSET;
// To make things easy the fuse bank is part of the fuse bank controller emulation
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/root_bus.rs | sw-emulator/lib/periph/src/root_bus.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains the root Bus implementation for a full-featured Caliptra emulator.
--*/
use crate::{
abr::Abr,
aes_clp::AesKeyReleaseOp,
dma::Dma,
helpers::words_from_bytes_be,
iccm::Iccm,
mci::Mci,
soc_reg::{DebugManufService, SocRegistersExternal},
Aes, AsymEcc384, Csrng, Doe, EmuCtrl, HashSha256, HashSha3, HashSha512, HmacSha, KeyVault,
MailboxExternal, MailboxInternal, MailboxRam, Sha512Accelerator, SocRegistersInternal, Uart,
};
use crate::{AesClp, MailboxRequester};
use caliptra_api_types::{DbgManufServiceRegReq, SecurityState};
use caliptra_emu_bus::{Bus, Clock, Event, Ram, Rom};
use caliptra_emu_cpu::{Pic, PicMmioRegisters};
use caliptra_emu_derive::Bus;
use caliptra_hw_model_types::{EtrngResponse, RandomEtrngResponses, RandomNibbles};
use std::{cell::RefCell, path::PathBuf, rc::Rc, sync::mpsc};
use tock_registers::registers::InMemoryRegister;
/// Default Deobfuscation engine key
pub const DEFAULT_DOE_KEY: [u8; 32] = [
0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81,
0x1F, 0x35, 0x2C, 0x7, 0x3B, 0x61, 0x8, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x9, 0x14, 0xDF, 0xF4,
];
pub struct TbServicesCb(pub Box<dyn FnMut(u8)>);
impl TbServicesCb {
pub fn new(f: impl FnMut(u8) + 'static) -> Self {
Self(Box::new(f))
}
pub(crate) fn take(&mut self) -> Box<dyn FnMut(u8)> {
std::mem::take(self).0
}
}
impl Default for TbServicesCb {
fn default() -> Self {
Self(Box::new(|_| {}))
}
}
impl std::fmt::Debug for TbServicesCb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TbServicesCb")
.field(&"<unknown closure>")
.finish()
}
}
impl From<Box<dyn FnMut(u8) + 'static>> for TbServicesCb {
fn from(value: Box<dyn FnMut(u8)>) -> Self {
Self(value)
}
}
type ReadyForFwCbSchedFn<'a> = dyn FnOnce(u64, Box<dyn FnOnce(&mut MailboxInternal)>) + 'a;
pub struct ReadyForFwCbArgs<'a> {
pub mailbox: &'a mut MailboxInternal,
pub(crate) sched_fn: Box<ReadyForFwCbSchedFn<'a>>,
}
impl ReadyForFwCbArgs<'_> {
pub fn schedule_later(
self,
ticks_from_now: u64,
cb: impl FnOnce(&mut MailboxInternal) + 'static,
) {
(self.sched_fn)(ticks_from_now, Box::new(cb));
}
}
type ReadyForFwFn = Box<dyn FnMut(ReadyForFwCbArgs)>;
pub struct ReadyForFwCb(pub ReadyForFwFn);
impl ReadyForFwCb {
pub fn new(f: impl FnMut(ReadyForFwCbArgs) + 'static) -> Self {
Self(Box::new(f))
}
pub(crate) fn take(&mut self) -> ReadyForFwFn {
std::mem::take(self).0
}
}
impl Default for ReadyForFwCb {
fn default() -> Self {
Self(Box::new(|_| {}))
}
}
impl std::fmt::Debug for ReadyForFwCb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ReadyForFwCb")
.field(&"<unknown closure>")
.finish()
}
}
impl From<Box<dyn FnMut(ReadyForFwCbArgs) + 'static>> for ReadyForFwCb {
fn from(value: Box<dyn FnMut(ReadyForFwCbArgs)>) -> Self {
Self(value)
}
}
type UploadUpdateFwFn = Box<dyn FnMut(&mut MailboxInternal)>;
pub struct UploadUpdateFwCb(pub UploadUpdateFwFn);
impl UploadUpdateFwCb {
pub fn new(f: impl FnMut(&mut MailboxInternal) + 'static) -> Self {
Self(Box::new(f))
}
pub(crate) fn take(&mut self) -> UploadUpdateFwFn {
std::mem::take(self).0
}
}
impl Default for UploadUpdateFwCb {
fn default() -> Self {
Self(Box::new(|_| {}))
}
}
impl std::fmt::Debug for UploadUpdateFwCb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("UploadUpdateFwCb")
.field(&"<unknown closure>")
.finish()
}
}
impl From<Box<dyn FnMut(&mut MailboxInternal) + 'static>> for UploadUpdateFwCb {
fn from(value: Box<dyn FnMut(&mut MailboxInternal)>) -> Self {
Self(value)
}
}
type DownloadCsrFn =
Box<dyn FnMut(&mut MailboxInternal, &mut InMemoryRegister<u32, DebugManufService::Register>)>;
pub struct DownloadIdevidCsrCb(pub DownloadCsrFn);
impl DownloadIdevidCsrCb {
pub fn new(
f: impl FnMut(&mut MailboxInternal, &mut InMemoryRegister<u32, DebugManufService::Register>)
+ 'static,
) -> Self {
Self(Box::new(f))
}
pub(crate) fn take(&mut self) -> DownloadCsrFn {
std::mem::take(self).0
}
}
impl Default for DownloadIdevidCsrCb {
fn default() -> Self {
Self(Box::new(|_, _| {}))
}
}
impl std::fmt::Debug for DownloadIdevidCsrCb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("DownloadCsrCb")
.field(&"<unknown closure>")
.finish()
}
}
impl
From<
Box<
dyn FnMut(&mut MailboxInternal, &mut InMemoryRegister<u32, DebugManufService::Register>)
+ 'static,
>,
> for DownloadIdevidCsrCb
{
fn from(
value: Box<
dyn FnMut(
&mut MailboxInternal,
&mut InMemoryRegister<u32, DebugManufService::Register>,
),
>,
) -> Self {
Self(value)
}
}
pub struct ActionCb(Box<dyn FnMut()>);
impl ActionCb {
pub fn new(f: impl FnMut() + 'static) -> Self {
Self(Box::new(f))
}
pub(crate) fn take(&mut self) -> Box<dyn FnMut()> {
std::mem::take(self).0
}
}
impl Default for ActionCb {
fn default() -> Self {
Self(Box::new(|| {}))
}
}
impl std::fmt::Debug for ActionCb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ActionCb")
.field(&"<unknown closure>")
.finish()
}
}
impl From<Box<dyn FnMut() + 'static>> for ActionCb {
fn from(value: Box<dyn FnMut()>) -> Self {
Self(value)
}
}
/// Caliptra Root Bus Arguments
pub struct CaliptraRootBusArgs<'a> {
pub pic: Rc<Pic>,
pub clock: Rc<Clock>,
pub rom: Vec<u8>,
pub log_dir: PathBuf,
// The security state wires provided to caliptra_top
pub security_state: SecurityState,
pub dbg_manuf_service_req: DbgManufServiceRegReq,
pub subsystem_mode: bool,
pub ocp_lock_en: bool,
pub prod_dbg_unlock_keypairs: Vec<(&'a [u8; 96], &'a [u8; 2592])>,
pub debug_intent: bool,
/// Callback to customize application behavior when
/// a write to the tb-services register write is performed.
pub tb_services_cb: TbServicesCb,
pub ready_for_fw_cb: ReadyForFwCb,
pub upload_update_fw: UploadUpdateFwCb,
pub bootfsm_go_cb: ActionCb,
pub download_idevid_csr_cb: DownloadIdevidCsrCb,
// The obfuscation key, as passed to caliptra-top
pub cptra_obf_key: [u32; 8],
pub itrng_nibbles: Option<Box<dyn Iterator<Item = u8>>>,
pub etrng_responses: Box<dyn Iterator<Item = EtrngResponse>>,
// Initial contents of the test sram
pub test_sram: Option<&'a [u8]>,
// If true, the recovery interface in the MCU will be used,
// otherwise, the local recovery interface is used.
pub use_mcu_recovery_interface: bool,
}
impl Default for CaliptraRootBusArgs<'_> {
fn default() -> Self {
Self {
clock: Default::default(),
pic: Default::default(),
rom: Default::default(),
log_dir: Default::default(),
security_state: Default::default(),
dbg_manuf_service_req: Default::default(),
subsystem_mode: false,
ocp_lock_en: false,
prod_dbg_unlock_keypairs: vec![],
debug_intent: false,
tb_services_cb: Default::default(),
ready_for_fw_cb: Default::default(),
upload_update_fw: Default::default(),
bootfsm_go_cb: Default::default(),
download_idevid_csr_cb: Default::default(),
cptra_obf_key: words_from_bytes_be(&DEFAULT_DOE_KEY),
itrng_nibbles: Some(Box::new(RandomNibbles::new_from_thread_rng())),
etrng_responses: Box::new(RandomEtrngResponses::new_from_stdrng()),
test_sram: None,
use_mcu_recovery_interface: false,
}
}
}
#[derive(Bus)]
#[incoming_event_fn(incoming_event)]
#[register_outgoing_events_fn(register_outgoing_events)]
pub struct CaliptraRootBus {
#[peripheral(offset = 0x0000_0000, len = 0x18000)]
pub rom: Rom,
#[peripheral(offset = 0x1000_0000, len = 0xa14)]
pub doe: Doe,
#[peripheral(offset = 0x1000_8000, len = 0xa14)]
pub ecc384: AsymEcc384,
#[peripheral(offset = 0x1001_0000, len = 0xa14)]
pub hmac: HmacSha,
#[peripheral(offset = 0x1001_1000, len = 0x8c)]
pub aes: Aes,
#[peripheral(offset = 0x1001_1800, len = 0x614)]
pub aes_clp: AesClp,
#[peripheral(offset = 0x1001_8000, len = 0x44c0)]
pub key_vault: KeyVault,
#[peripheral(offset = 0x1002_0000, len = 0xa14)]
pub sha512: HashSha512,
#[peripheral(offset = 0x1002_8000, len = 0xa14)]
pub sha256: HashSha256,
#[peripheral(offset = 0x1003_0000, len = 0x10000)]
pub abr: Abr,
#[peripheral(offset = 0x1004_0000, len = 0xa14)]
pub sha3: HashSha3,
#[peripheral(offset = 0x4000_0000, len = 0x40000)]
pub iccm: Iccm,
#[peripheral(offset = 0x2000_1000, len = 0x34)]
pub uart: Uart,
#[peripheral(offset = 0x2000_2000, len = 0x10e4)]
pub csrng: Csrng,
#[peripheral(offset = 0x2000_f000, len = 0x4)]
pub ctrl: EmuCtrl,
#[peripheral(offset = 0x3002_0000, len = 0x28)]
pub mailbox: MailboxInternal,
#[peripheral(offset = 0x3002_1000, len = 0xa14)]
pub sha512_acc: Sha512Accelerator,
#[peripheral(offset = 0x3002_2000, len = 0xa14)]
pub dma: Dma,
#[peripheral(offset = 0x3003_0000, len = 0xa38)]
pub soc_reg: SocRegistersInternal,
#[peripheral(offset = 0x3004_0000, len = 0x40000)]
pub mailbox_sram: MailboxRam,
#[peripheral(offset = 0x5000_0000, len = 0x40000)]
pub dccm: Ram,
#[peripheral(offset = 0x6000_0000, len = 0x507d)]
pub pic_regs: PicMmioRegisters,
pub mci: Mci,
}
impl CaliptraRootBus {
pub const ROM_SIZE: usize = 96 * 1024;
pub const ICCM_SIZE: usize = 256 * 1024;
pub const DCCM_SIZE: usize = 256 * 1024;
pub fn new(mut args: CaliptraRootBusArgs<'_>) -> Self {
let clock = &args.clock.clone();
let pic = &args.pic.clone();
let mut key_vault = KeyVault::new();
let mailbox_ram = MailboxRam::new(args.subsystem_mode);
let mailbox = MailboxInternal::new(clock, mailbox_ram.clone());
let rom = Rom::new(std::mem::take(&mut args.rom));
let prod_dbg_unlock_keypairs = std::mem::take(&mut args.prod_dbg_unlock_keypairs);
let iccm = Iccm::new(clock);
let itrng_nibbles = args.itrng_nibbles.take();
let test_sram = std::mem::take(&mut args.test_sram);
let use_mcu_recovery_interface = args.use_mcu_recovery_interface;
let mci = Mci::new(prod_dbg_unlock_keypairs);
let soc_reg = SocRegistersInternal::new(mailbox.clone(), iccm.clone(), mci.clone(), args);
if !soc_reg.is_debug_locked() {
// When debug is possible, the key-vault is initialized with a debug value...
// This is necessary to match the behavior of the RTL.
key_vault.clear_keys_with_debug_values(false);
}
let sha512_acc = Sha512Accelerator::new(clock, mailbox_ram.clone());
let aes_key = Rc::new(RefCell::new(None));
let aes_destination = Rc::new(RefCell::new(AesKeyReleaseOp::default()));
let aes = Aes::new(aes_key.clone(), aes_destination.clone());
let dma = Dma::new(
clock,
mailbox_ram.clone(),
soc_reg.clone(),
sha512_acc.clone(),
mci.clone(),
aes.clone(),
test_sram,
use_mcu_recovery_interface,
);
let sha512 = HashSha512::new(clock, key_vault.clone());
let ml_dsa87 = Abr::new(clock, key_vault.clone(), sha512.clone());
let sha3 = HashSha3::new();
Self {
rom,
aes,
aes_clp: AesClp::new(clock, key_vault.clone(), aes_key, aes_destination),
doe: Doe::new(clock, key_vault.clone(), soc_reg.clone()),
ecc384: AsymEcc384::new(clock, key_vault.clone(), sha512.clone()),
hmac: HmacSha::new(clock, key_vault.clone()),
key_vault: key_vault.clone(),
sha512,
sha256: HashSha256::new(clock),
abr: ml_dsa87,
sha3,
iccm,
dccm: Ram::new(vec![0; Self::DCCM_SIZE]),
uart: Uart::new(),
ctrl: EmuCtrl::new(),
soc_reg,
mailbox_sram: mailbox_ram.clone(),
mailbox,
sha512_acc,
dma,
csrng: Csrng::new(itrng_nibbles.unwrap()),
pic_regs: pic.mmio_regs(clock.clone()),
mci,
}
}
pub fn soc_to_caliptra_bus(&self, soc_user: MailboxRequester) -> SocToCaliptraBus {
SocToCaliptraBus {
mailbox: self.mailbox.as_external(soc_user),
soc_ifc: self.soc_reg.external_regs(),
}
}
pub fn mci_external_regs(&self) -> Mci {
self.mci.clone()
}
fn incoming_event(&mut self, event: Rc<Event>) {
self.aes.incoming_event(event.clone());
self.aes_clp.incoming_event(event.clone());
self.rom.incoming_event(event.clone());
self.doe.incoming_event(event.clone());
self.doe.incoming_event(event.clone());
self.ecc384.incoming_event(event.clone());
self.hmac.incoming_event(event.clone());
self.key_vault.incoming_event(event.clone());
self.sha512.incoming_event(event.clone());
self.sha256.incoming_event(event.clone());
self.abr.incoming_event(event.clone());
self.iccm.incoming_event(event.clone());
self.dccm.incoming_event(event.clone());
self.uart.incoming_event(event.clone());
self.ctrl.incoming_event(event.clone());
self.soc_reg.incoming_event(event.clone());
self.mailbox_sram.incoming_event(event.clone());
self.mailbox.incoming_event(event.clone());
self.sha512_acc.incoming_event(event.clone());
self.dma.incoming_event(event.clone());
self.csrng.incoming_event(event.clone());
self.pic_regs.incoming_event(event);
}
fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
self.aes.register_outgoing_events(sender.clone());
self.aes_clp.register_outgoing_events(sender.clone());
self.rom.register_outgoing_events(sender.clone());
self.doe.register_outgoing_events(sender.clone());
self.doe.register_outgoing_events(sender.clone());
self.ecc384.register_outgoing_events(sender.clone());
self.hmac.register_outgoing_events(sender.clone());
self.key_vault.register_outgoing_events(sender.clone());
self.sha512.register_outgoing_events(sender.clone());
self.sha256.register_outgoing_events(sender.clone());
self.abr.register_outgoing_events(sender.clone());
self.iccm.register_outgoing_events(sender.clone());
self.dccm.register_outgoing_events(sender.clone());
self.uart.register_outgoing_events(sender.clone());
self.ctrl.register_outgoing_events(sender.clone());
self.soc_reg.register_outgoing_events(sender.clone());
self.mailbox_sram.register_outgoing_events(sender.clone());
self.mailbox.register_outgoing_events(sender.clone());
self.sha512_acc.register_outgoing_events(sender.clone());
self.dma.register_outgoing_events(sender.clone());
self.csrng.register_outgoing_events(sender.clone());
self.pic_regs.register_outgoing_events(sender.clone());
self.mci.register_outgoing_events(sender.clone());
}
}
#[derive(Bus)]
pub struct SocToCaliptraBus {
#[peripheral(offset = 0x3002_0000, len = 0x1000)]
pub mailbox: MailboxExternal,
#[peripheral(offset = 0x3003_0000, len = 0x1000)]
soc_ifc: SocRegistersExternal,
}
#[cfg(test)]
mod tests {
use crate::KeyUsage;
use super::*;
#[test]
fn test_keyvault_init_val_in_debug_unlocked_mode() {
let mut root_bus = CaliptraRootBus::new(CaliptraRootBusArgs {
security_state: *SecurityState::default().set_debug_locked(false),
..CaliptraRootBusArgs::default()
});
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_key(true);
root_bus
.key_vault
.write_key(1, &[0x00, 0x11, 0x22, 0x33], key_usage.into())
.unwrap();
// The key-entry will still have the "init data" in the unwritten words.
// See chipsalliace/caliptra-rtl#114
assert_eq!(
root_bus.key_vault.read_key(1, key_usage).unwrap(),
[
0x00_u8, 0x11, 0x22, 0x33, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa
]
);
}
#[test]
fn test_keyvault_init_val_in_debug_locked_mode() {
let mut root_bus = CaliptraRootBus::new(CaliptraRootBusArgs {
security_state: *SecurityState::default().set_debug_locked(true),
..CaliptraRootBusArgs::default()
});
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_key(true);
root_bus
.key_vault
.write_key(1, &[0x00, 0x11, 0x22, 0x33], key_usage.into())
.unwrap();
// The key-entry will still have the "init data" in the unwritten words.
// See chipsalliace/caliptra-rtl#114
assert_eq!(
root_bus.key_vault.read_key(1, key_usage).unwrap(),
[
0x00_u8, 0x11, 0x22, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/dma.rs | sw-emulator/lib/periph/src/dma.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
dma.rs
Abstract:
File contains DMA peripheral implementation.
--*/
use crate::helpers::words_from_bytes_be;
use crate::{mci::Mci, Aes, MailboxRam, Sha512Accelerator, SocRegistersInternal};
use caliptra_emu_bus::{
ActionHandle, Bus, BusError, Clock, Event, ReadOnlyRegister, ReadWriteRegister, Timer,
WriteOnlyRegister,
};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use std::borrow::BorrowMut;
use std::collections::VecDeque;
use std::rc::Rc;
use std::sync::mpsc;
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
pub mod axi_root_bus;
use axi_root_bus::{AxiAddr, AxiRootBus};
pub mod otp_fc;
pub mod recovery;
const RECOVERY_STATUS_OFFSET: u64 = 0x40;
const AWATING_RECOVERY_IMAGE: u32 = 0x1;
/// The number of CPU clock cycles it takes to receive the payload from the DMA.
const PAYLOAD_AVAILABLE_OP_TICKS: u64 = 1000;
register_bitfields! [
u32,
/// Capabilities
Capabilites [
MAX_FIFO_DEPTH OFFSET(0) NUMBITS(12) [], // TODO?
],
/// Control
Control [
GO OFFSET(0) NUMBITS(1) [],
FLUSH OFFSET(1) NUMBITS(1) [],
AES_MODE_EN OFFSET(2) NUMBITS(1) [],
AES_GCM_MODE OFFSET(3) NUMBITS(1) [],
READ_ROUTE OFFSET(16) NUMBITS(2) [
DISABLE = 0b00,
MAILBOX = 0b01,
AHB_FIFO = 0b10,
AXI_WR = 0b11,
],
READ_ADDR_FIXED OFFSET(20) NUMBITS(1) [],
WRITE_ROUTE OFFSET(24) NUMBITS(2) [
DISABLE = 0b00,
MAILBOX = 0b01,
AHB_FIFO = 0b10,
AXI_RD = 0b11,
],
WRITE_ADDR_FIXED OFFSET(28) NUMBITS(1) [],
],
/// Status 0
Status0 [
BUSY OFFSET(0) NUMBITS(1) [], // 0 = ready to accept transfer request, 1 = operation in progress
ERROR OFFSET(1) NUMBITS(1) [],
RESERVED OFFSET(2) NUMBITS(2) [],
FIFO_DEPTH OFFSET(4) NUMBITS(12) [],
DMA_FSM_PRESENT_STATE OFFSET(16) NUMBITS(2) [
IDLE = 0b00,
WAIT_DATA = 0b01,
DONE = 0b10,
ERROR = 0b11,
],
PAYLOAD_AVAILABLE OFFSET(18) NUMBITS(1) [],
IMAGE_ACTIVATED OFFSET(19) NUMBITS(1) [],
RESERVED2 OFFSET(20) NUMBITS(12) [],
],
/// Block Size
BlockSize [
BLOCK_SIZE OFFSET(0) NUMBITS(12) [],
],
];
#[derive(Bus)]
#[poll_fn(poll)]
#[incoming_event_fn(incoming_event)]
#[register_outgoing_events_fn(register_outgoing_events)]
pub struct Dma {
/// ID
#[register(offset = 0x0000_0000)]
name: ReadOnlyRegister<u32>,
/// Capabilities
#[register(offset = 0x0000_0004)]
capabilities: ReadOnlyRegister<u32>,
/// Control
#[register(offset = 0x0000_0008, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
/// Status 0
#[register(offset = 0x0000_000c, read_fn = on_read_status0)]
status0: ReadOnlyRegister<u32, Status0::Register>,
/// Status 1: Reports remaining byte count that must be sent to destination.
#[register(offset = 0x0000_0010)]
status1: ReadOnlyRegister<u32>,
/// Source Address Low
#[register(offset = 0x0000_0014)]
src_addr_l: ReadWriteRegister<u32>,
/// Source Address High
#[register(offset = 0x0000_0018)]
src_addr_h: ReadWriteRegister<u32>,
/// Destination Address Low
#[register(offset = 0x0000_001c)]
dest_addr_l: ReadWriteRegister<u32>,
/// Destination Address High
#[register(offset = 0x0000_0020)]
dest_addr_h: ReadWriteRegister<u32>,
/// Byte count
#[register(offset = 0x0000_0024)]
byte_count: ReadWriteRegister<u32>,
/// Block size
#[register(offset = 0x0000_0028)]
block_size: ReadWriteRegister<u32, BlockSize::Register>,
/// Write Data
#[register(offset = 0x0000_002c, write_fn = on_write_data)]
write_data: WriteOnlyRegister<u32>,
/// Read Data
#[register(offset = 0x0000_0030, read_fn = on_read_data)]
read_data: ReadOnlyRegister<u32>,
// TODO interrupt block
/// Timer
timer: Timer,
/// Operation complete callback
op_complete_action: Option<ActionHandle>,
/// Payload available callback
op_payload_available_action: Option<ActionHandle>,
/// FIFO
fifo: VecDeque<u32>,
/// Axi Bus
pub axi: AxiRootBus,
/// Mailbox
mailbox: MailboxRam,
/// AES peripheral
aes: Aes,
// Ongoing DMA operations
pending_axi_to_axi: Option<WriteXfer>,
pending_axi_to_fifo: bool,
pending_axi_to_mailbox: bool,
// If true, the recovery interface in the MCU will be used,
// otherwise, the local recovery interface is used.
use_mcu_recovery_interface: bool,
}
#[derive(Debug)]
struct ReadXfer {
pub src: AxiAddr,
pub fixed: bool,
pub len: usize,
}
#[derive(Debug)]
struct WriteXfer {
pub dest: AxiAddr,
pub fixed: bool,
pub len: usize,
}
impl Dma {
const NAME: u32 = 0x6776_8068; // CLPD
const FIFO_SIZE: usize = 0x400;
// [TODO][CAP2] DMA transactions need to be a multiple of this
const AXI_DATA_WIDTH: usize = 4;
// How many cycles it takes for a DMA transfer, per word
const DMA_CYCLES_PER_WORD: u64 = 1;
// Minimum number of cycles for a DMA transfer.
const DMA_CYCLES_MIN: u64 = 16;
#[allow(clippy::too_many_arguments)]
pub fn new(
clock: &Clock,
mailbox: MailboxRam,
soc_reg: SocRegistersInternal,
sha512_acc: Sha512Accelerator,
mci: Mci,
aes: Aes,
test_sram: Option<&[u8]>,
use_mcu_recovery_interface: bool,
) -> Self {
Self {
name: ReadOnlyRegister::new(Self::NAME),
capabilities: ReadOnlyRegister::new(Self::FIFO_SIZE as u32 - 1), // MAX FIFO DEPTH
control: ReadWriteRegister::new(0),
status0: ReadOnlyRegister::new(0),
status1: ReadOnlyRegister::new(0),
src_addr_l: ReadWriteRegister::new(0),
src_addr_h: ReadWriteRegister::new(0),
dest_addr_l: ReadWriteRegister::new(0),
dest_addr_h: ReadWriteRegister::new(0),
byte_count: ReadWriteRegister::new(0),
block_size: ReadWriteRegister::new(0),
write_data: WriteOnlyRegister::new(0),
read_data: ReadOnlyRegister::new(0),
timer: Timer::new(clock),
op_complete_action: None,
op_payload_available_action: None,
fifo: VecDeque::with_capacity(Self::FIFO_SIZE),
axi: AxiRootBus::new(
soc_reg,
sha512_acc,
mci,
test_sram,
use_mcu_recovery_interface,
),
mailbox,
aes,
pending_axi_to_axi: None,
pending_axi_to_fifo: false,
pending_axi_to_mailbox: false,
use_mcu_recovery_interface,
}
}
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Write have to be words
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.control.reg.set(val);
// TODO not clear if this should clear
if self.control.reg.is_set(Control::FLUSH) {
self.fifo.clear();
self.status0.reg.write(Status0::DMA_FSM_PRESENT_STATE::IDLE);
self.control.reg.set(0);
}
if self.control.reg.is_set(Control::GO) && self.op_complete_action.is_none() {
if self.status0.reg.read(Status0::DMA_FSM_PRESENT_STATE)
== Status0::DMA_FSM_PRESENT_STATE::WAIT_DATA.value
{
// TODO write interrupt field
todo!();
}
self.op_complete_action = Some(
self.timer.schedule_poll_in(
(Self::DMA_CYCLES_PER_WORD * self.byte_count.reg.get() as u64 / 4)
.max(Self::DMA_CYCLES_MIN),
),
);
self.status0
.reg
.write(Status0::BUSY::SET + Status0::DMA_FSM_PRESENT_STATE::WAIT_DATA);
}
// clear the go and flush bits
self.control
.reg
.modify(Control::GO::CLEAR + Control::FLUSH::CLEAR);
Ok(())
}
fn on_read_status0(&mut self, size: RvSize) -> Result<RvData, BusError> {
if size != RvSize::Word {
Err(BusError::LoadAccessFault)?
}
let status0 = ReadWriteRegister::new(self.status0.reg.get());
status0.reg.modify(
Status0::FIFO_DEPTH.val((self.fifo.len() as u32 * 4).min(Status0::FIFO_DEPTH.mask)), // don't overflow bitfield
);
if self.use_mcu_recovery_interface {
self.axi.send_get_recovery_indirect_fifo_status();
if self.axi.get_recovery_indirect_fifo_status() != 0 {
status0.reg.modify(Status0::PAYLOAD_AVAILABLE::SET);
} else {
status0.reg.modify(Status0::PAYLOAD_AVAILABLE::CLEAR);
}
}
Ok(status0.reg.get())
}
pub fn on_write_data(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
match size {
RvSize::Word => {
self.fifo.push_back(val);
Ok(())
}
_ => Err(BusError::StoreAccessFault),
}
}
pub fn on_read_data(&mut self, size: RvSize) -> Result<RvData, BusError> {
match size {
// TODO write status in interrupt if empty
RvSize::Word => Ok(self.fifo.pop_front().unwrap_or(0)),
_ => Err(BusError::LoadAccessFault),
}
}
fn read_xfer(&self) -> ReadXfer {
assert!(self.byte_count.reg.get() % Self::AXI_DATA_WIDTH as u32 == 0);
ReadXfer {
src: ((self.src_addr_h.reg.get() as u64) << 32) | self.src_addr_l.reg.get() as u64,
fixed: self.control.reg.is_set(Control::READ_ADDR_FIXED),
len: self.byte_count.reg.get() as usize,
}
}
fn write_xfer(&self) -> WriteXfer {
assert!(self.byte_count.reg.get() % Self::AXI_DATA_WIDTH as u32 == 0);
WriteXfer {
dest: ((self.dest_addr_h.reg.get() as u64) << 32) | self.dest_addr_l.reg.get() as u64,
fixed: self.control.reg.is_set(Control::WRITE_ADDR_FIXED),
len: self.byte_count.reg.get() as usize,
}
}
fn check_block_size(&self) {
match (self.read_xfer().fixed, self.block_size.reg.get()) {
(true, 64) => (),
(false, 0) => (),
_ => {
panic!("Unsupported DMA block size: must be 64 for I3C to mailbox and 0 otherwise")
}
}
}
// Returns true if this completed immediately.
fn axi_to_mailbox(&mut self) -> bool {
self.check_block_size();
let xfer = self.read_xfer();
// check if we have to do the read async
if self.axi.must_schedule(xfer.src) {
self.pending_axi_to_mailbox = true;
self.timer.schedule_poll_in(1);
self.axi.schedule_read(xfer.src, xfer.len as u32).unwrap();
return false;
}
let block = self.read_axi_block(xfer);
self.write_mailbox(&block);
true
}
fn write_mailbox(&mut self, block: &[u32]) {
let mbox_ram = self.mailbox.borrow_mut();
for i in (0..block.len() * 4).step_by(Self::AXI_DATA_WIDTH) {
let data = block[i / 4];
mbox_ram
.write(Self::AXI_DATA_WIDTH.into(), i as RvAddr, data as RvData)
.unwrap();
}
}
// Returns true if this completed immediately.
fn axi_to_fifo(&mut self) -> bool {
self.check_block_size();
let xfer = self.read_xfer();
// check if we have to do the read async
if self.axi.must_schedule(xfer.src) {
self.pending_axi_to_fifo = true;
self.timer.schedule_poll_in(1);
self.axi.schedule_read(xfer.src, xfer.len as u32).unwrap();
return false;
}
let block = self.read_axi_block(xfer);
self.write_fifo_block(&block);
true
}
fn write_fifo_block(&mut self, block: &[u32]) {
for i in (0..block.len() * 4).step_by(Self::AXI_DATA_WIDTH) {
let cur_fifo_depth = self.status0.reg.read(Status0::FIFO_DEPTH);
if cur_fifo_depth >= Self::FIFO_SIZE as u32 {
self.status0.reg.write(Status0::ERROR::SET);
// TODO set interrupt bits
return;
}
self.fifo.push_back(block[i / 4]);
}
}
// Returns true if this completed immediately.
fn axi_to_axi(&mut self) -> bool {
self.check_block_size();
let read_xfer = self.read_xfer();
let write_xfer = self.write_xfer();
// check if we have to do the read async
if self.axi.must_schedule(read_xfer.src) {
self.pending_axi_to_axi = Some(write_xfer);
self.timer.schedule_poll_in(1);
self.axi
.schedule_read(read_xfer.src, read_xfer.len as u32)
.unwrap();
return false;
}
let data = self.read_axi_block(read_xfer);
self.write_axi_block(&data, write_xfer);
true
}
fn read_axi_block(&mut self, read_xfer: ReadXfer) -> Vec<u32> {
let mut block = vec![];
for i in (0..read_xfer.len).step_by(Self::AXI_DATA_WIDTH) {
let src = read_xfer.src + if read_xfer.fixed { 0 } else { i as AxiAddr };
let data = self.axi.read(Self::AXI_DATA_WIDTH.into(), src).unwrap();
block.push(data);
}
block
}
fn write_axi_block(&mut self, block: &[u32], write_xfer: WriteXfer) {
let block = if self.control.reg.is_set(Control::AES_MODE_EN) {
self.encrypt_block(block)
} else {
block.to_vec()
};
for i in (0..write_xfer.len).step_by(Self::AXI_DATA_WIDTH) {
let dest = write_xfer.dest + if write_xfer.fixed { 0 } else { i as AxiAddr };
let data = block[i / 4];
self.axi
.write(Self::AXI_DATA_WIDTH.into(), dest, data)
.unwrap();
}
}
fn encrypt_block(&mut self, block: &[u32]) -> Vec<u32> {
// Process each 16-byte block
block.chunks(4).fold(Vec::new(), |mut acc, chunk| {
let data = chunk
.iter()
.enumerate()
.fold([0u8; 16], |mut acc, (i, &word)| {
let bytes = word.to_le_bytes();
acc[i * 4..][..4].copy_from_slice(&bytes);
acc
});
let encrypted_data = self.aes.process_block(&data);
let encrypted_data_words = words_from_bytes_be(&encrypted_data);
acc.extend_from_slice(&encrypted_data_words[..chunk.len()]);
acc
})
}
// Returns true if this completed immediately.
fn mailbox_to_axi(&mut self) -> bool {
let xfer = self.write_xfer();
let mbox_ram = self.mailbox.borrow_mut();
if self.block_size.reg.get() != 0 {
panic!("Unsupported DMA block size: must be 0 for mailbox to AXI");
}
for i in (0..xfer.len).step_by(Self::AXI_DATA_WIDTH) {
let addr = xfer.dest + if xfer.fixed { 0 } else { i as AxiAddr };
let data = mbox_ram
.read(Self::AXI_DATA_WIDTH.into(), i as RvAddr)
.unwrap();
self.axi
.write(Self::AXI_DATA_WIDTH.into(), addr, data)
.unwrap();
}
true
}
// Returns true if this completed immediately.
fn fifo_to_axi(&mut self) -> bool {
let xfer = self.write_xfer();
if self.block_size.reg.get() != 0 {
panic!("Unsupported DMA block size: must be 0 for FIFO to AXI");
}
for i in (0..xfer.len).step_by(Self::AXI_DATA_WIDTH) {
let addr = xfer.dest + if xfer.fixed { 0 } else { i as AxiAddr };
let data = match self.fifo.pop_front() {
Some(b) => b,
None => {
self.status0.reg.write(Status0::ERROR::SET);
// TODO set interrupt bits
return true;
}
};
self.axi
.write(Self::AXI_DATA_WIDTH.into(), addr, data)
.unwrap();
if !self.use_mcu_recovery_interface {
// Check if FW is indicating that it is ready to receive the recovery image.
if ((addr & RECOVERY_STATUS_OFFSET) == RECOVERY_STATUS_OFFSET)
&& ((data & AWATING_RECOVERY_IMAGE) == AWATING_RECOVERY_IMAGE)
{
self.status0.reg.modify(Status0::PAYLOAD_AVAILABLE::CLEAR);
// Schedule the timer to indicate that the payload is available
self.op_payload_available_action =
Some(self.timer.schedule_poll_in(PAYLOAD_AVAILABLE_OP_TICKS));
}
}
}
true
}
fn op_complete(&mut self) {
let read_target = self.control.reg.read_as_enum(Control::READ_ROUTE).unwrap();
let write_origin = self.control.reg.read_as_enum(Control::WRITE_ROUTE).unwrap();
let complete = match (read_target, write_origin) {
(Control::READ_ROUTE::Value::MAILBOX, Control::WRITE_ROUTE::Value::DISABLE) => {
self.axi_to_mailbox()
}
(Control::READ_ROUTE::Value::AHB_FIFO, Control::WRITE_ROUTE::Value::DISABLE) => {
self.axi_to_fifo()
}
(Control::READ_ROUTE::Value::AXI_WR, Control::WRITE_ROUTE::Value::AXI_RD) => {
self.axi_to_axi()
}
(Control::READ_ROUTE::Value::DISABLE, Control::WRITE_ROUTE::Value::MAILBOX) => {
self.mailbox_to_axi()
}
(Control::READ_ROUTE::Value::DISABLE, Control::WRITE_ROUTE::Value::AHB_FIFO) => {
self.fifo_to_axi()
}
(_, _) => panic!("Invalid read/write DMA combination"),
};
if complete {
self.set_status_complete();
}
}
fn set_status_complete(&mut self) {
self.status0
.reg
.modify(Status0::BUSY::CLEAR + Status0::DMA_FSM_PRESENT_STATE::DONE);
}
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
self.op_complete();
}
if self.timer.fired(&mut self.op_payload_available_action) {
self.status0.reg.modify(Status0::PAYLOAD_AVAILABLE::SET);
}
if let Some(dma_data) = self.axi.dma_result.take() {
if let Some(write_xfer) = self.pending_axi_to_axi.take() {
self.write_axi_block(&dma_data, write_xfer);
self.set_status_complete();
} else if self.pending_axi_to_fifo {
self.write_fifo_block(&dma_data);
self.set_status_complete();
self.pending_axi_to_fifo = false;
} else if self.pending_axi_to_mailbox {
self.write_mailbox(&dma_data);
self.set_status_complete();
self.pending_axi_to_mailbox = false;
}
} else if self.pending_axi_to_axi.is_some()
|| self.pending_axi_to_fifo
|| self.pending_axi_to_mailbox
{
// check again next cycle
self.timer.schedule_poll_in(1);
}
}
fn incoming_event(&mut self, event: Rc<Event>) {
self.axi.incoming_event(event);
}
fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
self.axi.register_outgoing_events(sender);
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use tock_registers::registers::InMemoryRegister;
use crate::{aes_clp::AesKeyReleaseOp, CaliptraRootBusArgs, Iccm, MailboxInternal};
use super::*;
const AXI_TEST_OFFSET: AxiAddr = 0xaa00;
const CTRL_OFFSET: RvAddr = 0x8;
const STATUS0_OFFSET: RvAddr = 0xc;
const SRC_ADDR_L_OFFSET: RvAddr = 0x14;
const SRC_ADDR_H_OFFSET: RvAddr = 0x18;
const DST_ADDR_L_OFFSET: RvAddr = 0x1c;
const DST_ADDR_H_OFFSET: RvAddr = 0x20;
const BYTE_COUNT_OFFSET: RvAddr = 0x24;
const WRITE_DATA_OFFSET: RvAddr = 0x2c;
const READ_DATA_OFFSET: RvAddr = 0x30;
fn dma_read_u32(dma: &mut Dma, clock: &Clock, addr: AxiAddr) -> u32 {
let ctrl = InMemoryRegister::<u32, Control::Register>::new(0);
ctrl.modify(Control::FLUSH::SET);
dma.write(RvSize::Word, CTRL_OFFSET, ctrl.get()).unwrap();
let ctrl = InMemoryRegister::<u32, Control::Register>::new(0);
ctrl.modify(Control::READ_ROUTE::AHB_FIFO);
dma.write(RvSize::Word, CTRL_OFFSET, ctrl.get()).unwrap();
dma.write(RvSize::Word, SRC_ADDR_L_OFFSET, addr as RvAddr)
.unwrap();
dma.write(RvSize::Word, SRC_ADDR_H_OFFSET, (addr >> 32) as RvAddr)
.unwrap();
dma.write(RvSize::Word, BYTE_COUNT_OFFSET, Dma::AXI_DATA_WIDTH as u32)
.unwrap();
// Launch transaction
ctrl.modify(Control::GO::SET);
dma.write(RvSize::Word, CTRL_OFFSET, ctrl.get()).unwrap();
while {
let status0 = dma.read(RvSize::Word, STATUS0_OFFSET).unwrap();
let status0 = InMemoryRegister::<u32, Status0::Register>::new(status0);
status0.is_set(Status0::BUSY)
} {
clock.increment_and_process_timer_actions(1, dma);
}
dma.read(RvSize::Word, READ_DATA_OFFSET).unwrap()
}
fn dma_write_u32(dma: &mut Dma, clock: &Clock, addr: AxiAddr, data: RvData) {
let ctrl = InMemoryRegister::<u32, Control::Register>::new(0);
ctrl.modify(Control::FLUSH::SET);
dma.write(RvSize::Word, CTRL_OFFSET, ctrl.get()).unwrap();
dma.write(RvSize::Word, WRITE_DATA_OFFSET, data).unwrap();
dma.write(RvSize::Word, DST_ADDR_L_OFFSET, addr as RvAddr)
.unwrap();
dma.write(RvSize::Word, DST_ADDR_H_OFFSET, (addr >> 32) as RvAddr)
.unwrap();
let ctrl = InMemoryRegister::<u32, Control::Register>::new(0);
ctrl.modify(Control::WRITE_ROUTE::AHB_FIFO);
dma.write(RvSize::Word, CTRL_OFFSET, ctrl.get()).unwrap();
dma.write(RvSize::Word, BYTE_COUNT_OFFSET, Dma::AXI_DATA_WIDTH as u32)
.unwrap();
// Launch transaction
ctrl.modify(Control::GO::SET);
dma.write(RvSize::Word, CTRL_OFFSET, ctrl.get()).unwrap();
while {
let status0 = dma.read(RvSize::Word, STATUS0_OFFSET).unwrap();
let status0 = InMemoryRegister::<u32, Status0::Register>::new(status0);
status0.is_set(Status0::BUSY)
} {
clock.increment_and_process_timer_actions(1, dma);
}
}
#[test]
fn test_dma_fifo_read_write() {
let clock = Rc::new(Clock::new());
let mbox_ram = MailboxRam::default();
let iccm = Iccm::new(&clock);
let args = CaliptraRootBusArgs {
clock: clock.clone(),
..CaliptraRootBusArgs::default()
};
let mailbox_internal = MailboxInternal::new(&clock, mbox_ram.clone());
let mci = Mci::new(vec![]);
let soc_reg = SocRegistersInternal::new(mailbox_internal, iccm, mci.clone(), args);
let aes_key = Rc::new(RefCell::new(None));
let aes = crate::Aes::new(aes_key, Rc::new(RefCell::new(AesKeyReleaseOp::default())));
let mut dma = Dma::new(
&clock,
mbox_ram.clone(),
soc_reg,
Sha512Accelerator::new(&clock, mbox_ram.clone()),
mci.clone(),
aes,
None,
false,
);
assert_eq!(
dma_read_u32(&mut dma, &clock.clone(), AXI_TEST_OFFSET),
0xaabbccdd
); // Initial test value
let test_value = 0xdeadbeef;
dma_write_u32(&mut dma, &clock, AXI_TEST_OFFSET, test_value);
assert_eq!(
dma_read_u32(&mut dma, &clock.clone(), AXI_TEST_OFFSET),
test_value
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/emu_ctrl.rs | sw-emulator/lib/periph/src/emu_ctrl.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
emu_ctrl.rs
Abstract:
File contains emulation control device implementation.
--*/
use caliptra_emu_bus::{Bus, BusError};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use std::process::exit;
/// Emulation Control
pub struct EmuCtrl {}
impl EmuCtrl {
// Exit emulator address
const ADDR_EXIT: RvAddr = 0x0000_0000;
/// Create an new instance of emulator control
///
/// # Arguments
///
/// * `name` - Name of the device
pub fn new() -> Self {
Self {}
}
/// Memory map size.
pub fn mmap_size(&self) -> RvAddr {
4
}
}
impl Default for EmuCtrl {
fn default() -> Self {
Self::new()
}
}
impl Bus for EmuCtrl {
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::LoadAccessFault`
/// or `RvExceptionCause::LoadAddrMisaligned`
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match (size, addr) {
(RvSize::Word, EmuCtrl::ADDR_EXIT) => Ok(0),
_ => Err(BusError::LoadAccessFault),
}
}
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `val` - Data to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::StoreAccessFault`
/// or `RvExceptionCause::StoreAddrMisaligned`
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match (size, addr) {
(RvSize::Word, EmuCtrl::ADDR_EXIT) => {
exit(val as i32);
}
_ => Err(BusError::StoreAccessFault)?,
}
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/uart.rs | sw-emulator/lib/periph/src/uart.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
uart.rs
Abstract:
File contains UART device implementation.
--*/
use caliptra_emu_bus::{Bus, BusError};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
pub struct Uart {
bit_rate: u8,
data_bits: u8,
stop_bits: u8,
}
impl Uart {
/// Bit Rate Register
const ADDR_BIT_RATE: RvAddr = 0x00000010;
/// Data Bits Register
const ADDR_DATA_BITS: RvAddr = 0x00000011;
/// Stop Bits Register
const ADDR_STOP_BITS: RvAddr = 0x00000012;
/// Transmit status Register
const ADDR_TX_STATUS: RvAddr = 0x00000040;
/// Transmit Data Register
const ADDR_TX_DATA: RvAddr = 0x00000041;
pub fn new() -> Self {
Self {
bit_rate: 0,
data_bits: 8,
stop_bits: 1,
}
}
/// Memory map size.
pub fn mmap_size(&self) -> RvAddr {
256
}
}
impl Default for Uart {
fn default() -> Self {
Self::new()
}
}
impl Bus for Uart {
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::LoadAccessFault`
/// or `RvExceptionCause::LoadAddrMisaligned`
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match (size, addr) {
(RvSize::Byte, Uart::ADDR_BIT_RATE) => Ok(self.bit_rate as RvData),
(RvSize::Byte, Uart::ADDR_DATA_BITS) => Ok(self.data_bits as RvData),
(RvSize::Byte, Uart::ADDR_STOP_BITS) => Ok(self.stop_bits as RvData),
(RvSize::Byte, Uart::ADDR_TX_STATUS) => Ok(1),
_ => Err(BusError::LoadAccessFault),
}
}
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `data` - Data to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::StoreAccessFault`
/// or `RvExceptionCause::StoreAddrMisaligned`
fn write(&mut self, size: RvSize, addr: RvAddr, value: RvData) -> Result<(), BusError> {
match (size, addr) {
(RvSize::Byte, Uart::ADDR_BIT_RATE) => self.bit_rate = value as u8,
(RvSize::Byte, Uart::ADDR_DATA_BITS) => self.data_bits = value as u8,
(RvSize::Byte, Uart::ADDR_STOP_BITS) => self.stop_bits = value as u8,
(RvSize::Byte, Uart::ADDR_TX_DATA) => print!("{}", value as u8 as char),
_ => Err(BusError::StoreAccessFault)?,
}
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/aes.rs | sw-emulator/lib/periph/src/aes.rs | // Licensed under the Apache-2.0 license
use crate::aes_clp::AesKeyReleaseOp;
use crate::helpers::words_from_bytes_be;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt, KeyInit};
use aes::Aes256;
use caliptra_emu_bus::{Bus, BusError, Event, ReadWriteRegister};
use caliptra_emu_bus::{ReadOnlyRegister, WriteOnlyRegister};
use caliptra_emu_crypto::{Aes256Cbc, Aes256Ctr, Aes256Gcm, GHash, AES_256_BLOCK_SIZE};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use rand::Rng;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use std::sync::mpsc;
use tock_registers::interfaces::{Readable, Writeable};
use tock_registers::register_bitfields;
register_bitfields! [
u32,
pub Status [
IDLE OFFSET(0) NUMBITS(1) [],
STALL OFFSET(1) NUMBITS(1) [],
OUTPUT_LOST OFFSET(2) NUMBITS(1) [],
OUTPUT_VALID OFFSET(3) NUMBITS(1) [],
INPUT_READY OFFSET(4) NUMBITS(1) [],
ALERT_RECOV_CTRL_UPDATE_ERROR OFFSET(5) NUMBITS(1) [],
ALERT_FATAL_FAULT OFFSET(6) NUMBITS(1) [],
],
pub Ctrl [
OP OFFSET(0) NUMBITS(2) [
ENCRYPT = 1,
DECRYPT = 2,
],
MODE OFFSET(2) NUMBITS(6) [
ECB = 1,
CBC = 2,
CFB = 4,
OFB = 8,
CTR = 16,
GCM = 32,
NONE = 0x3f,
],
KEY_LEN OFFSET(8) NUMBITS(3) [
KEY_128 = 1,
KEY_192 = 2,
KEY_256 = 4,
],
SIDELOAD OFFSET(11) NUMBITS(1) [],
PRNG_RESEED_RATE OFFSET(12) NUMBITS(3) [],
MANUAL_OPERATION OFFSET(15) NUMBITS(1) [
DISABLED = 0,
ENABLED = 1,
],
],
GcmCtrl [
PHASE OFFSET(0) NUMBITS(6) [
INIT = 1,
RESTORE = 2,
AAD = 4,
TEXT = 8,
SAVE = 16,
TAG = 32,
],
NUM_VALID_BYTES OFFSET(6) NUMBITS(5) [],
],
Trigger [
START OFFSET(0) NUMBITS(1) [],
KEY_IV_DATA_IN_CLEAR OFFSET(1) NUMBITS(1) [],
DATA_OUT_CLEAR OFFSET(2) NUMBITS(1) [],
PRNG_RESEED OFFSET(3) NUMBITS(1) [],
],
];
/// AES peripheral registers implementation
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
pub struct AesRegs {
#[register_array(offset = 0x4, item_size = 4, len = 8, write_fn = write_key_share0)]
key_share0: [u32; 8],
#[register_array(offset = 0x24, item_size = 4, len = 8, write_fn = write_key_share1)]
key_share1: [u32; 8],
#[register_array(offset = 0x44, item_size = 4, len = 4, write_fn = write_iv)]
iv: [u32; 4],
#[register_array(offset = 0x54, item_size = 4, len = 4, write_fn = write_data_in)]
data_in: [u32; 4],
#[register_array(offset = 0x64, item_size = 4, len = 4, read_fn = read_data_out)]
data_out: [u32; 4],
#[register(offset = 0x74)]
ctrl_shadowed: ReadWriteRegister<u32, Ctrl::Register>,
#[register(offset = 0x78)]
_ctrl_aux_shadowed: ReadWriteRegister<u32>,
#[register(offset = 0x7c)]
_ctrl_aux_regwen: ReadWriteRegister<u32>,
#[register(offset = 0x80, write_fn = write_trigger)]
trigger: WriteOnlyRegister<u32, Trigger::Register>,
#[register(offset = 0x84)]
status: ReadOnlyRegister<u32, Status::Register>,
#[register(offset = 0x88, write_fn = write_ctrl_gcm_shadowed)]
ctrl_gcm_shadowed: ReadOnlyRegister<u32, GcmCtrl::Register>,
data_in_written: [bool; 4],
ghash: GHash,
cbc: Aes256Cbc,
ctr: Aes256Ctr,
data_out_read: [bool; 4],
data_out_block_queue: VecDeque<u32>,
key_vault_key: Rc<RefCell<Option<[u8; 32]>>>,
key_vault_destination: Rc<RefCell<AesKeyReleaseOp>>,
}
impl AesRegs {
/// Create a new AES peripheral registers instance
pub fn new(
key_vault_key: Rc<RefCell<Option<[u8; 32]>>>,
key_vault_destination: Rc<RefCell<AesKeyReleaseOp>>,
) -> Self {
Self {
key_share0: [0; 8],
key_share1: [0; 8],
iv: [0; 4],
data_in: [0; 4],
data_out: [0; 4],
ctrl_shadowed: ReadWriteRegister::new(0),
_ctrl_aux_shadowed: ReadWriteRegister::new(0),
_ctrl_aux_regwen: ReadWriteRegister::new(0),
trigger: WriteOnlyRegister::new(0),
status: ReadOnlyRegister::new(
(Status::INPUT_READY.val(1) + Status::OUTPUT_VALID.val(1) + Status::IDLE.val(1))
.into(),
),
ctrl_gcm_shadowed: ReadOnlyRegister::new(0),
data_in_written: [false; 4],
ghash: GHash::default(),
cbc: Aes256Cbc::default(),
ctr: Aes256Ctr::default(),
data_out_read: [true; 4],
data_out_block_queue: VecDeque::new(),
key_vault_key,
key_vault_destination,
}
}
fn write_trigger(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.trigger.reg.set(val);
if self.trigger.reg.is_set(Trigger::KEY_IV_DATA_IN_CLEAR) {
rand::thread_rng().fill(&mut self.key_share0[..]);
rand::thread_rng().fill(&mut self.key_share1[..]);
rand::thread_rng().fill(&mut self.iv[..]);
rand::thread_rng().fill(&mut self.data_in[..]);
self.data_in_written.fill(false);
self.ghash = GHash::default();
self.cbc = Aes256Cbc::default();
self.data_out_read.fill(true);
self.data_out_block_queue.clear();
}
if self.trigger.reg.is_set(Trigger::DATA_OUT_CLEAR) {
rand::thread_rng().fill(&mut self.data_out[..]);
} else {
self.data_out.fill(0);
}
self.trigger.reg.set(0);
Ok(())
}
fn poll(&mut self) {
// check if key vault key was loaded
let key = self.key_vault_key.borrow_mut().take();
if let Some(key) = key {
let k = words_from_bytes_be(&key);
for (i, ki) in k.into_iter().enumerate() {
self.write_key_share0(RvSize::Word, i, ki).unwrap();
self.write_key_share1(RvSize::Word, i, 0).unwrap();
}
}
}
fn warm_reset(&mut self) {
self.key_share0.fill(0);
self.key_share1.fill(0);
self.iv.fill(0);
self.data_in.fill(0);
self.data_out.fill(0);
self.ctrl_shadowed.reg.set(0);
self._ctrl_aux_shadowed.reg.set(0);
self._ctrl_aux_regwen.reg.set(0);
self.trigger.reg.set(0);
self.status.reg.set(
(Status::INPUT_READY.val(1) + Status::OUTPUT_VALID.val(1) + Status::IDLE.val(1)).into(),
);
self.ctrl_gcm_shadowed.reg.set(0);
self.data_in_written.fill(false);
self.ghash = GHash::default();
self.cbc = Aes256Cbc::default();
self.data_out_read.fill(true);
self.data_out_block_queue.clear();
}
fn write_ctrl_gcm_shadowed(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.ctrl_gcm_shadowed.reg.set(val);
match self.gcm_phase() {
GcmCtrl::PHASE::Value::INIT => {
self.data_in_written.fill(false);
self.data_in.fill(0);
self.data_out.fill(0);
self.ghash = GHash::new(&self.key());
self.iv.fill(0);
self.iv[3] = 1;
}
GcmCtrl::PHASE::Value::RESTORE => {}
GcmCtrl::PHASE::Value::AAD => {}
GcmCtrl::PHASE::Value::TEXT => {}
GcmCtrl::PHASE::Value::SAVE => {
let ghash = self.ghash.state();
self.data_out[0] = u32::from_le_bytes(ghash[0..4].try_into().unwrap());
self.data_out[1] = u32::from_le_bytes(ghash[4..8].try_into().unwrap());
self.data_out[2] = u32::from_le_bytes(ghash[8..12].try_into().unwrap());
self.data_out[3] = u32::from_le_bytes(ghash[12..16].try_into().unwrap());
}
GcmCtrl::PHASE::Value::TAG => {}
}
Ok(())
}
fn gcm_phase(&self) -> GcmCtrl::PHASE::Value {
self.ctrl_gcm_shadowed
.reg
.read_as_enum(GcmCtrl::PHASE)
.unwrap_or(GcmCtrl::PHASE::Value::INIT)
}
fn is_encrypt(&self) -> bool {
self.ctrl_shadowed
.reg
.read_as_enum(Ctrl::OP)
.unwrap_or(Ctrl::OP::Value::ENCRYPT)
== Ctrl::OP::Value::ENCRYPT
}
fn key(&self) -> [u8; 32] {
let mut key = [0u8; 32];
for i in 0..8 {
let word = (self.key_share0[i] ^ self.key_share1[i]).to_le_bytes();
key[i * 4..(i + 1) * 4].copy_from_slice(&word);
}
key
}
fn gcm_iv(&self) -> [u8; 12] {
let mut iv = [0u8; 12];
for i in 0..3 {
let word = self.iv[i].to_le_bytes();
iv[i * 4..(i + 1) * 4].copy_from_slice(&word);
}
iv
}
fn iv(&self) -> [u8; 16] {
let mut iv = [0u8; 16];
for i in 0..4 {
let word = self.iv[i].to_le_bytes();
iv[i * 4..(i + 1) * 4].copy_from_slice(&word);
}
iv
}
fn read_data_out(&mut self, size: RvSize, index: usize) -> Result<RvData, BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
if index >= 4 {
Err(BusError::LoadAccessFault)?
}
self.data_out_read[index] = true;
match self.mode() {
Ctrl::MODE::Value::CBC => {
// block modes write data out only after 2 blocks are written
if self.data_out_read.iter().copied().all(|x| x) {
if self.data_out_block_queue.is_empty() {
Err(BusError::LoadAccessFault)?
}
self.data_out_read.fill(false);
self.data_out[0] = self.data_out_block_queue.pop_front().unwrap();
self.data_out[1] = self.data_out_block_queue.pop_front().unwrap();
self.data_out[2] = self.data_out_block_queue.pop_front().unwrap();
self.data_out[3] = self.data_out_block_queue.pop_front().unwrap();
}
}
// streaming modes and ECB can directly read the register
Ctrl::MODE::Value::CTR | Ctrl::MODE::Value::GCM | Ctrl::MODE::Value::ECB => (),
_ => todo!(),
}
let data = self.data_out[index];
Ok(data)
}
fn update_ecb(&mut self, data: &[u8]) {
assert_eq!(data.len(), 16);
let data: &[u8; 16] = data.try_into().unwrap();
let mut data = GenericArray::from(*data);
let cipher = Aes256::new((&self.key()).into());
if self.is_encrypt() {
cipher.encrypt_block(&mut data);
} else {
cipher.decrypt_block(&mut data);
}
self.data_out[0] = u32::from_le_bytes(data[0..4].try_into().unwrap());
self.data_out[1] = u32::from_le_bytes(data[4..8].try_into().unwrap());
self.data_out[2] = u32::from_le_bytes(data[8..12].try_into().unwrap());
self.data_out[3] = u32::from_le_bytes(data[12..16].try_into().unwrap());
let mut kv_op = self.key_vault_destination.borrow_mut();
kv_op.load_data(&self.data_out);
}
fn update_cbc(&mut self, data: &[u8]) {
assert_eq!(data.len(), 16);
let data: &[u8; 16] = data.try_into().unwrap();
let output = if self.is_encrypt() {
self.cbc.encrypt_block(data)
} else {
self.cbc.decrypt_block(data)
};
self.data_out_block_queue
.push_back(u32::from_le_bytes(output[0..4].try_into().unwrap()));
self.data_out_block_queue
.push_back(u32::from_le_bytes(output[4..8].try_into().unwrap()));
self.data_out_block_queue
.push_back(u32::from_le_bytes(output[8..12].try_into().unwrap()));
self.data_out_block_queue
.push_back(u32::from_le_bytes(output[12..16].try_into().unwrap()));
}
fn update_ctr(&mut self, data: &[u8]) {
assert_eq!(data.len(), 16);
let data: &[u8; 16] = data.try_into().unwrap();
let output = self.ctr.crypt_block(data);
self.data_out[0] = u32::from_le_bytes(output[0..4].try_into().unwrap());
self.data_out[1] = u32::from_le_bytes(output[4..8].try_into().unwrap());
self.data_out[2] = u32::from_le_bytes(output[8..12].try_into().unwrap());
self.data_out[3] = u32::from_le_bytes(output[12..16].try_into().unwrap());
}
fn update_gcm(&mut self, data: &[u8]) {
let num_valid = self.ctrl_gcm_shadowed.reg.read(GcmCtrl::NUM_VALID_BYTES) as usize;
let num_valid = if num_valid == 0 || num_valid > 16 {
16
} else {
num_valid
};
let mut buffer = [0u8; 16];
buffer[..num_valid].copy_from_slice(&data[..num_valid]);
let buffer = &buffer;
// populate the data_out and iv registers
// There is not proper AES streaming implementation, so we do this the slow way
// and recompute the GHASH ourselves.
let key = self.key();
let gcm_iv = self.gcm_iv();
match self.gcm_phase() {
GcmCtrl::PHASE::Value::AAD => {
self.ghash.update(buffer);
}
GcmCtrl::PHASE::Value::RESTORE => {
let mut state = [0u8; AES_256_BLOCK_SIZE];
state[0..4].copy_from_slice(&self.data_in[0].to_le_bytes());
state[4..8].copy_from_slice(&self.data_in[1].to_le_bytes());
state[8..12].copy_from_slice(&self.data_in[2].to_le_bytes());
state[12..16].copy_from_slice(&self.data_in[3].to_le_bytes());
self.ghash.restore(state);
}
GcmCtrl::PHASE::Value::TEXT => {
// in GCM encryption and decryption result in the same output
if self.iv[3] == 0 {
self.iv[3] = 2;
}
let output = Aes256Gcm::crypt_block(&key, &gcm_iv, self.iv[3] as usize - 2, buffer);
self.data_out[0] = u32::from_le_bytes(output[0..4].try_into().unwrap());
self.data_out[1] = u32::from_le_bytes(output[4..8].try_into().unwrap());
self.data_out[2] = u32::from_le_bytes(output[8..12].try_into().unwrap());
self.data_out[3] = u32::from_le_bytes(output[12..16].try_into().unwrap());
// update GHASH
let ciphertext = if self.is_encrypt() { &output } else { buffer };
let mut ciphertext = *ciphertext;
if num_valid != 16 {
ciphertext[num_valid..].fill(0);
}
self.ghash.update(&ciphertext);
self.iv[3] += 1;
}
GcmCtrl::PHASE::Value::TAG => {
self.ghash.update(buffer);
let tag = self.ghash.finalize(&key, &gcm_iv);
self.data_out[0] = u32::from_le_bytes(tag[0..4].try_into().unwrap());
self.data_out[1] = u32::from_le_bytes(tag[4..8].try_into().unwrap());
self.data_out[2] = u32::from_le_bytes(tag[8..12].try_into().unwrap());
self.data_out[3] = u32::from_le_bytes(tag[12..16].try_into().unwrap());
}
_ => {}
}
}
fn mode(&self) -> Ctrl::MODE::Value {
self.ctrl_shadowed
.reg
.read_as_enum(Ctrl::MODE)
.unwrap_or(Ctrl::MODE::Value::NONE)
}
fn write_data_in(&mut self, size: RvSize, idx: usize, val: RvData) -> Result<(), BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.data_in[idx] = val;
self.data_in_written[idx] = true;
// All data_in registers have been written
if self.data_in_written.iter().copied().all(|x| x) {
self.data_in_written = [false; 4];
let mut buffer: Vec<u8> = vec![];
for i in 0..4 {
buffer.extend_from_slice(&self.data_in[i].to_le_bytes()[..]);
}
match self.mode() {
Ctrl::MODE::Value::CBC => {
self.update_cbc(&buffer);
}
Ctrl::MODE::Value::CTR => {
self.update_ctr(&buffer);
}
Ctrl::MODE::Value::GCM => {
self.update_gcm(&buffer);
}
Ctrl::MODE::Value::ECB => {
self.update_ecb(&buffer);
}
_ => todo!(),
}
}
Ok(())
}
fn write_key_share0(&mut self, size: RvSize, idx: usize, val: RvData) -> Result<(), BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.key_share0[idx] = val;
match self.mode() {
Ctrl::MODE::Value::CBC => {
self.cbc = Aes256Cbc::new(&self.iv(), &self.key());
}
Ctrl::MODE::Value::GCM => {
self.ghash = GHash::new(&self.key());
}
_ => (),
}
Ok(())
}
fn write_key_share1(&mut self, size: RvSize, idx: usize, val: RvData) -> Result<(), BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.key_share1[idx] = val;
match self.mode() {
Ctrl::MODE::Value::CBC => {
self.cbc = Aes256Cbc::new(&self.iv(), &self.key());
}
Ctrl::MODE::Value::GCM => {
self.ghash = GHash::new(&self.key());
}
_ => (),
}
Ok(())
}
fn write_iv(&mut self, size: RvSize, idx: usize, val: RvData) -> Result<(), BusError> {
// Writes have to be word-aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.iv[idx] = val;
match self.mode() {
Ctrl::MODE::Value::CBC => {
self.cbc = Aes256Cbc::new(&self.iv(), &self.key());
}
Ctrl::MODE::Value::CTR => {
self.ctr = Aes256Ctr::new(&self.iv(), &self.key());
}
Ctrl::MODE::Value::GCM => {
if idx == 3 {
// hardware quirk: IV[3] is loaded as big-endian, unlike all other registers
self.iv[3] = val.swap_bytes();
if val == 0 {
self.iv[3] = 2;
}
} else {
self.iv[idx] = val;
}
}
_ => todo!(),
}
Ok(())
}
/// Handle incoming events
pub fn incoming_event(&mut self, _event: Rc<Event>) {
// No event handling needed for now
}
/// Register for outgoing events
pub fn register_outgoing_events(&mut self, _sender: mpsc::Sender<Event>) {
// No events to register for now
}
}
#[derive(Clone)]
pub struct Aes {
pub regs: Rc<RefCell<AesRegs>>,
}
impl Aes {
/// Create a new AES peripheral instance
pub fn new(
key_vault_key: Rc<RefCell<Option<[u8; 32]>>>,
key_vault_destination: Rc<RefCell<AesKeyReleaseOp>>,
) -> Self {
Self {
regs: Rc::new(RefCell::new(AesRegs::new(
key_vault_key,
key_vault_destination,
))),
}
}
/// Process a block of data through AES
pub fn process_block(&mut self, data: &[u8; 16]) -> [u8; 16] {
let mut regs = self.regs.borrow_mut();
data.chunks(4).enumerate().for_each(|(i, chunk)| {
let word = u32::from_le_bytes(chunk.try_into().unwrap());
regs.write_data_in(RvSize::Word, i, word).unwrap();
});
let output_bytes: Vec<u8> = (0..4)
.flat_map(|i| {
let word = regs.read_data_out(RvSize::Word, i).unwrap();
word.to_le_bytes()
})
.collect();
output_bytes.try_into().unwrap()
}
/// Handle incoming events
pub fn incoming_event(&mut self, event: Rc<Event>) {
self.regs.borrow_mut().incoming_event(event);
}
/// Register for outgoing events
pub fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
self.regs.borrow_mut().register_outgoing_events(sender);
}
}
impl Bus for Aes {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: caliptra_emu_types::RvAddr) -> Result<RvData, BusError> {
self.regs.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(
&mut self,
size: RvSize,
addr: caliptra_emu_types::RvAddr,
val: RvData,
) -> Result<(), BusError> {
self.regs.borrow_mut().write(size, addr, val)
}
fn poll(&mut self) {
self.regs.borrow_mut().poll();
}
fn warm_reset(&mut self) {
self.regs.borrow_mut().warm_reset();
}
fn update_reset(&mut self) {
self.regs.borrow_mut().update_reset();
}
fn register_outgoing_events(&mut self, sender: mpsc::Sender<caliptra_emu_bus::Event>) {
self.regs.borrow_mut().register_outgoing_events(sender);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/doe.rs | sw-emulator/lib/periph/src/doe.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
doe.rs
Abstract:
File contains Deobfuscation Engine Implementation
--*/
use crate::helpers::bytes_swap_word_endian;
use crate::{KeyVault, SocRegistersInternal};
use caliptra_emu_bus::{
ActionHandle, BusError, Clock, ReadOnlyRegister, ReadWriteMemory, ReadWriteRegister, Timer,
};
use caliptra_emu_crypto::Aes256Cbc;
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use zerocopy::IntoBytes;
/// Initialization vector size
const DOE_IV_SIZE: usize = 16;
/// The number of CPU clock cycles it takes to perform the hash update action.
const DOE_OP_TICKS: u64 = 1000;
// hmac_key_dest_valid | hmac_block_dest_valid
const DOE_KEY_USAGE: u32 = 0x3;
register_bitfields! [
u32,
/// Control Register Fields
Control [
CMD OFFSET(0) NUMBITS(2) [
IDLE = 0b00,
DEOBFUSCATE_UDS = 0b01,
DEOBFUSCATE_FE = 0b10,
CLEAR_SECRETS = 0b11,
],
DEST OFFSET(2) NUMBITS(5) [],
CMD_EXT OFFSET(7) NUMBITS(2) [
DOE_STD = 0b00,
DOE_HEK = 0b01,
DOE_RSVD0 = 0b10,
DOE_RSVD1 = 0b11,
],
],
/// Status Register Fields
Status [
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
UDS_FLOW_DONE OFFSET(2) NUMBITS(1) [],
FE_FLOW_DONE OFFSET(3) NUMBITS(1) [],
DEOBF_SECRETS_CLEARED OFFSET(4) NUMBITS(1) [],
RSVD OFFSET(5) NUMBITS(27) [],
],
];
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct Doe {
/// Initialization Vector
#[peripheral(offset = 0x0000_0000, len = 0x10)]
iv: ReadWriteMemory<DOE_IV_SIZE>,
/// Control Register
#[register(offset = 0x0000_0010, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
#[register(offset = 0x0000_0014)]
status: ReadOnlyRegister<u32, Status::Register>,
/// Timer
timer: Timer,
/// Key Vault
key_vault: KeyVault,
/// SOC Registers
soc_reg: SocRegistersInternal,
/// Operation Complete Action
op_complete_action: Option<ActionHandle>,
}
impl Doe {
/// Create new instance of deobfuscation engine
///
/// # Arguments
///
/// * `clock` - Clock
/// * `key_vault` - Key Vault
/// * `soc-rec` - SOC Registers
///
/// # Returns
///
/// * `Self` - Instance of deobfuscation engine
pub fn new(clock: &Clock, key_vault: KeyVault, soc_reg: SocRegistersInternal) -> Self {
Self {
iv: ReadWriteMemory::new(),
control: ReadWriteRegister::new(0),
status: ReadOnlyRegister::new(Status::READY::SET.value),
timer: Timer::new(clock),
key_vault,
soc_reg,
op_complete_action: None,
}
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.control.reg.set(val);
if self.control.reg.read(Control::CMD) != Control::CMD::IDLE.value
|| self.control.reg.is_set(Control::CMD_EXT)
{
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
self.op_complete_action = Some(self.timer.schedule_poll_in(DOE_OP_TICKS));
}
Ok(())
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
let key_id = self.control.reg.read(Control::DEST);
match self.control.reg.read_as_enum(Control::CMD) {
Some(Control::CMD::Value::DEOBFUSCATE_UDS) => self.unscramble_uds(key_id),
Some(Control::CMD::Value::DEOBFUSCATE_FE) => self.unscramble_fe(key_id),
Some(Control::CMD::Value::CLEAR_SECRETS) => self.clear_secrets(),
_ => {}
}
if let Some(Control::CMD_EXT::Value::DOE_HEK) =
self.control.reg.read_as_enum(Control::CMD_EXT)
{
self.unscramble_hek_seed(key_id)
};
self.status
.reg
.modify(Status::READY::SET + Status::VALID::SET);
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
// TODO: Reset registers
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
// TODO: Reset registers
}
/// Unscramble unique device secret (UDS) and store it in key vault
///
/// # Argument
///
/// * `key_id` - Key index to store the UDS
fn unscramble_uds(&mut self, key_id: u32) {
let cipher_uds = self.soc_reg.uds();
let mut plain_uds = [0u8; 64];
Aes256Cbc::decrypt(
&self.soc_reg.doe_key(),
self.iv.data(),
&cipher_uds,
&mut plain_uds[..cipher_uds.len()],
);
self.key_vault
.write_key(key_id, &bytes_swap_word_endian(&plain_uds), DOE_KEY_USAGE)
.unwrap();
}
/// Unscramble field entropy and store it in key vault
///
/// # Argument
///
/// * `key_id` - Key index to store the field entropy
fn unscramble_fe(&mut self, key_id: u32) {
let mut plain_fe = [0_u8; 32];
let cipher_fe = self.soc_reg.field_entropy();
Aes256Cbc::decrypt(
&self.soc_reg.doe_key(),
self.iv.data(),
&cipher_fe,
&mut plain_fe[..cipher_fe.len()],
);
self.key_vault
.write_key(key_id, &bytes_swap_word_endian(&plain_fe), DOE_KEY_USAGE)
.unwrap();
}
/// Unscramble hek seed and store it in key vault
///
/// # Argument
///
/// * `key_id` - Key index to store the hek seed
fn unscramble_hek_seed(&mut self, key_id: u32) {
let mut plain_hek_seed = [0_u8; 32];
let cipher_hek_seed = self.soc_reg.doe_hek_seed();
Aes256Cbc::decrypt(
&self.soc_reg.doe_key(),
self.iv.data(),
cipher_hek_seed.as_bytes(),
&mut plain_hek_seed[..cipher_hek_seed.len()],
);
self.key_vault
.write_key(
key_id,
&bytes_swap_word_endian(&plain_hek_seed),
DOE_KEY_USAGE,
)
.unwrap();
}
/// Clear secrets
fn clear_secrets(&mut self) {
self.soc_reg.clear_secrets()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CaliptraRootBusArgs, Iccm, KeyUsage, MailboxInternal, MailboxRam, Mci};
use caliptra_api_types::SecurityState;
use caliptra_emu_bus::Bus;
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_types::RvAddr;
use std::rc::Rc;
use tock_registers::registers::InMemoryRegister;
const OFFSET_IV: RvAddr = 0;
const OFFSET_CONTROL: RvAddr = 0x10;
const OFFSET_STATUS: RvAddr = 0x14;
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
#[test]
fn test_deobfuscate_uds() {
let mut iv: [u8; 16] = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f,
];
iv.to_big_endian();
const PLAIN_TEXT_UDS: [u8; 48] = [
0xE2, 0xBE, 0xC1, 0x6B, 0x96, 0x9F, 0x40, 0x2E, 0x11, 0x7E, 0x3D, 0xE9, 0x2A, 0x17,
0x93, 0x73, 0x57, 0x8A, 0x2D, 0xAE, 0x9C, 0xAC, 0x03, 0x1E, 0xAC, 0x6F, 0xB7, 0x9E,
0x51, 0x8E, 0xAF, 0x45, 0x46, 0x1C, 0xC8, 0x30, 0x11, 0xE4, 0x5C, 0xA3, 0x19, 0xC1,
0xFB, 0xE5, 0xEF, 0x52, 0x0A, 0x1A,
];
let clock = Rc::new(Clock::new());
let key_vault = KeyVault::new();
let mci = Mci::new(vec![]);
let soc_reg = SocRegistersInternal::new(
MailboxInternal::new(&clock, MailboxRam::default()),
Iccm::new(&clock),
mci.clone(),
CaliptraRootBusArgs {
clock: clock.clone(),
security_state: *SecurityState::default().set_debug_locked(true),
..CaliptraRootBusArgs::default()
},
);
let mut doe = Doe::new(&clock, key_vault.clone(), soc_reg);
for i in (0..iv.len()).step_by(4) {
assert_eq!(
doe.write(RvSize::Word, OFFSET_IV + i as RvAddr, make_word(i, &iv))
.ok(),
Some(())
);
}
assert_eq!(
doe.write(
RvSize::Word,
OFFSET_CONTROL,
(Control::CMD::DEOBFUSCATE_UDS + Control::DEST.val(2)).value
)
.ok(),
Some(())
);
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
doe.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) {
break;
}
clock.increment_and_process_timer_actions(1, &mut doe);
}
let mut ku_hmac_data = KeyUsage::default();
ku_hmac_data.set_hmac_data(true);
let mut ku_hmac_key = KeyUsage::default();
ku_hmac_key.set_hmac_key(true);
assert_eq!(
key_vault.read_key(2, ku_hmac_data).unwrap()[..48],
PLAIN_TEXT_UDS
);
assert_eq!(
key_vault.read_key(2, ku_hmac_key).unwrap()[..48],
PLAIN_TEXT_UDS
);
}
#[test]
fn test_deobfuscate_fe() {
const PLAIN_TEXT_FE: [u8; 48] = [
0x4D, 0x65, 0x10, 0xC6, 0x53, 0xA8, 0xED, 0xB4, 0xEF, 0x6D, 0x54, 0xCF, 0x5F, 0xC1,
0x4E, 0x52, 0xB2, 0x9A, 0xEF, 0x39, 0xAC, 0x57, 0x12, 0x4B, 0x10, 0x92, 0xAB, 0x30,
0xA0, 0x3E, 0xB1, 0xAD, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
let clock = Rc::new(Clock::new());
let key_vault = KeyVault::new();
let mci = Mci::new(vec![]);
let soc_reg = SocRegistersInternal::new(
MailboxInternal::new(&clock, MailboxRam::default()),
Iccm::new(&clock),
mci.clone(),
CaliptraRootBusArgs {
clock: clock.clone(),
security_state: *SecurityState::default().set_debug_locked(true),
..CaliptraRootBusArgs::default()
},
);
let mut doe = Doe::new(&clock, key_vault.clone(), soc_reg);
let mut iv = [0u8; DOE_IV_SIZE];
iv.to_big_endian();
for i in (0..iv.len()).step_by(4) {
assert_eq!(
doe.write(RvSize::Word, OFFSET_IV + i as RvAddr, make_word(i, &iv))
.ok(),
Some(())
);
}
assert_eq!(
doe.write(
RvSize::Word,
OFFSET_CONTROL,
(Control::CMD::DEOBFUSCATE_FE + Control::DEST.val(3)).value
)
.ok(),
Some(())
);
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
doe.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) {
break;
}
clock.increment_and_process_timer_actions(1, &mut doe);
}
let mut ku_hmac_data = KeyUsage::default();
ku_hmac_data.set_hmac_data(true);
let mut ku_hmac_key = KeyUsage::default();
ku_hmac_key.set_hmac_key(true);
assert_eq!(
key_vault.read_key(3, ku_hmac_data).unwrap()[..48],
PLAIN_TEXT_FE
);
assert_eq!(
key_vault.read_key(3, ku_hmac_key).unwrap()[..48],
PLAIN_TEXT_FE
);
}
#[test]
fn test_deobfuscate_hek_seed() {
const PLAIN_TEXT_HEK_SEED: [u8; 48] = [
0x4D, 0x65, 0x10, 0xC6, 0x53, 0xA8, 0xED, 0xB4, 0xEF, 0x6D, 0x54, 0xCF, 0x5F, 0xC1,
0x4E, 0x52, 0xB2, 0x9A, 0xEF, 0x39, 0xAC, 0x57, 0x12, 0x4B, 0x10, 0x92, 0xAB, 0x30,
0xA0, 0x3E, 0xB1, 0xAD, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
let clock = Rc::new(Clock::new());
let key_vault = KeyVault::new();
let mci = Mci::new(vec![]);
let mut soc_reg = SocRegistersInternal::new(
MailboxInternal::new(&clock, MailboxRam::default()),
Iccm::new(&clock),
mci.clone(),
CaliptraRootBusArgs {
clock: clock.clone(),
security_state: *SecurityState::default().set_debug_locked(true),
..CaliptraRootBusArgs::default()
},
);
soc_reg.set_hek_seed(&[0xFFFF_FFFF; 8]);
let mut doe = Doe::new(&clock, key_vault.clone(), soc_reg);
let mut iv = [0u8; DOE_IV_SIZE];
iv.to_big_endian();
for i in (0..iv.len()).step_by(4) {
assert!(doe
.write(RvSize::Word, OFFSET_IV + i as RvAddr, make_word(i, &iv))
.is_ok());
}
assert!(doe
.write(
RvSize::Word,
OFFSET_CONTROL,
(Control::CMD_EXT::DOE_HEK + Control::DEST.val(3)).value
)
.is_ok());
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
doe.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) {
break;
}
clock.increment_and_process_timer_actions(1, &mut doe);
}
let mut ku_hmac_data = KeyUsage::default();
ku_hmac_data.set_hmac_data(true);
let mut ku_hmac_key = KeyUsage::default();
ku_hmac_key.set_hmac_key(true);
assert_eq!(
key_vault.read_key(3, ku_hmac_data).unwrap()[..48],
PLAIN_TEXT_HEK_SEED
);
assert_eq!(
key_vault.read_key(3, ku_hmac_key).unwrap()[..48],
PLAIN_TEXT_HEK_SEED
);
}
#[test]
fn test_clear_secrets() {
let expected_uds = [0u8; 64];
let expected_doe_key = [0u8; 32];
let expected_fe = [0u8; 32];
let expected_hek_seed = [0u8; 32];
let clock = Rc::new(Clock::new());
let key_vault = KeyVault::new();
let mci = Mci::new(vec![]);
let mut soc_reg = SocRegistersInternal::new(
MailboxInternal::new(&clock, MailboxRam::default()),
Iccm::new(&clock),
mci.clone(),
CaliptraRootBusArgs {
clock: clock.clone(),
security_state: *SecurityState::default().set_debug_locked(true),
..CaliptraRootBusArgs::default()
},
);
soc_reg.set_hek_seed(&[0xABAB_ABAB; 8]);
let mut doe = Doe::new(&clock, key_vault, soc_reg.clone());
assert_ne!(soc_reg.uds(), expected_uds);
assert_ne!(soc_reg.doe_key(), expected_doe_key);
assert_ne!(soc_reg.field_entropy(), expected_fe);
assert_ne!(soc_reg.doe_hek_seed(), expected_hek_seed);
assert_eq!(
doe.write(
RvSize::Word,
OFFSET_CONTROL,
(Control::CMD::CLEAR_SECRETS + Control::DEST.val(0)).value
)
.ok(),
Some(())
);
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
doe.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) {
break;
}
clock.increment_and_process_timer_actions(1, &mut doe);
}
assert_eq!(soc_reg.uds(), expected_uds);
assert_eq!(soc_reg.doe_key(), expected_doe_key);
assert_eq!(soc_reg.field_entropy(), expected_fe);
assert_eq!(soc_reg.doe_hek_seed(), expected_hek_seed);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/hash_sha256.rs | sw-emulator/lib/periph/src/hash_sha256.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
hash_sha256.rs
Abstract:
File contains SHA256 peripheral implementation.
--*/
use caliptra_emu_bus::{
ActionHandle, BusError, Clock, ReadOnlyMemory, ReadOnlyRegister, ReadWriteMemory,
ReadWriteRegister, Timer,
};
use caliptra_emu_crypto::{EndianessTransform, Sha256, Sha256Mode};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
// Register bitfields for the SHA256 peripheral
register_bitfields! [
u32,
/// Control Register Fields
Control [
INIT OFFSET(0) NUMBITS(1) [],
NEXT OFFSET(1) NUMBITS(1) [],
MODE OFFSET(2) NUMBITS(1) [
SHA256_224 = 0b00,
SHA256 = 0b01,
],
ZEROIZE OFFSET(3) NUMBITS(1) [],
WNTZ_MODE OFFSET(4) NUMBITS(1) [],
WNTZ_W OFFSET(5)NUMBITS(4) [],
WNTZ_N_MODE OFFSET(9) NUMBITS(1) [],
RSVD OFFSET(10) NUMBITS(22) [],
],
/// Status Register Fields
Status[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
WNTZ_BUSY OFFSET(2) NUMBITS(1) [],
],
];
const SHA256_BLOCK_SIZE: usize = 64;
const SHA256_HASH_SIZE: usize = 32;
/// The number of CPU clock cycles it takes to perform initialization action.
const INIT_TICKS: u64 = 1000;
/// The number of CPU clock cycles it takes to perform the hash update action.
const UPDATE_TICKS: u64 = 1000;
/// SHA-256 Peripheral
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct HashSha256 {
/// Name 0 register
#[register(offset = 0x0000_0000)]
name0: ReadOnlyRegister<u32>,
/// Name 1 register
#[register(offset = 0x0000_0004)]
name1: ReadOnlyRegister<u32>,
/// Version 0 register
#[register(offset = 0x0000_0008)]
version0: ReadOnlyRegister<u32>,
/// Version 1 register
#[register(offset = 0x0000_000C)]
version1: ReadOnlyRegister<u32>,
/// Control register
#[register(offset = 0x0000_0010, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
/// Status register
#[register(offset = 0x0000_0018)]
status: ReadOnlyRegister<u32, Status::Register>,
/// SHA256 Block Memory
#[peripheral(offset = 0x0000_0080, len = 0x40)]
block: ReadWriteMemory<SHA256_BLOCK_SIZE>,
/// SHA256 Hash Memory
#[peripheral(offset = 0x0000_0100, len = 0x20)]
hash: ReadOnlyMemory<SHA256_HASH_SIZE>,
/// SHA256 engine
sha256: Sha256,
timer: Timer,
op_complete_action: Option<ActionHandle>,
}
#[derive(Debug)]
pub struct WntzParams {
/// Enable/disable winterniz accel mode.
wntz_mode: bool,
/// Winterniz w value.
wntz_w: u32,
/// Winternitz n value(SHA192/SHA256 --> n = 24/32)
wntz_n_mode: bool,
init: bool,
}
#[derive(Debug, Eq, PartialEq)]
pub enum WntzError {
WntzDisabled,
WntzParamInvalid,
}
impl HashSha256 {
/// NAME0 Register Value
const NAME0_VAL: RvData = 0x363532; // 256
/// NAME1 Register Value
const NAME1_VAL: RvData = 0x32616873; // sha2
/// VERSION0 Register Value
const VERSION0_VAL: RvData = 0x30302E31; // 1.0
/// VERSION1 Register Value
const VERSION1_VAL: RvData = 0x00000000;
const WNTZ_ACCEL_COEFF_OFFSET: usize = 22;
/// Create a new instance of SHA-512 Engine
pub fn new(clock: &Clock) -> Self {
Self {
sha256: Sha256::new(Sha256Mode::Sha256), // Default SHA256 mode
name0: ReadOnlyRegister::new(Self::NAME0_VAL),
name1: ReadOnlyRegister::new(Self::NAME1_VAL),
version0: ReadOnlyRegister::new(Self::VERSION0_VAL),
version1: ReadOnlyRegister::new(Self::VERSION1_VAL),
control: ReadWriteRegister::new(0),
status: ReadOnlyRegister::new(Status::READY::SET.value),
block: ReadWriteMemory::new(),
hash: ReadOnlyMemory::new(),
timer: Timer::new(clock),
op_complete_action: None,
}
}
pub fn hash_block(&mut self, block: &[u8; 64]) -> Result<(), BusError> {
if self.control.reg.is_set(Control::INIT) || self.control.reg.is_set(Control::NEXT) {
// Reset the Ready and Valid status bits
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
if self.control.reg.is_set(Control::INIT) {
// Initialize the SHA512 engine with the mode.
let mut mode = Sha256Mode::Sha256;
let modebits = self.control.reg.read(Control::MODE);
match modebits {
0 => {
mode = Sha256Mode::Sha224;
}
1 => {
mode = Sha256Mode::Sha256;
}
_ => Err(BusError::StoreAccessFault)?,
}
self.sha256.reset(mode);
// Update the SHA256 engine with a new block
self.sha256.update(block);
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(INIT_TICKS));
} else if self.control.reg.is_set(Control::NEXT) {
// Update the SHA512 engine with a new block
self.sha256.update(self.block.data());
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(UPDATE_TICKS));
}
}
Ok(())
}
pub fn is_wntz_enabled(&self) -> Result<WntzParams, WntzError> {
let params = WntzParams {
wntz_mode: self.control.reg.is_set(Control::WNTZ_MODE),
wntz_w: self.control.reg.read(Control::WNTZ_W),
wntz_n_mode: self.control.reg.is_set(Control::WNTZ_N_MODE),
init: self.control.reg.is_set(Control::INIT),
};
if params.wntz_mode && params.init {
match params.wntz_w {
1 | 2 | 4 | 8 => (),
_ => return Err(WntzError::WntzParamInvalid),
}
return Ok(params);
}
Err(WntzError::WntzDisabled)
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.control.reg.set(val);
// If WNTZ_MODE is set and first is set, then enable winternitz
if let Ok(params) = self.is_wntz_enabled() {
// Initialize winternitz iteration count
let iter_count = (1 << params.wntz_w) - 1;
let mut block = [0u8; 64];
block.clone_from(self.block.data());
block.to_big_endian();
let coeff = block[Self::WNTZ_ACCEL_COEFF_OFFSET] as u16;
let mut mode = Sha256Mode::Sha256;
let modebits = self.control.reg.read(Control::MODE);
match modebits {
0 => {
mode = Sha256Mode::Sha224;
}
1 => {
mode = Sha256Mode::Sha256;
}
_ => Err(BusError::StoreAccessFault)?,
}
for j in coeff..iter_count {
// Update the SHA256 engine with a new block
if j == coeff {
// Reset the Ready and Valid status bits
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
self.sha256.reset(mode);
self.sha256.update(self.block.data());
} else {
block[Self::WNTZ_ACCEL_COEFF_OFFSET] = j as u8;
let hash_len = if params.wntz_n_mode { 32 } else { 24 };
let mut digest = [0u8; SHA256_HASH_SIZE];
self.sha256.hash(&mut digest);
digest.to_big_endian();
block[23..23 + hash_len].copy_from_slice(&digest[..hash_len]);
block.to_little_endian();
self.sha256.reset(mode);
self.sha256.update(&block);
block.to_big_endian();
}
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(INIT_TICKS));
}
} else {
let mut block = [0; 64];
block.clone_from(self.block.data());
self.hash_block(&block)?;
}
if self.control.reg.is_set(Control::ZEROIZE) {
self.zeroize();
}
Ok(())
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
// Retrieve the hash
self.sha256.hash(self.hash.data_mut());
// Update Ready and Valid status bits
self.status
.reg
.modify(Status::READY::SET + Status::VALID::SET);
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
// TODO: Reset registers
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
// TODO: Reset registers
}
pub fn hash(&self) -> &[u8] {
&self.hash.data()[..self.sha256.hash_len()]
}
fn zeroize(&mut self) {
self.block.data_mut().fill(0);
self.hash.data_mut().fill(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use caliptra_emu_bus::Bus;
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_types::RvAddr;
use tock_registers::registers::InMemoryRegister;
const OFFSET_NAME0: RvAddr = 0x0;
const OFFSET_NAME1: RvAddr = 0x4;
const OFFSET_VERSION0: RvAddr = 0x8;
const OFFSET_VERSION1: RvAddr = 0xC;
const OFFSET_CONTROL: RvAddr = 0x10;
const OFFSET_STATUS: RvAddr = 0x18;
const OFFSET_BLOCK: RvAddr = 0x80;
const OFFSET_HASH: RvAddr = 0x100;
#[test]
fn test_name_read() {
let mut sha256 = HashSha256::new(&Clock::new());
let name0 = sha256.read(RvSize::Word, OFFSET_NAME0).unwrap();
let mut name0 = String::from_utf8_lossy(&name0.to_le_bytes()).to_string();
name0.pop();
assert_eq!(name0, "256");
let name1 = sha256.read(RvSize::Word, OFFSET_NAME1).unwrap();
let name1 = String::from_utf8_lossy(&name1.to_le_bytes()).to_string();
assert_eq!(name1, "sha2");
}
#[test]
fn test_version_read() {
let mut sha256 = HashSha256::new(&Clock::new());
let version0 = sha256.read(RvSize::Word, OFFSET_VERSION0).unwrap();
let version0 = String::from_utf8_lossy(&version0.to_le_bytes()).to_string();
assert_eq!(version0, "1.00");
let version1 = sha256.read(RvSize::Word, OFFSET_VERSION1).unwrap();
let version1 = String::from_utf8_lossy(&version1.to_le_bytes()).to_string();
assert_eq!(version1, "\0\0\0\0");
}
#[test]
fn test_control_read() {
let mut sha256 = HashSha256::new(&Clock::new());
assert_eq!(sha256.read(RvSize::Word, OFFSET_CONTROL).unwrap(), 0);
}
#[test]
fn test_status_read() {
let mut sha256 = HashSha256::new(&Clock::new());
assert_eq!(sha256.read(RvSize::Word, OFFSET_STATUS).unwrap(), 1);
}
#[test]
fn test_block_read_write() {
let mut sha256 = HashSha256::new(&Clock::new());
for addr in (OFFSET_BLOCK..(OFFSET_BLOCK + SHA256_BLOCK_SIZE as u32)).step_by(4) {
assert_eq!(sha256.write(RvSize::Word, addr, u32::MAX).ok(), Some(()));
assert_eq!(sha256.read(RvSize::Word, addr).ok(), Some(u32::MAX));
}
}
#[test]
fn test_hash_read_write() {
let mut sha256 = HashSha256::new(&Clock::new());
for addr in (OFFSET_HASH..(OFFSET_HASH + SHA256_HASH_SIZE as u32)).step_by(4) {
assert_eq!(sha256.read(RvSize::Word, addr).ok(), Some(0));
assert_eq!(
sha256.write(RvSize::Word, addr, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
}
fn test_sha(data: &[u8], expected: &[u8], mode: Sha256Mode) {
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
// Compute the total bytes and total blocks required for the final message.
let totalblocks = ((data.len() + 8) + SHA256_BLOCK_SIZE) / SHA256_BLOCK_SIZE;
let totalbytes = totalblocks * SHA256_BLOCK_SIZE;
let mut block_arr = vec![0; totalbytes];
block_arr[..data.len()].copy_from_slice(data);
block_arr[data.len()] = 1 << 7;
let len: u64 = data.len() as u64;
let len = len * 8;
block_arr[totalbytes - 8..].copy_from_slice(&len.to_be_bytes());
block_arr.to_big_endian();
let clock = Clock::new();
let mut sha256 = HashSha256::new(&clock);
// Process each block via the SHA engine.
for idx in 0..totalblocks {
for i in (0..SHA256_BLOCK_SIZE).step_by(4) {
assert_eq!(
sha256
.write(
RvSize::Word,
OFFSET_BLOCK + i as RvAddr,
make_word((idx * SHA256_BLOCK_SIZE) + i, &block_arr)
)
.ok(),
Some(())
);
}
if idx == 0 {
let modebits = match mode {
Sha256Mode::Sha224 => 0,
Sha256Mode::Sha256 => 1,
};
let control: ReadWriteRegister<u32, Control::Register> = ReadWriteRegister::new(0);
control.reg.modify(Control::MODE.val(modebits));
control.reg.modify(Control::INIT::SET);
assert_eq!(
sha256
.write(RvSize::Word, OFFSET_CONTROL, control.reg.get())
.ok(),
Some(())
);
} else {
assert_eq!(
sha256
.write(RvSize::Word, OFFSET_CONTROL, Control::NEXT::SET.into())
.ok(),
Some(())
);
}
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
sha256.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) && status.is_set(Status::READY) {
break;
}
clock.increment_and_process_timer_actions(1, &mut sha256);
}
}
let mut hash_le: [u8; 32] = [0; 32];
hash_le[..sha256.hash().len()].clone_from_slice(sha256.hash());
hash_le.to_little_endian();
assert_eq!(&hash_le[0..sha256.hash().len()], expected);
}
#[rustfmt::skip]
const SHA_256_TEST_BLOCK: [u8; 3] = [
0x61, 0x62, 0x63
];
#[rustfmt::skip]
const SHA_256_ACC_TEST_BLOCK: [u8; 64] = [
0xF6, 0x4F, 0xF1, 0xD2, 0x64, 0xF9, 0x6A, 0x34, 0x6C, 0x7D, 0x9F, 0x56, 0xB6, 0xA1, 0x80,
0xB8, 0x0A, 0x00, 0x00, 0x00, 0x95, 0xC5, 0x00, 0x00, 0x89, 0x5B, 0xE0, 0xCA, 0xFD, 0xDF,
0x35, 0x9E, 0x70, 0x54, 0x70, 0x71, 0x8E, 0x98, 0x09, 0x62, 0x37, 0x6E, 0xDF, 0xBF, 0xC3,
0xB5, 0x0B, 0x96, 0xE8, 0x57, 0x76, 0x8D, 0x80, 0xEF, 0xFE, 0xBF, 0x00, 0x00, 0x00, 0x00,
0xB8, 0x01, 0x00, 0x00,
];
#[test]
fn test_sha256_224() {
#[rustfmt::skip]
let expected: [u8; 28] = [
0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8, 0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2, 0x55, 0xb3,
0x2a, 0xad, 0xbc, 0xe4, 0xbd, 0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7,
];
test_sha(&SHA_256_TEST_BLOCK, &expected, Sha256Mode::Sha224);
}
#[test]
fn test_sha256_256() {
#[rustfmt::skip]
let expected: [u8; 32] = [
0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x1, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23,
0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x0, 0x15, 0xAD,
];
test_sha(&SHA_256_TEST_BLOCK, &expected, Sha256Mode::Sha256);
}
#[test]
fn test_sha256_multi_block() {
const SHA_256_TEST_MULTI_BLOCK: [u8; 130] = [
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E,
0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64,
0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74,
0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,
0x77, 0x78, 0x79, 0x7A,
];
let expected: [u8; 32] = [
0x06, 0xF9, 0xB1, 0xA7, 0xAC, 0x97, 0xBC, 0x8E, 0x6A, 0x83, 0x5C, 0x08, 0x98, 0x6F,
0xE5, 0x38, 0xF0, 0x47, 0x8B, 0x03, 0x82, 0x6E, 0xFB, 0x4E, 0xED, 0x35, 0xDC, 0x51,
0x7B, 0x43, 0x3B, 0x8A,
];
test_sha(&SHA_256_TEST_MULTI_BLOCK, &expected, Sha256Mode::Sha256);
}
#[test]
fn test_wntz_params() {
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
let clock = Clock::new();
let mut sha256 = HashSha256::new(&clock);
for i in (0..SHA256_BLOCK_SIZE).step_by(4) {
assert_eq!(
sha256
.write(
RvSize::Word,
OFFSET_BLOCK + i as RvAddr,
make_word(i, &SHA_256_ACC_TEST_BLOCK)
)
.ok(),
Some(())
);
}
let control: ReadWriteRegister<u32, Control::Register> = ReadWriteRegister::new(0);
control.reg.modify(Control::INIT::SET);
control.reg.modify(Control::WNTZ_MODE::SET);
control.reg.modify(Control::WNTZ_W.val(8));
control.reg.modify(Control::WNTZ_N_MODE::SET);
control.reg.modify(Control::MODE.val(1));
sha256
.write(RvSize::Word, OFFSET_CONTROL, control.reg.get())
.unwrap();
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
sha256.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) && status.is_set(Status::READY) {
break;
}
clock.increment_and_process_timer_actions(1, &mut sha256);
}
let mut hash_be: [u8; 32] = [0; 32];
hash_be[..sha256.hash().len()].clone_from_slice(sha256.hash());
const EXPECTED: [u8; 32] = [
0xDA, 0xC8, 0x0B, 0x84, 0x56, 0x3A, 0x75, 0x0B, 0x46, 0x14, 0x11, 0x7A, 0xAD, 0xCC,
0xB3, 0x47, 0x72, 0x0C, 0x0D, 0xB1, 0x1B, 0xA1, 0xE2, 0x39, 0xF9, 0x17, 0x93, 0x52,
0x90, 0x20, 0xF6, 0xF8,
];
assert_eq!(&hash_be[0..sha256.hash().len()], EXPECTED);
}
#[test]
fn test_wntz_mode_disabled_by_default() {
let sha256 = HashSha256::new(&Clock::new());
let err = sha256.is_wntz_enabled().unwrap_err();
assert_eq!(err, WntzError::WntzDisabled);
}
#[test]
fn test_wntz_mode_disabled_if_init_not_set() {
let mut sha256 = HashSha256::new(&Clock::new());
let control: ReadWriteRegister<u32, Control::Register> = ReadWriteRegister::new(0);
control.reg.modify(Control::WNTZ_MODE::SET);
control.reg.modify(Control::WNTZ_W.val(8));
control.reg.modify(Control::WNTZ_N_MODE::SET);
control.reg.modify(Control::MODE.val(1));
sha256
.write(RvSize::Word, OFFSET_CONTROL, control.reg.get())
.unwrap();
let err = sha256.is_wntz_enabled().unwrap_err();
assert_eq!(err, WntzError::WntzDisabled);
}
#[test]
fn test_wntz_error_if_w_is_not_valid() {
let mut sha256 = HashSha256::new(&Clock::new());
let control: ReadWriteRegister<u32, Control::Register> = ReadWriteRegister::new(0);
control.reg.modify(Control::INIT::SET);
control.reg.modify(Control::WNTZ_MODE::SET);
control.reg.modify(Control::WNTZ_W.val(7));
control.reg.modify(Control::WNTZ_N_MODE::SET);
control.reg.modify(Control::MODE.val(1));
sha256
.write(RvSize::Word, OFFSET_CONTROL, control.reg.get())
.unwrap();
let err = sha256.is_wntz_enabled().unwrap_err();
assert_eq!(err, WntzError::WntzParamInvalid);
}
#[test]
fn test_wntz_is_enabled() {
let mut sha256 = HashSha256::new(&Clock::new());
let control: ReadWriteRegister<u32, Control::Register> = ReadWriteRegister::new(0);
control.reg.modify(Control::INIT::SET);
control.reg.modify(Control::WNTZ_MODE::SET);
control.reg.modify(Control::WNTZ_W.val(8));
control.reg.modify(Control::WNTZ_N_MODE::SET);
control.reg.modify(Control::MODE.val(1));
sha256
.write(RvSize::Word, OFFSET_CONTROL, control.reg.get())
.unwrap();
assert!(sha256.is_wntz_enabled().is_ok());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/asym_ecc384.rs | sw-emulator/lib/periph/src/asym_ecc384.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
asym_ecc384.rs
Abstract:
File contains ECC384 peripheral implementation.
--*/
use crate::helpers::{bytes_from_words_le, words_from_bytes_le};
use crate::{HashSha512, KeyUsage, KeyVault};
use caliptra_emu_bus::{ActionHandle, BusError, Clock, ReadOnlyRegister, ReadWriteRegister, Timer};
use caliptra_emu_crypto::{Ecc384, Ecc384PubKey, Ecc384Signature};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use tock_registers::registers::InMemoryRegister;
/// ECC-384 Key Generation seed
const ECC384_SEED_SIZE: usize = 48;
/// ECC-384 Coordinate size
const ECC384_COORD_SIZE: usize = 48;
/// ECC384 Initialization Vector size
const ECC384_IV_SIZE: usize = 48;
/// ECC384 Nonce size
const ECC384_NONCE_SIZE: usize = 48;
/// The number of CPU clock cycles it takes to perform ECC operation
const ECC384_OP_TICKS: u64 = 1000;
/// The number of CPU clock cycles read and write keys from key vault
const KEY_RW_TICKS: u64 = 100;
register_bitfields! [
u32,
/// Control Register Fields
Control [
CTRL OFFSET(0) NUMBITS(2) [
IDLE = 0b00,
GEN_KEY = 0b01,
SIGN = 0b10,
VERIFY = 0b11,
],
ZEROIZE OFFSET(2) NUMBITS(1) [],
PCR_SIGN OFFSET(3) NUMBITS(1) [],
DH_SHAREDKEY OFFSET(4) NUMBITS(1) [],
],
/// Status Register Fields
Status[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// Key Control Register Fields
KeyReadControl[
KEY_READ_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
PCR_HASH_EXTEND OFFSET(6) NUMBITS(1) [],
RSVD OFFSET(7) NUMBITS(25) [],
],
/// Key Status Register Fields
KeyReadStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
KV_SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL= 2,
],
RSVD OFFSET(10) NUMBITS(22) [],
],
/// Private Key Write Control Register Fields
KeyWriteControl[
KEY_WRITE_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
USAGE OFFSET(6) NUMBITS(6) [],
RSVD OFFSET(12) NUMBITS(20) [],
],
// Tag Status Register Fields
KeyWriteStatus[
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
KV_SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL= 2,
],
RSVD OFFSET(10) NUMBITS(22) [],
],
];
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct AsymEcc384 {
/// Name 0 register
#[register(offset = 0x0000_0000)]
name0: ReadOnlyRegister<u32>,
/// Name 1 register
#[register(offset = 0x0000_0004)]
name1: ReadOnlyRegister<u32>,
/// Version 0 register
#[register(offset = 0x0000_0008)]
version0: ReadOnlyRegister<u32>,
/// Version 1 register
#[register(offset = 0x0000_000C)]
version1: ReadOnlyRegister<u32>,
/// Control register
#[register(offset = 0x0000_0010, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
/// Status register
#[register(offset = 0x0000_0018)]
status: ReadOnlyRegister<u32, Status::Register>,
/// Side Channel Attack Counter measure configuration registers
#[register(offset = 0x0000_0020)]
sca_cfg: ReadWriteRegister<u32, Status::Register>,
/// Seed size
#[register_array(offset = 0x0000_0080)]
seed: [u32; ECC384_SEED_SIZE / 4],
/// Hash size
#[register_array(offset = 0x0000_0100)]
hash: [u32; ECC384_SEED_SIZE / 4],
/// Private Key Out
#[register_array(offset = 0x0000_0180, write_fn = write_access_fault)]
priv_key_out: [u32; ECC384_COORD_SIZE / 4],
/// Private Key In
#[register_array(offset = 0x0000_0580, item_size = 4, len = 12, read_fn = read_access_fault, write_fn = write_priv_key_in)]
priv_key_in: [u32; ECC384_COORD_SIZE / 4],
/// Public Key X coordinate
#[register_array(offset = 0x0000_0200)]
pub_key_x: [u32; ECC384_COORD_SIZE / 4],
/// Public Key Y coordinate
#[register_array(offset = 0x0000_0280)]
pub_key_y: [u32; ECC384_COORD_SIZE / 4],
/// Signature R coordinate
#[register_array(offset = 0x0000_0300)]
sig_r: [u32; ECC384_COORD_SIZE / 4],
/// Signature S coordinate
#[register_array(offset = 0x0000_0380)]
sig_s: [u32; ECC384_COORD_SIZE / 4],
/// Verify R coordinate
#[register_array(offset = 0x0000_0400, write_fn = write_access_fault)]
verify_r: [u32; ECC384_COORD_SIZE / 4],
/// Initialization vector for blinding and counter measures
#[register_array(offset = 0x0000_0480)]
iv: [u32; ECC384_IV_SIZE / 4],
/// Nonce for blinding and counter measures
#[register_array(offset = 0x0000_0500)]
nonce: [u32; ECC384_NONCE_SIZE / 4],
/// DH Shared Key
#[register_array(offset = 0x0000_05C0, write_fn = write_access_fault)]
dh_shared_key: [u32; ECC384_COORD_SIZE / 4],
/// Key Read Control Register
#[register(offset = 0x0000_0600, write_fn = on_write_key_read_control)]
key_read_ctrl: ReadWriteRegister<u32, KeyReadControl::Register>,
/// Key Read Status Register
#[register(offset = 0x0000_0604)]
key_read_status: ReadOnlyRegister<u32, KeyReadStatus::Register>,
/// Seed Read Control Register
#[register(offset = 0x0000_0608, write_fn = on_write_seed_read_control)]
seed_read_ctrl: ReadWriteRegister<u32, KeyReadControl::Register>,
/// Seed Read Status Register
#[register(offset = 0x0000_060c)]
seed_read_status: ReadOnlyRegister<u32, KeyReadStatus::Register>,
/// Key Write Control Register
#[register(offset = 0x0000_0610, write_fn = on_write_key_write_control)]
key_write_ctrl: ReadWriteRegister<u32, KeyWriteControl::Register>,
/// Key Write Status Register
#[register(offset = 0x0000_0614)]
key_write_status: ReadOnlyRegister<u32, KeyWriteStatus::Register>,
/// Error Global Intr register
#[register(offset = 0x0000_080c)]
error_global_intr: ReadOnlyRegister<u32>,
/// Error Internal Intr register
#[register(offset = 0x0000_0814)]
error_internal_intr: ReadOnlyRegister<u32>,
/// Tracks whether priv_key_in was set internally
priv_key_in_set_internally: bool,
/// Key Vault
key_vault: KeyVault,
hash_sha512: HashSha512,
/// Timer
timer: Timer,
/// Operation complete callback
op_complete_action: Option<ActionHandle>,
/// Key read complete action
op_key_read_complete_action: Option<ActionHandle>,
/// Seed read complete action
op_seed_read_complete_action: Option<ActionHandle>,
/// Key write complete action
op_key_write_complete_action: Option<ActionHandle>,
}
impl AsymEcc384 {
/// NAME0 Register Value
const NAME0_VAL: RvData = 0x73656370; //0x63737065; // secp
/// NAME1 Register Value
const NAME1_VAL: RvData = 0x2D333834; // -384
/// VERSION0 Register Value
const VERSION0_VAL: RvData = 0x30302E31; // 1.0
/// VERSION1 Register Value
const VERSION1_VAL: RvData = 0x00000000;
/// Create a new instance of ECC-384 Engine
pub fn new(clock: &Clock, key_vault: KeyVault, hash_sha512: HashSha512) -> Self {
Self {
name0: ReadOnlyRegister::new(Self::NAME0_VAL),
name1: ReadOnlyRegister::new(Self::NAME1_VAL),
version0: ReadOnlyRegister::new(Self::VERSION0_VAL),
version1: ReadOnlyRegister::new(Self::VERSION1_VAL),
control: ReadWriteRegister::new(0),
status: ReadOnlyRegister::new(Status::READY::SET.value),
sca_cfg: ReadWriteRegister::new(0),
seed: Default::default(),
hash: Default::default(),
priv_key_in: Default::default(),
priv_key_out: Default::default(),
pub_key_x: Default::default(),
pub_key_y: Default::default(),
sig_r: Default::default(),
sig_s: Default::default(),
verify_r: Default::default(),
iv: Default::default(),
nonce: Default::default(),
dh_shared_key: Default::default(),
key_read_ctrl: ReadWriteRegister::new(0),
key_read_status: ReadOnlyRegister::new(KeyReadStatus::READY::SET.value),
seed_read_ctrl: ReadWriteRegister::new(0),
seed_read_status: ReadOnlyRegister::new(KeyReadStatus::READY::SET.value),
key_write_ctrl: ReadWriteRegister::new(0),
key_write_status: ReadOnlyRegister::new(KeyWriteStatus::READY::SET.value),
key_vault,
hash_sha512,
timer: Timer::new(clock),
op_complete_action: None,
op_key_read_complete_action: None,
op_seed_read_complete_action: None,
op_key_write_complete_action: None,
error_global_intr: ReadOnlyRegister::new(0),
error_internal_intr: ReadOnlyRegister::new(0),
priv_key_in_set_internally: false,
}
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.control.reg.set(val);
match self.control.reg.read_as_enum(Control::CTRL) {
Some(Control::CTRL::Value::GEN_KEY)
| Some(Control::CTRL::Value::SIGN)
| Some(Control::CTRL::Value::VERIFY) => {
// Reset the Ready and Valid status bits
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
self.op_complete_action = Some(self.timer.schedule_poll_in(ECC384_OP_TICKS));
}
_ => {}
}
if self.control.reg.is_set(Control::DH_SHAREDKEY) {
// Reset the Ready and Valid status bits
self.status
.reg
.modify(Status::READY::CLEAR + Status::VALID::CLEAR);
self.op_complete_action = Some(self.timer.schedule_poll_in(ECC384_OP_TICKS));
}
if self.control.reg.is_set(Control::ZEROIZE) {
self.zeroize();
}
Ok(())
}
/// On Write callback for `key_read_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_key_read_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the key control register
let key_read_ctrl = InMemoryRegister::<u32, KeyReadControl::Register>::new(val);
self.key_read_ctrl.reg.modify(
KeyReadControl::KEY_READ_EN.val(key_read_ctrl.read(KeyReadControl::KEY_READ_EN))
+ KeyReadControl::KEY_ID.val(key_read_ctrl.read(KeyReadControl::KEY_ID)),
);
if key_read_ctrl.is_set(KeyReadControl::KEY_READ_EN) {
self.key_read_status.reg.modify(
KeyReadStatus::READY::CLEAR
+ KeyReadStatus::VALID::CLEAR
+ KeyReadStatus::ERROR::CLEAR,
);
self.op_key_read_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
/// On Write callback for `seed_read_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_seed_read_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the key control register
let seed_ctrl = InMemoryRegister::<u32, KeyReadControl::Register>::new(val);
self.seed_read_ctrl.reg.modify(
KeyReadControl::KEY_READ_EN.val(seed_ctrl.read(KeyReadControl::KEY_READ_EN))
+ KeyReadControl::KEY_ID.val(seed_ctrl.read(KeyReadControl::KEY_ID)),
);
if seed_ctrl.is_set(KeyReadControl::KEY_READ_EN) {
self.seed_read_status.reg.modify(
KeyReadStatus::READY::CLEAR
+ KeyReadStatus::VALID::CLEAR
+ KeyReadStatus::ERROR::CLEAR,
);
self.op_seed_read_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
/// On Write callback for `key_write_control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_key_write_control(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the Tag control register
let key_write_ctrl = InMemoryRegister::<u32, KeyWriteControl::Register>::new(val);
self.key_write_ctrl.reg.modify(
KeyWriteControl::KEY_WRITE_EN.val(key_write_ctrl.read(KeyWriteControl::KEY_WRITE_EN))
+ KeyWriteControl::KEY_ID.val(key_write_ctrl.read(KeyWriteControl::KEY_ID))
+ KeyWriteControl::USAGE.val(key_write_ctrl.read(KeyWriteControl::USAGE)),
);
Ok(())
}
fn read_access_fault(&self, _size: RvSize, _index: usize) -> Result<RvData, BusError> {
Err(BusError::LoadAccessFault)
}
fn write_access_fault(
&self,
_size: RvSize,
_index: usize,
_val: RvData,
) -> Result<(), BusError> {
Err(BusError::StoreAccessFault)
}
/// Custom write handler for priv_key_in register
pub fn write_priv_key_in(
&mut self,
size: RvSize,
index: usize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Reset the internal flag when written directly
self.priv_key_in_set_internally = false;
// Update the register value
if index < self.priv_key_in.len() {
self.priv_key_in[index] = val;
Ok(())
} else {
Err(BusError::StoreAccessFault)
}
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
self.op_complete();
} else if self.timer.fired(&mut self.op_key_read_complete_action) {
self.key_read_complete();
} else if self.timer.fired(&mut self.op_seed_read_complete_action) {
self.seed_read_complete();
} else if self.timer.fired(&mut self.op_key_write_complete_action) {
self.key_write_complete();
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
// TODO: Reset registers
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
// TODO: Reset registers
}
fn op_complete(&mut self) {
match self.control.reg.read_as_enum(Control::CTRL) {
Some(Control::CTRL::Value::GEN_KEY) => self.gen_key(),
Some(Control::CTRL::Value::SIGN) => {
if self.control.reg.is_set(Control::PCR_SIGN) {
self.pcr_digest_sign();
} else {
self.sign();
}
}
Some(Control::CTRL::Value::VERIFY) => self.verify(),
_ => {}
}
if self.control.reg.is_set(Control::DH_SHAREDKEY) {
self.generate_dh_shared_key();
}
self.status
.reg
.modify(Status::READY::SET + Status::VALID::SET);
}
fn key_read_complete(&mut self) {
let key_id = self.key_read_ctrl.reg.read(KeyReadControl::KEY_ID);
let mut key_usage = KeyUsage::default();
key_usage.set_ecc_private_key(true);
let result = self.key_vault.read_key(key_id, key_usage);
let (key_read_result, key) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => (KeyReadStatus::ERROR::KV_READ_FAIL.value, None),
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(KeyReadStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => (
KeyReadStatus::ERROR::KV_SUCCESS.value,
Some(result.unwrap()),
),
};
if let Some(key) = key {
self.priv_key_in = words_from_bytes_le(
&<[u8; ECC384_COORD_SIZE]>::try_from(&key[..ECC384_COORD_SIZE]).unwrap(),
);
self.priv_key_in_set_internally = true;
}
self.key_read_status.reg.modify(
KeyReadStatus::READY::SET
+ KeyReadStatus::VALID::SET
+ KeyReadStatus::ERROR.val(key_read_result),
);
}
fn seed_read_complete(&mut self) {
let key_id = self.seed_read_ctrl.reg.read(KeyReadControl::KEY_ID);
let mut key_usage = KeyUsage::default();
key_usage.set_ecc_key_gen_seed(true);
let result = self.key_vault.read_key(key_id, key_usage);
let (seed_read_result, seed) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => (KeyReadStatus::ERROR::KV_READ_FAIL.value, None),
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(KeyReadStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => (
KeyReadStatus::ERROR::KV_SUCCESS.value,
Some(result.unwrap()),
),
};
if let Some(seed) = seed {
self.seed = words_from_bytes_le(
&<[u8; ECC384_SEED_SIZE]>::try_from(&seed[..ECC384_SEED_SIZE]).unwrap(),
);
}
self.seed_read_status.reg.modify(
KeyReadStatus::READY::SET
+ KeyReadStatus::VALID::SET
+ KeyReadStatus::ERROR.val(seed_read_result),
);
}
fn key_write_complete(&mut self) {
let key_id = self.key_write_ctrl.reg.read(KeyWriteControl::KEY_ID);
// Store the key in the key-vault.
let key_write_result = match self
.key_vault
.write_key(
key_id,
&bytes_from_words_le(&self.priv_key_in),
self.key_write_ctrl.reg.read(KeyWriteControl::USAGE),
)
.err()
{
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => KeyWriteStatus::ERROR::KV_READ_FAIL.value,
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
KeyWriteStatus::ERROR::KV_WRITE_FAIL.value
}
None => KeyWriteStatus::ERROR::KV_SUCCESS.value,
};
// Reset the internal flag
self.priv_key_in_set_internally = false;
self.key_write_status.reg.modify(
KeyWriteStatus::READY::SET
+ KeyWriteStatus::VALID::SET
+ KeyWriteStatus::ERROR.val(key_write_result),
);
}
/// Generate ECC Key Pair
fn gen_key(&mut self) {
let (priv_key, pub_key) = Ecc384::gen_key_pair(
&bytes_from_words_le(&self.seed),
&bytes_from_words_le(&self.nonce),
);
self.priv_key_in = words_from_bytes_le(&priv_key);
// Check if key write control is enabled.
if self
.key_write_ctrl
.reg
.is_set(KeyWriteControl::KEY_WRITE_EN)
{
self.key_write_status.reg.modify(
KeyWriteStatus::READY::CLEAR
+ KeyWriteStatus::VALID::CLEAR
+ KeyWriteStatus::ERROR::CLEAR,
);
self.op_key_write_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
} else {
// Make the private key available to the uC
self.priv_key_out = self.priv_key_in;
}
self.pub_key_x = words_from_bytes_le(&pub_key.x);
self.pub_key_y = words_from_bytes_le(&pub_key.y);
}
/// Sign the hash register
fn sign(&mut self) {
let signature = Ecc384::sign(
&bytes_from_words_le(&self.priv_key_in),
&bytes_from_words_le(&self.hash),
);
self.sig_r = words_from_bytes_le(&signature.r);
self.sig_s = words_from_bytes_le(&signature.s);
}
/// Sign the PCR digest
fn pcr_digest_sign(&mut self) {
const PCR_SIGN_KEY: u32 = 7;
let mut key_usage = KeyUsage::default();
key_usage.set_ecc_private_key(true);
let pcr_key = self
.key_vault
.read_key_locked(PCR_SIGN_KEY, key_usage)
.unwrap();
let pcr_digest: [u8; 48] = self.hash_sha512.pcr_hash_digest()[..48].try_into().unwrap();
let signature = Ecc384::sign(
&pcr_key[..48].try_into().unwrap(),
&pcr_digest[..48].try_into().unwrap(),
);
self.sig_r = words_from_bytes_le(&signature.r);
self.sig_s = words_from_bytes_le(&signature.s);
}
/// Verify the ECC Signature
fn verify(&mut self) {
let verify_r = Ecc384::verify(
&Ecc384PubKey {
x: bytes_from_words_le(&self.pub_key_x),
y: bytes_from_words_le(&self.pub_key_y),
},
&bytes_from_words_le(&self.hash),
&Ecc384Signature {
r: bytes_from_words_le(&self.sig_r),
s: bytes_from_words_le(&self.sig_s),
},
);
self.verify_r = words_from_bytes_le(&verify_r);
}
// Clear registers
fn zeroize(&mut self) {
self.seed.fill(0);
self.hash.fill(0);
self.priv_key_out.fill(0);
self.pub_key_x.fill(0);
self.pub_key_y.fill(0);
self.sig_r.fill(0);
self.sig_s.fill(0);
self.verify_r.fill(0);
self.iv.fill(0);
self.nonce.fill(0);
self.priv_key_in.fill(0);
self.dh_shared_key.fill(0);
}
/// Generate Diffie-Hellman shared key
fn generate_dh_shared_key(&mut self) {
let shared_key = Ecc384::compute_shared_secret(
&bytes_from_words_le(&self.priv_key_in),
&Ecc384PubKey {
x: bytes_from_words_le(&self.pub_key_x),
y: bytes_from_words_le(&self.pub_key_y),
},
);
// Handle the shared key based on control register settings
if self
.key_write_ctrl
.reg
.is_set(KeyWriteControl::KEY_WRITE_EN)
{
// If key write is enabled, prepare for writing to key vault
self.key_write_status.reg.modify(
KeyWriteStatus::READY::CLEAR
+ KeyWriteStatus::VALID::CLEAR
+ KeyWriteStatus::ERROR::CLEAR,
);
self.priv_key_in = words_from_bytes_le(&shared_key);
self.priv_key_in_set_internally = true;
self.op_key_write_complete_action = Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
} else if self.priv_key_in_set_internally {
// If key read is enabled, store in priv_key_in but don't schedule write operation
self.priv_key_in = words_from_bytes_le(&shared_key);
self.priv_key_in_set_internally = true;
} else {
// Normal case: store in dh_shared_key register
self.dh_shared_key = words_from_bytes_le(&shared_key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use caliptra_emu_bus::Bus;
use caliptra_emu_crypto::EndianessTransform;
use caliptra_emu_types::RvAddr;
use tock_registers::registers::InMemoryRegister;
const OFFSET_NAME0: RvAddr = 0x0;
const OFFSET_NAME1: RvAddr = 0x4;
const OFFSET_VERSION0: RvAddr = 0x8;
const OFFSET_VERSION1: RvAddr = 0xC;
const OFFSET_CONTROL: RvAddr = 0x10;
const OFFSET_STATUS: RvAddr = 0x18;
const OFFSET_SEED: RvAddr = 0x80;
const OFFSET_HASH: RvAddr = 0x100;
const OFFSET_PRIV_KEY_IN: RvAddr = 0x580;
const OFFSET_PUB_KEY_X: RvAddr = 0x200;
const OFFSET_PUB_KEY_Y: RvAddr = 0x280;
const OFFSET_SIG_R: RvAddr = 0x300;
const OFFSET_SIG_S: RvAddr = 0x380;
const OFFSET_NONCE: RvAddr = 0x500;
const OFFSET_KEY_READ_CONTROL: RvAddr = 0x600;
const OFFSET_KEY_READ_STATUS: RvAddr = 0x604;
const OFFSET_SEED_CONTROL: RvAddr = 0x608;
const OFFSET_SEED_STATUS: RvAddr = 0x60c;
const OFFSET_KEY_WRITE_CONTROL: RvAddr = 0x610;
const OFFSET_KEY_WRITE_STATUS: RvAddr = 0x614;
const PRIV_KEY: [u8; 48] = [
0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73,
0xf2, 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c,
0xa7, 0x84, 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab,
0x89, 0x46, 0xd6,
];
const PUB_KEY_X: [u8; 48] = [
0xd7, 0xdd, 0x94, 0xe0, 0xbf, 0xfc, 0x4c, 0xad, 0xe9, 0x90, 0x2b, 0x7f, 0xdb, 0x15, 0x42,
0x60, 0xd5, 0xec, 0x5d, 0xfd, 0x57, 0x95, 0xe, 0x83, 0x59, 0x1, 0x5a, 0x30, 0x2c, 0x8b,
0xf7, 0xbb, 0xa7, 0xe5, 0xf6, 0xdf, 0xfc, 0x16, 0x85, 0x16, 0x2b, 0xdd, 0x35, 0xf9, 0xf5,
0xc1, 0xb0, 0xff,
];
const PUB_KEY_Y: [u8; 48] = [
0xbb, 0x9c, 0x3a, 0x2f, 0x6, 0x1e, 0x8d, 0x70, 0x14, 0x27, 0x8d, 0xd5, 0x1e, 0x66, 0xa9,
0x18, 0xa6, 0xb6, 0xf9, 0xf1, 0xc1, 0x93, 0x73, 0x12, 0xd4, 0xe7, 0xa9, 0x21, 0xb1, 0x8e,
0xf0, 0xf4, 0x1f, 0xdd, 0x40, 0x1d, 0x9e, 0x77, 0x18, 0x50, 0x9f, 0x87, 0x31, 0xe9, 0xee,
0xc9, 0xc3, 0x1d,
];
const SIG_R: [u8; 48] = [
0x93, 0x79, 0x9d, 0x55, 0x12, 0x26, 0x36, 0x28, 0x34, 0xf6, 0xf, 0x7b, 0x94, 0x52, 0x90,
0xb7, 0xcc, 0xe6, 0xe9, 0x96, 0x1, 0xfb, 0x7e, 0xbd, 0x2, 0x6c, 0x2e, 0x3c, 0x44, 0x5d,
0x3c, 0xd9, 0xb6, 0x50, 0x68, 0xda, 0xc0, 0xa8, 0x48, 0xbe, 0x9f, 0x5, 0x60, 0xaa, 0x75,
0x8f, 0xda, 0x27,
];
const SIG_S: [u8; 48] = [
0xe5, 0x48, 0xe5, 0x35, 0xa1, 0xcc, 0x60, 0xe, 0x13, 0x3b, 0x55, 0x91, 0xae, 0xba, 0xad,
0x78, 0x5, 0x40, 0x6, 0xd7, 0x52, 0xd0, 0xe1, 0xdf, 0x94, 0xfb, 0xfa, 0x95, 0xd7, 0x8f,
0xb, 0x3f, 0x8e, 0x81, 0xb9, 0x11, 0x9c, 0x2b, 0xe0, 0x8, 0xbf, 0x6d, 0x6f, 0x4e, 0x41,
0x85, 0xf8, 0x7d,
];
const SHARED_SECRET: [u8; 48] = [
0xcf, 0x45, 0xb5, 0x72, 0x47, 0x40, 0x59, 0xc5, 0x0a, 0x3d, 0xc1, 0xd1, 0x0b, 0xcf, 0x72,
0xab, 0xc8, 0x9e, 0x06, 0x16, 0x60, 0x50, 0xc4, 0x2e, 0x6f, 0x63, 0x1f, 0x71, 0xb7, 0xaf,
0x17, 0xf8, 0x66, 0x45, 0x31, 0x81, 0x1a, 0x3e, 0xf4, 0x1c, 0x93, 0xb1, 0x97, 0x3c, 0x24,
0x6c, 0x50, 0xb6,
];
fn make_word(idx: usize, arr: &[u8]) -> RvData {
let mut res: RvData = 0;
for i in 0..4 {
res |= (arr[idx + i] as RvData) << (i * 8);
}
res
}
#[test]
fn test_name() {
let clock = Clock::new();
let key_vault = KeyVault::new();
let sha512 = HashSha512::new(&clock, key_vault.clone());
let mut ecc = AsymEcc384::new(&clock, key_vault, sha512);
let name0 = ecc.read(RvSize::Word, OFFSET_NAME0).unwrap();
let name0 = String::from_utf8_lossy(&name0.to_be_bytes()).to_string();
assert_eq!(name0, "secp");
let name1 = ecc.read(RvSize::Word, OFFSET_NAME1).unwrap();
let name1 = String::from_utf8_lossy(&name1.to_be_bytes()).to_string();
assert_eq!(name1, "-384");
}
#[test]
fn test_version() {
let clock = Clock::new();
let key_vault = KeyVault::new();
let sha512 = HashSha512::new(&clock, key_vault.clone());
let mut ecc = AsymEcc384::new(&clock, key_vault, sha512);
let version0 = ecc.read(RvSize::Word, OFFSET_VERSION0).unwrap();
let version0 = String::from_utf8_lossy(&version0.to_le_bytes()).to_string();
assert_eq!(version0, "1.00");
let version1 = ecc.read(RvSize::Word, OFFSET_VERSION1).unwrap();
let version1 = String::from_utf8_lossy(&version1.to_le_bytes()).to_string();
assert_eq!(version1, "\0\0\0\0");
}
#[test]
fn test_control() {
let clock = Clock::new();
let key_vault = KeyVault::new();
let sha512 = HashSha512::new(&clock, key_vault.clone());
let mut ecc = AsymEcc384::new(&clock, key_vault, sha512);
assert_eq!(ecc.read(RvSize::Word, OFFSET_CONTROL).unwrap(), 0);
}
#[test]
fn test_status() {
let clock = Clock::new();
let key_vault = KeyVault::new();
let sha512 = HashSha512::new(&clock, key_vault.clone());
let mut ecc = AsymEcc384::new(&clock, key_vault, sha512);
assert_eq!(ecc.read(RvSize::Word, OFFSET_STATUS).unwrap(), 1);
}
#[test]
fn test_gen_key() {
let clock = Clock::new();
let key_vault = KeyVault::new();
let sha512 = HashSha512::new(&clock, key_vault.clone());
let mut ecc = AsymEcc384::new(&clock, key_vault, sha512);
let mut seed = [0u8; 48];
seed.to_big_endian(); // Change DWORDs to big-endian.
for i in (0..seed.len()).step_by(4) {
ecc.write(RvSize::Word, OFFSET_SEED + i as RvAddr, make_word(i, &seed))
.unwrap();
}
let mut nonce = [0u8; 48];
nonce.to_big_endian(); // Change DWORDs to big-endian.
for i in (0..nonce.len()).step_by(4) {
assert_eq!(
ecc.write(
RvSize::Word,
OFFSET_NONCE + i as RvAddr,
make_word(i, &nonce)
)
.ok(),
Some(())
);
}
ecc.write(RvSize::Word, OFFSET_CONTROL, Control::CTRL::GEN_KEY.into())
.unwrap();
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
ecc.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) && status.is_set(Status::READY) {
break;
}
clock.increment_and_process_timer_actions(1, &mut ecc);
}
let mut priv_key = bytes_from_words_le(&ecc.priv_key_out);
priv_key.to_little_endian(); // Change DWORDs to little-endian.
let mut pub_key_x = bytes_from_words_le(&ecc.pub_key_x);
pub_key_x.to_little_endian(); // Change DWORDs to little-endian.
let mut pub_key_y = bytes_from_words_le(&ecc.pub_key_y);
pub_key_y.to_little_endian(); // Change DWORDs to little-endian.
assert_eq!(&priv_key, &PRIV_KEY);
assert_eq!(&pub_key_x, &PUB_KEY_X);
assert_eq!(&pub_key_y, &PUB_KEY_Y);
}
#[test]
fn test_gen_key_kv_seed() {
// Test for getting the seed from the key-vault.
for key_id in 0..KeyVault::KEY_COUNT {
let clock = Clock::new();
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/abr.rs | sw-emulator/lib/periph/src/abr.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
abr.rs
Abstract:
File contains Adams Bridge peripheral implementation.
--*/
use crate::helpers::{bytes_from_words_le, words_from_bytes_le};
use crate::{HashSha512, KeyUsage, KeyVault};
use caliptra_emu_bus::{ActionHandle, BusError, Clock, ReadOnlyRegister, ReadWriteRegister, Timer};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use fips204::ml_dsa_87::{try_keygen_with_rng, PrivateKey, PublicKey, PK_LEN, SIG_LEN, SK_LEN};
use fips204::traits::{SerDes, Signer, Verifier};
use ml_dsa_01::{MlDsa87, SigningKey, VerifyingKey};
use ml_kem::MlKem1024Params;
use ml_kem::{
kem::{Decapsulate, DecapsulationKey, Encapsulate, EncapsulationKey},
EncodedSizeUser, KemCore, MlKem1024,
};
use rand::{CryptoRng, RngCore};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use zerocopy::IntoBytes;
// RNG that provides fixed seeds from a vector.
pub(crate) struct SeedOnlyRng {
seeds: Vec<[u8; 32]>,
call_count: usize,
}
impl SeedOnlyRng {
pub(crate) fn new(seed: [u8; 32]) -> Self {
Self {
seeds: vec![seed],
call_count: 0,
}
}
pub(crate) fn new_with_seeds(seeds: Vec<[u8; 32]>) -> Self {
Self {
seeds,
call_count: 0,
}
}
}
impl RngCore for SeedOnlyRng {
fn next_u32(&mut self) -> u32 {
unimplemented!()
}
fn next_u64(&mut self) -> u64 {
unimplemented!()
}
fn fill_bytes(&mut self, out: &mut [u8]) {
if self.call_count >= self.seeds.len() {
panic!("Called fill_bytes more times than available seeds");
}
assert_eq!(out.len(), 32);
out.copy_from_slice(&self.seeds[self.call_count]);
self.call_count += 1;
}
fn try_fill_bytes(&mut self, out: &mut [u8]) -> Result<(), rand::Error> {
self.fill_bytes(out);
Ok(())
}
}
impl CryptoRng for SeedOnlyRng {}
/// ML_DSA87 Initialization Vector size
const ML_DSA87_IV_SIZE: usize = 64;
/// ML_DSA87 Key Generation seed
const ML_DSA87_SEED_SIZE: usize = 32;
/// ML_DSA87 SIGN_RND size
const ML_DSA87_SIGN_RND_SIZE: usize = 32;
/// ML_DSA87 MSG size
const ML_DSA87_MSG_SIZE: usize = 64;
/// ML_DSA87 MSG MAX size (for streaming mode)
const ML_DSA87_MSG_MAX_SIZE: usize = 8192; // Message limit for streamed messages
/// ML_DSA87 external mu size
const ML_DSA87_EXTERNAL_MU_SIZE: usize = 64;
/// ML_DSA87 VERIFICATION size
const ML_DSA87_VERIFICATION_SIZE_BYTES: usize = 64;
/// ML_DSA87 CTX_CONFIG size
const ML_DSA87_CTX_SIZE: usize = 256;
/// ML_DSA87 PUBKEY size
const ML_DSA87_PUBKEY_SIZE: usize = PK_LEN;
/// ML_DSA87 SIGNATURE size
// Signature len is unaligned
const ML_DSA87_SIGNATURE_SIZE: usize = SIG_LEN + 1;
/// ML_DSA87 PRIVKEY size
const ML_DSA87_PRIVKEY_SIZE: usize = SK_LEN;
/// ML_KEM-1024 constants
const ML_KEM_1024_SEED_SIZE: usize = 32;
const ML_KEM_1024_MESSAGE_SIZE: usize = 32;
const ML_KEM_1024_SHARED_KEY_SIZE: usize = 32;
const ML_KEM_1024_ENCAPS_KEY_SIZE: usize = 1568;
const ML_KEM_1024_DECAPS_KEY_SIZE: usize = 3168;
const ML_KEM_1024_CIPHERTEXT_SIZE: usize = 1568;
/// The number of CPU clock cycles it takes to perform Ml_Dsa87 operation
const ML_DSA87_OP_TICKS: u64 = 1000;
/// The number of CPU clock cycles it takes to perform ML-KEM operation
const ML_KEM_OP_TICKS: u64 = 1000;
/// The number of CPU clock cycles to read keys from key vault
const KEY_RW_TICKS: u64 = 100;
register_bitfields! [
u32,
/// Control Register Fields
MlDsaControl [
CTRL OFFSET(0) NUMBITS(3) [
NONE = 0b000,
KEYGEN = 0b001,
SIGNING = 0b010,
VERIFYING = 0b011,
KEYGEN_AND_SIGN = 0b100,
],
ZEROIZE OFFSET(3) NUMBITS(1) [],
PCR_SIGN OFFSET(4) NUMBITS(1) [],
EXTERNAL_MU OFFSET(5) NUMBITS(1) [],
STREAM_MSG OFFSET(6) NUMBITS(1) [],
],
/// ML-KEM Control Register Fields
MlKemControl [
CTRL OFFSET(0) NUMBITS(3) [
NONE = 0b000,
KEYGEN = 0b001,
ENCAPS = 0b010,
DECAPS = 0b011,
KEYGEN_DECAPS = 0b100,
],
ZEROIZE OFFSET(3) NUMBITS(1) [],
],
/// Status Register Fields
MlDsaStatus [
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
MSG_STREAM_READY OFFSET(2) NUMBITS(1) [],
],
/// ML-KEM Status Register Fields
MlKemStatus [
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(1) [],
],
/// Context Config Register Fields
MlDsaCtxConfig [
CTX_SIZE OFFSET(0) NUMBITS(7) [],
],
/// Strobe Register Fields
MlDsaStrobe [
STROBE OFFSET(0) NUMBITS(4) [],
],
/// Key Vault Read Control Fields
KvRdCtrl [
READ_EN OFFSET(0) NUMBITS(1) [],
READ_ENTRY OFFSET(1) NUMBITS(5) [],
],
/// Key Vault Read Status Fields
KvStatus [
READY OFFSET(0) NUMBITS(1) [],
VALID OFFSET(1) NUMBITS(1) [],
ERROR OFFSET(2) NUMBITS(8) [
SUCCESS = 0,
KV_READ_FAIL = 1,
KV_WRITE_FAIL = 2,
],
],
/// Key Write Control Register Fields
KeyWrCtrl[
KEY_WRITE_EN OFFSET(0) NUMBITS(1) [],
KEY_ID OFFSET(1) NUMBITS(5) [],
USAGE OFFSET(6) NUMBITS(6) [],
RSVD OFFSET(12) NUMBITS(20) [],
]
];
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct Abr {
/// MLDSA Name registers
#[register_array(offset = 0x0000_0000)]
mldsa_name: [u32; 2],
/// MLDSA Version registers
#[register_array(offset = 0x0000_0008)]
mldsa_version: [u32; 2],
/// MLDSA Control register
#[register(offset = 0x0000_0010, write_fn = on_write_mldsa_control)]
mldsa_ctrl: ReadWriteRegister<u32, MlDsaControl::Register>,
/// MLDSA Status register
#[register(offset = 0x0000_0014)]
mldsa_status: ReadOnlyRegister<u32, MlDsaStatus::Register>,
/// ABR Entropy (shared between MLDSA and MLKEM)
#[register_array(offset = 0x0000_0018)]
abr_entropy: [u32; ML_DSA87_IV_SIZE / 4],
/// MLDSA Seed
#[register_array(offset = 0x0000_0058)]
mldsa_seed: [u32; ML_DSA87_SEED_SIZE / 4],
/// MLDSA Sign RND
#[register_array(offset = 0x0000_0078)]
mldsa_sign_rnd: [u32; ML_DSA87_SIGN_RND_SIZE / 4],
/// MLDSA Message
#[register_array(offset = 0x0000_0098, write_fn = on_write_mldsa_msg)]
mldsa_msg: [u32; ML_DSA87_MSG_SIZE / 4],
/// MLDSA Verification result
#[register_array(offset = 0x0000_00d8, write_fn = write_mldsa_access_fault)]
mldsa_verify_res: [u32; ML_DSA87_VERIFICATION_SIZE_BYTES / 4],
/// MLDSA External mu
#[register_array(offset = 0x0000_0118)]
mldsa_external_mu: [u32; ML_DSA87_EXTERNAL_MU_SIZE / 4],
/// MLDSA Message Strobe
#[register(offset = 0x0000_0158)]
mldsa_msg_strobe: ReadWriteRegister<u32, MlDsaStrobe::Register>,
/// MLDSA Context config
#[register(offset = 0x0000_015c)]
mldsa_ctx_config: ReadWriteRegister<u32, MlDsaCtxConfig::Register>,
/// MLDSA Context
#[register_array(offset = 0x0000_0160)]
mldsa_ctx: [u32; ML_DSA87_CTX_SIZE / 4],
/// MLDSA Public key
#[register_array(offset = 0x0000_1000)]
mldsa_pubkey: [u32; ML_DSA87_PUBKEY_SIZE / 4],
/// MLDSA Signature
#[register_array(offset = 0x0000_2000)]
mldsa_signature: [u32; ML_DSA87_SIGNATURE_SIZE / 4],
/// MLDSA Private Key Out
#[register_array(offset = 0x0000_4000)]
mldsa_privkey_out: [u32; ML_DSA87_PRIVKEY_SIZE / 4],
/// MLDSA Private Key In
#[register_array(offset = 0x0000_6000)]
mldsa_privkey_in: [u32; ML_DSA87_PRIVKEY_SIZE / 4],
/// Key Vault MLDSA Seed Read Control
#[register(offset = 0x0000_8000, write_fn = on_write_mldsa_kv_rd_seed_ctrl)]
kv_mldsa_seed_rd_ctrl: ReadWriteRegister<u32, KvRdCtrl::Register>,
/// Key Vault MLDSA Seed Read Status
#[register(offset = 0x0000_8004)]
kv_mldsa_seed_rd_status: ReadOnlyRegister<u32, KvStatus::Register>,
/// MLKEM Name registers
#[register_array(offset = 0x0000_9000)]
mlkem_name: [u32; 2],
/// MLKEM Version registers
#[register_array(offset = 0x0000_9008)]
mlkem_version: [u32; 2],
/// MLKEM Control register
#[register(offset = 0x0000_9010, write_fn = on_write_mlkem_control)]
mlkem_ctrl: ReadWriteRegister<u32, MlKemControl::Register>,
/// MLKEM Status register
#[register(offset = 0x0000_9014)]
mlkem_status: ReadOnlyRegister<u32, MlKemStatus::Register>,
/// MLKEM Seed D
#[register_array(offset = 0x0000_9018)]
mlkem_seed_d: [u32; ML_KEM_1024_SEED_SIZE / 4],
/// MLKEM Seed Z
#[register_array(offset = 0x0000_9038)]
mlkem_seed_z: [u32; ML_KEM_1024_SEED_SIZE / 4],
/// MLKEM Shared Key
#[register_array(offset = 0x0000_9058)]
mlkem_shared_key: [u32; ML_KEM_1024_SHARED_KEY_SIZE / 4],
/// MLKEM Message
#[register_array(offset = 0x0000_9080)]
mlkem_msg: [u32; ML_KEM_1024_MESSAGE_SIZE / 4],
/// MLKEM Decapsulation Key
#[register_array(offset = 0x0000_A000)]
mlkem_decaps_key: [u32; ML_KEM_1024_DECAPS_KEY_SIZE / 4],
/// MLKEM Encapsulation Key
#[register_array(offset = 0x0000_B000)]
mlkem_encaps_key: [u32; ML_KEM_1024_ENCAPS_KEY_SIZE / 4],
/// MLKEM Ciphertext
#[register_array(offset = 0x0000_B800)]
mlkem_ciphertext: [u32; ML_KEM_1024_CIPHERTEXT_SIZE / 4],
/// Key Vault MLKEM Seed Read Control
#[register(offset = 0x0000_C000, write_fn = on_write_mlkem_kv_rd_seed_ctrl)]
kv_mlkem_seed_rd_ctrl: ReadWriteRegister<u32, KvRdCtrl::Register>,
/// Key Vault MLKEM Seed Read Status
#[register(offset = 0x0000_C004)]
kv_mlkem_seed_rd_status: ReadOnlyRegister<u32, KvStatus::Register>,
/// Key Vault MLKEM Message Read Control
#[register(offset = 0x0000_C008, write_fn = on_write_mlkem_kv_rd_msg_ctrl)]
kv_mlkem_msg_rd_ctrl: ReadWriteRegister<u32, KvRdCtrl::Register>,
/// Key Vault MLKEM Message Read Status
#[register(offset = 0x0000_C00C)]
kv_mlkem_msg_rd_status: ReadOnlyRegister<u32, KvStatus::Register>,
/// Key Vault MLKEM Shared Key Write Control
#[register(offset = 0x0000_C010, write_fn = on_write_mlkem_kv_wr_sharedkey_ctrl)]
kv_mlkem_sharedkey_wr_ctrl: ReadWriteRegister<u32, KeyWrCtrl::Register>,
/// Key Vault MLKEM Shared Key Write Status
#[register(offset = 0x0000_C014)]
kv_mlkem_sharedkey_wr_status: ReadOnlyRegister<u32, KvStatus::Register>,
/// Error Global Intr register
#[register(offset = 0x0000_810c)]
error_global_intr: ReadOnlyRegister<u32>,
/// Error Internal Intr register
#[register(offset = 0x0000_8114)]
error_internal_intr: ReadOnlyRegister<u32>,
mldsa_private_key: [u8; ML_DSA87_PRIVKEY_SIZE],
/// Timer
timer: Timer,
/// Key Vault
key_vault: KeyVault,
/// SHA512 hash
hash_sha512: HashSha512,
/// Operation complete callback
mldsa_op_complete_action: Option<ActionHandle>,
/// Seed read complete action
mldsa_op_seed_read_complete_action: Option<ActionHandle>,
/// Zeroize complete callback
mldsa_op_zeroize_complete_action: Option<ActionHandle>,
/// Msg stream ready callback
mldsa_op_msg_stream_ready_action: Option<ActionHandle>,
/// Streaming message buffer
mldsa_streamed_msg: Vec<u8>,
/// ML-KEM operation complete callback
mlkem_op_complete_action: Option<ActionHandle>,
/// ML-KEM zeroize complete callback
mlkem_op_zeroize_complete_action: Option<ActionHandle>,
/// ML-KEM seed read complete action
mlkem_seed_read_complete_action: Option<ActionHandle>,
/// ML-KEM message read complete action
mlkem_msg_read_complete_action: Option<ActionHandle>,
/// ML-KEM shared key write complete action
mlkem_sharedkey_write_complete_action: Option<ActionHandle>,
/// Internal storage for shared key (not exposed via registers when writing to KV)
mlkem_shared_key_internal: [u8; ML_KEM_1024_SHARED_KEY_SIZE],
}
impl Abr {
/// MLDSA NAME0 Register Value
const MLDSA_NAME0_VAL: RvData = 0x44534D4C; // "DSML" - part of "MLDSA-87"
/// MLDSA NAME1 Register Value
const MLDSA_NAME1_VAL: RvData = 0x3837412D; // "87A-" - part of "MLDSA-87"
/// MLKEM NAME0 Register Value
const MLKEM_NAME0_VAL: RvData = 0x4D2D4B45; // "M-KE" - part of "KEM-1024"
/// MLKEM NAME1 Register Value
const MLKEM_NAME1_VAL: RvData = 0x32343130; // "2410" - part of "KEM-1024"
/// VERSION0 Register Value
const VERSION0_VAL: RvData = 0x3030312e; // "1.00"
/// VERSION1 Register Value
const VERSION1_VAL: RvData = 0x00000000;
pub fn new(clock: &Clock, key_vault: KeyVault, hash_sha512: HashSha512) -> Self {
Self {
mldsa_name: [Self::MLDSA_NAME0_VAL, Self::MLDSA_NAME1_VAL],
mldsa_version: [Self::VERSION0_VAL, Self::VERSION1_VAL],
mldsa_ctrl: ReadWriteRegister::new(0),
mldsa_status: ReadOnlyRegister::new(MlDsaStatus::READY::SET.value),
abr_entropy: Default::default(),
mldsa_seed: Default::default(),
mldsa_sign_rnd: Default::default(),
mldsa_msg: Default::default(),
mldsa_verify_res: Default::default(),
mldsa_external_mu: Default::default(),
mldsa_msg_strobe: ReadWriteRegister::new(0xf),
mldsa_ctx_config: ReadWriteRegister::new(0),
mldsa_ctx: [0; ML_DSA87_CTX_SIZE / 4],
mldsa_pubkey: [0; ML_DSA87_PUBKEY_SIZE / 4],
mldsa_signature: [0; ML_DSA87_SIGNATURE_SIZE / 4],
mldsa_privkey_out: [0; ML_DSA87_PRIVKEY_SIZE / 4],
mldsa_privkey_in: [0; ML_DSA87_PRIVKEY_SIZE / 4],
kv_mldsa_seed_rd_ctrl: ReadWriteRegister::new(0),
kv_mldsa_seed_rd_status: ReadOnlyRegister::new(KvStatus::READY::SET.value),
mlkem_name: [Self::MLKEM_NAME0_VAL, Self::MLKEM_NAME1_VAL],
mlkem_version: [Self::VERSION0_VAL, Self::VERSION1_VAL],
mlkem_ctrl: ReadWriteRegister::new(0),
mlkem_status: ReadOnlyRegister::new(MlKemStatus::READY::SET.value),
mlkem_seed_d: Default::default(),
mlkem_seed_z: Default::default(),
mlkem_shared_key: Default::default(),
mlkem_msg: Default::default(),
mlkem_decaps_key: [0; ML_KEM_1024_DECAPS_KEY_SIZE / 4],
mlkem_encaps_key: [0; ML_KEM_1024_ENCAPS_KEY_SIZE / 4],
mlkem_ciphertext: [0; ML_KEM_1024_CIPHERTEXT_SIZE / 4],
kv_mlkem_seed_rd_ctrl: ReadWriteRegister::new(0),
kv_mlkem_seed_rd_status: ReadOnlyRegister::new(0),
kv_mlkem_msg_rd_ctrl: ReadWriteRegister::new(0),
kv_mlkem_msg_rd_status: ReadOnlyRegister::new(0),
kv_mlkem_sharedkey_wr_ctrl: ReadWriteRegister::new(0),
kv_mlkem_sharedkey_wr_status: ReadOnlyRegister::new(0),
error_global_intr: ReadOnlyRegister::new(0),
error_internal_intr: ReadOnlyRegister::new(0),
mldsa_private_key: [0; ML_DSA87_PRIVKEY_SIZE],
timer: Timer::new(clock),
key_vault,
hash_sha512,
mldsa_op_complete_action: None,
mldsa_op_seed_read_complete_action: None,
mldsa_op_zeroize_complete_action: None,
mldsa_op_msg_stream_ready_action: None,
mldsa_streamed_msg: Vec::with_capacity(ML_DSA87_MSG_MAX_SIZE),
mlkem_op_complete_action: None,
mlkem_op_zeroize_complete_action: None,
mlkem_seed_read_complete_action: None,
mlkem_msg_read_complete_action: None,
mlkem_sharedkey_write_complete_action: None,
mlkem_shared_key_internal: [0; ML_KEM_1024_SHARED_KEY_SIZE],
}
}
fn write_mldsa_access_fault(
&self,
_size: RvSize,
_index: usize,
_val: RvData,
) -> Result<(), BusError> {
Err(BusError::StoreAccessFault)
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_mldsa_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.mldsa_ctrl.reg.set(val);
match self.mldsa_ctrl.reg.read_as_enum(MlDsaControl::CTRL) {
Some(MlDsaControl::CTRL::Value::KEYGEN)
| Some(MlDsaControl::CTRL::Value::SIGNING)
| Some(MlDsaControl::CTRL::Value::VERIFYING)
| Some(MlDsaControl::CTRL::Value::KEYGEN_AND_SIGN) => {
// Reset the Ready and Valid status bits
self.mldsa_status
.reg
.modify(MlDsaStatus::READY::CLEAR + MlDsaStatus::VALID::CLEAR);
// If streaming message mode is enabled, set the MSG_STREAM_READY bit
// and wait for the message to be streamed in
if self.mldsa_ctrl.reg.is_set(MlDsaControl::STREAM_MSG)
&& (self.mldsa_ctrl.reg.read_as_enum(MlDsaControl::CTRL)
== Some(MlDsaControl::CTRL::Value::SIGNING)
|| self.mldsa_ctrl.reg.read_as_enum(MlDsaControl::CTRL)
== Some(MlDsaControl::CTRL::Value::VERIFYING)
|| self.mldsa_ctrl.reg.read_as_enum(MlDsaControl::CTRL)
== Some(MlDsaControl::CTRL::Value::KEYGEN_AND_SIGN))
{
// Clear any previous streamed message
self.mldsa_streamed_msg.clear();
self.mldsa_status
.reg
.modify(MlDsaStatus::MSG_STREAM_READY::CLEAR);
// Schedule an action to set the MSG_STREAM_READY bit after a short delay
self.mldsa_op_msg_stream_ready_action = Some(self.timer.schedule_poll_in(10));
} else {
// Not waiting for message streaming, proceed with operation
self.mldsa_op_complete_action =
Some(self.timer.schedule_poll_in(ML_DSA87_OP_TICKS));
}
}
_ => {}
}
if self.mldsa_ctrl.reg.is_set(MlDsaControl::ZEROIZE) {
// Reset the Ready status bit
self.mldsa_status.reg.modify(MlDsaStatus::READY::CLEAR);
self.mldsa_op_zeroize_complete_action =
Some(self.timer.schedule_poll_in(ML_DSA87_OP_TICKS));
}
Ok(())
}
/// On Write callback for `kv_rd_seed_ctrl` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_mldsa_kv_rd_seed_ctrl(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.kv_mldsa_seed_rd_ctrl.reg.set(val);
if self.kv_mldsa_seed_rd_ctrl.reg.is_set(KvRdCtrl::READ_EN) {
self.kv_mldsa_seed_rd_status
.reg
.modify(KvStatus::READY::CLEAR + KvStatus::VALID::CLEAR + KvStatus::ERROR::CLEAR);
self.mldsa_op_seed_read_complete_action =
Some(self.timer.schedule_poll_in(KEY_RW_TICKS));
}
Ok(())
}
/// On Write callback for message register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `index` - Index of the dword being written
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_mldsa_msg(
&mut self,
size: RvSize,
index: usize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Regular write for non-streaming mode
if !self.mldsa_ctrl.reg.is_set(MlDsaControl::STREAM_MSG) {
self.mldsa_msg[index] = val;
return Ok(());
}
// We're in streaming mode
assert!(index == 0);
// Streaming message mode - handle write to index 0
let strobe_value = self.mldsa_msg_strobe.reg.read(MlDsaStrobe::STROBE);
let mut bytes_to_add: Vec<u8> = Vec::new();
// Handle the strobe for valid bytes
if strobe_value == 0xF {
// All bytes valid
bytes_to_add.extend_from_slice(&val.to_le_bytes());
} else {
let val_bytes = val.to_le_bytes();
for (i, &byte) in val_bytes.iter().enumerate() {
if (strobe_value & (1 << i)) != 0 {
bytes_to_add.push(byte);
}
}
// Reset the strobe and mark end of message
self.mldsa_msg_strobe
.reg
.write(MlDsaStrobe::STROBE.val(0xF));
// If this was the last segment, start processing
self.mldsa_status
.reg
.modify(MlDsaStatus::MSG_STREAM_READY::CLEAR);
self.mldsa_op_complete_action = Some(self.timer.schedule_poll_in(ML_DSA87_OP_TICKS));
}
// Add the bytes to the streamed message
self.mldsa_streamed_msg.extend_from_slice(&bytes_to_add);
Ok(())
}
fn mldsa_gen_key(&mut self) {
// Unlike ECC, no dword endianness reversal is needed.
let seed = bytes_from_words_le(&self.mldsa_seed);
let mut rng = SeedOnlyRng::new(seed);
let (pubkey, privkey) = try_keygen_with_rng(&mut rng).unwrap();
let pubkey = pubkey.into_bytes();
self.mldsa_pubkey = words_from_bytes_le(&pubkey);
self.mldsa_private_key = privkey.into_bytes();
if !self.kv_mldsa_seed_rd_ctrl.reg.is_set(KvRdCtrl::READ_EN) {
// privkey_out is in hardware format, which is same as library format.
let privkey_out = self.mldsa_private_key;
self.mldsa_privkey_out = words_from_bytes_le(&privkey_out);
}
}
fn mldsa_sign(&mut self, caller_provided: bool) {
// Check if PCR_SIGN is set
if self.mldsa_ctrl.reg.is_set(MlDsaControl::PCR_SIGN) {
panic!("ML-DSA PCR Sign operation needs to be performed with KEYGEN_AND_SIGN option");
}
let secret_key = if caller_provided {
// Unlike ECC, no dword endianness reversal is needed.
bytes_from_words_le(&self.mldsa_privkey_in)
} else {
self.mldsa_private_key
};
let signature = if self.mldsa_ctrl.reg.is_set(MlDsaControl::EXTERNAL_MU) {
self.mldsa_sign_mu(secret_key)
} else {
self.mldsa_sign_msg(secret_key)
};
// The Ml_Dsa87 signature is 4627 len but the reg is one byte longer
let signature_extended = {
let mut sig = [0; SIG_LEN + 1];
sig[..SIG_LEN].copy_from_slice(&signature);
sig
};
self.mldsa_signature = words_from_bytes_le(&signature_extended);
}
fn mldsa_sign_msg(&mut self, sk_bytes: [u8; SK_LEN]) -> Vec<u8> {
let secret_key = PrivateKey::try_from_bytes(sk_bytes).unwrap();
// Get message data based on streaming mode
let message = if self.mldsa_ctrl.reg.is_set(MlDsaControl::STREAM_MSG) {
// Use the streamed message
self.mldsa_streamed_msg.as_slice()
} else {
// Use the fixed message register
&bytes_from_words_le(&self.mldsa_msg)
};
// Get context if specified
let mut ctx: Vec<u8> = Vec::new();
if self.mldsa_ctrl.reg.is_set(MlDsaControl::STREAM_MSG) {
// Make sure we're not still expecting more message data
assert!(!self.mldsa_status.reg.is_set(MlDsaStatus::MSG_STREAM_READY));
let ctx_size = self.mldsa_ctx_config.reg.read(MlDsaCtxConfig::CTX_SIZE) as usize;
if ctx_size > 0 {
// Convert context array to bytes using functional approach
let ctx_bytes: Vec<u8> = self
.mldsa_ctx
.iter()
.flat_map(|word| word.to_le_bytes().to_vec())
.collect();
ctx = ctx_bytes[..ctx_size].to_vec();
}
}
secret_key
.try_sign_with_seed(&[0u8; 32], message, &ctx)
.unwrap()
.to_vec()
}
fn mldsa_sign_mu(&mut self, sk_bytes: [u8; SK_LEN]) -> Vec<u8> {
let secret_key = SigningKey::<MlDsa87>::decode(sk_bytes.as_slice().try_into().unwrap());
secret_key
.sign_mu_deterministic(self.mldsa_external_mu.as_bytes().try_into().unwrap())
.encode()
.to_vec()
}
/// Sign the PCR digest
fn mldsa_pcr_digest_sign(&mut self) {
const PCR_SIGN_KEY: u32 = 8;
let _ = self.mldsa_read_seed_from_keyvault(PCR_SIGN_KEY, true);
// Generate private key from seed.
self.mldsa_gen_key();
let secret_key = PrivateKey::try_from_bytes(self.mldsa_private_key).unwrap();
let pcr_digest = self.hash_sha512.pcr_hash_digest();
let mut temp = words_from_bytes_le(
&<[u8; ML_DSA87_MSG_SIZE]>::try_from(&pcr_digest[..ML_DSA87_MSG_SIZE]).unwrap(),
);
// Reverse the dword order.
temp.reverse();
// The Ml_Dsa87 signature is 4595 len but the reg is one byte longer
let signature = secret_key
.try_sign_with_seed(&[0u8; 32], temp.as_bytes(), &[])
.unwrap();
let signature_extended = {
let mut sig = [0; SIG_LEN + 1];
sig[..SIG_LEN].copy_from_slice(&signature);
sig
};
self.mldsa_signature = words_from_bytes_le(&signature_extended);
}
fn mldsa_verify(&mut self) {
let key_bytes = bytes_from_words_le(&self.mldsa_pubkey);
let sig = bytes_from_words_le(&self.mldsa_signature);
let signature = &sig[..SIG_LEN].try_into().unwrap();
let success = if self.mldsa_ctrl.reg.is_set(MlDsaControl::EXTERNAL_MU) {
self.mldsa_verify_mu(key_bytes, signature)
} else {
self.mldsa_verify_msg(key_bytes, signature)
};
if success {
self.mldsa_verify_res
.copy_from_slice(&self.mldsa_signature[..(ML_DSA87_VERIFICATION_SIZE_BYTES / 4)]);
} else {
self.mldsa_verify_res = [0u32; ML_DSA87_VERIFICATION_SIZE_BYTES / 4];
}
}
fn mldsa_verify_msg(&mut self, key_bytes: [u8; PK_LEN], signature: &[u8; SIG_LEN]) -> bool {
// Get message data based on streaming mode
let message = if self.mldsa_ctrl.reg.is_set(MlDsaControl::STREAM_MSG) {
// Use the streamed message
self.mldsa_streamed_msg.as_slice()
} else {
// Unlike ECC, no dword endianness reversal is needed.
// Use the fixed message register
&bytes_from_words_le(&self.mldsa_msg)
};
let public_key = PublicKey::try_from_bytes(key_bytes).unwrap();
// Get context if specified
let mut ctx: Vec<u8> = Vec::new();
if self.mldsa_ctrl.reg.is_set(MlDsaControl::STREAM_MSG) {
// Make sure we're not still expecting more message data
assert!(!self.mldsa_status.reg.is_set(MlDsaStatus::MSG_STREAM_READY));
let ctx_size = self.mldsa_ctx_config.reg.read(MlDsaCtxConfig::CTX_SIZE) as usize;
if ctx_size > 0 {
// Convert context array to bytes using functional approach
let ctx_bytes: Vec<u8> = self
.mldsa_ctx
.iter()
.flat_map(|word| word.to_le_bytes().to_vec())
.collect();
ctx = ctx_bytes[..ctx_size].to_vec();
}
}
public_key.verify(message, signature, &ctx)
}
fn mldsa_verify_mu(&mut self, key_bytes: [u8; PK_LEN], signature: &[u8; SIG_LEN]) -> bool {
let public_key = VerifyingKey::<MlDsa87>::decode(key_bytes.as_slice().try_into().unwrap());
public_key.verify_mu(
self.mldsa_external_mu.as_bytes().try_into().unwrap(),
&signature.as_slice().try_into().unwrap(),
)
}
fn mldsa_op_complete(&mut self) {
match self.mldsa_ctrl.reg.read_as_enum(MlDsaControl::CTRL) {
Some(MlDsaControl::CTRL::Value::KEYGEN) => self.mldsa_gen_key(),
Some(MlDsaControl::CTRL::Value::SIGNING) => {
self.mldsa_sign(true);
}
Some(MlDsaControl::CTRL::Value::VERIFYING) => self.mldsa_verify(),
Some(MlDsaControl::CTRL::Value::KEYGEN_AND_SIGN) => {
if self.mldsa_ctrl.reg.is_set(MlDsaControl::PCR_SIGN) {
self.mldsa_pcr_digest_sign();
} else {
self.mldsa_gen_key();
self.mldsa_sign(false);
}
}
_ => panic!("Invalid value in ML-DSA Control"),
}
self.mldsa_status.reg.modify(
MlDsaStatus::READY::SET
+ MlDsaStatus::VALID::SET
+ MlDsaStatus::MSG_STREAM_READY::CLEAR,
);
}
fn mldsa_read_seed_from_keyvault(&mut self, key_id: u32, locked: bool) -> u32 {
let mut key_usage = KeyUsage::default();
key_usage.set_mldsa_key_gen_seed(true);
let result = if locked {
self.key_vault.read_key_locked(key_id, key_usage)
} else {
self.key_vault.read_key(key_id, key_usage)
};
let (seed_read_result, seed) = match result.err() {
Some(BusError::LoadAccessFault)
| Some(BusError::LoadAddrMisaligned)
| Some(BusError::InstrAccessFault) => (KvStatus::ERROR::KV_READ_FAIL.value, None),
Some(BusError::StoreAccessFault) | Some(BusError::StoreAddrMisaligned) => {
(KvStatus::ERROR::KV_WRITE_FAIL.value, None)
}
None => (KvStatus::ERROR::SUCCESS.value, Some(result.unwrap())),
};
// Read the first 32 bytes from KV.
// Key vault already stores seed in hardware format
if let Some(seed) = seed {
let mut temp = words_from_bytes_le(
&<[u8; ML_DSA87_SEED_SIZE]>::try_from(&seed[..ML_DSA87_SEED_SIZE]).unwrap(),
);
// DOWRD 0 from Key Vault goes to DWORD 7 of Seed.
temp.reverse();
self.mldsa_seed = temp;
}
seed_read_result
}
fn mldsa_seed_read_complete(&mut self) {
let key_id = self.kv_mldsa_seed_rd_ctrl.reg.read(KvRdCtrl::READ_ENTRY);
let seed_read_result = self.mldsa_read_seed_from_keyvault(key_id, false);
self.kv_mldsa_seed_rd_status.reg.modify(
KvStatus::READY::SET + KvStatus::VALID::SET + KvStatus::ERROR.val(seed_read_result),
);
}
fn mldsa_zeroize(&mut self) {
self.mldsa_ctrl.reg.set(0);
self.mldsa_seed = Default::default();
self.mldsa_sign_rnd = Default::default();
self.mldsa_msg = Default::default();
self.mldsa_verify_res = Default::default();
self.mldsa_external_mu = Default::default();
self.mldsa_msg_strobe.reg.set(0xf); // Reset to all bytes valid
self.mldsa_ctx_config.reg.set(0);
self.mldsa_ctx = [0; ML_DSA87_CTX_SIZE / 4];
self.mldsa_pubkey = [0; ML_DSA87_PUBKEY_SIZE / 4];
self.mldsa_signature = [0; ML_DSA87_SIGNATURE_SIZE / 4];
self.mldsa_privkey_out = [0; ML_DSA87_PRIVKEY_SIZE / 4];
self.mldsa_privkey_in = [0; ML_DSA87_PRIVKEY_SIZE / 4];
self.kv_mldsa_seed_rd_ctrl.reg.set(0);
self.kv_mldsa_seed_rd_status.reg.write(KvStatus::READY::SET);
self.mldsa_private_key = [0; ML_DSA87_PRIVKEY_SIZE];
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/sha512_acc.rs | sw-emulator/lib/periph/src/sha512_acc.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sha512_acc.rs
Abstract:
File contains SHA accelerator implementation.
--*/
use crate::MailboxRam;
use caliptra_emu_bus::{
ActionHandle, Bus, BusError, Clock, ReadOnlyMemory, ReadOnlyRegister, ReadWriteRegister, Timer,
};
use caliptra_emu_crypto::{EndianessTransform, Sha512, Sha512Mode};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use smlang::statemachine;
use std::cell::RefCell;
use std::rc::Rc;
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
use tock_registers::registers::InMemoryRegister;
/// Maximum mailbox capacity in DWORDS.
const MAX_MAILBOX_CAPACITY_WORDS: usize = (256 << 10) >> 2;
/// Maximum mailbox capacity in bytes.
const MAX_MAILBOX_CAPACITY_BYTES: usize = MAX_MAILBOX_CAPACITY_WORDS * RvSize::Word as usize;
/// The number of CPU clock cycles it takes to perform sha operation.
const SHA_ACC_OP_TICKS: u64 = 1000;
const SHA512_BLOCK_SIZE: usize = 128;
const SHA512_HASH_SIZE: usize = 64;
#[cfg(test)]
const SHA384_HASH_SIZE: usize = 48;
const SHA512_HASH_HALF_SIZE: usize = SHA512_HASH_SIZE / 2;
register_bitfields! [
u32,
/// Control Register Fields
ShaMode [
MODE OFFSET(0) NUMBITS(2) [
SHA512_ACC_MODE_SHA_STREAM_384 = 0,
SHA512_ACC_MODE_SHA_STREAM_512 = 1,
SHA512_ACC_MODE_MBOX_384 = 2,
SHA512_ACC_MODE_MBOX_512 = 3,
],
ENDIAN_TOGGLE OFFSET(2) NUMBITS(1) [],
RSVD OFFSET(3) NUMBITS(29) [],
],
/// Execute Register Fields
Execute[
EXECUTE OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Status Register Fields
Status[
VALID OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Lock Register Fields
Lock[
LOCK OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// Control Register Fields
Control[
ZEROIZE OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
];
#[derive(Bus)]
#[poll_fn(poll)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct Sha512AcceleratorRegs {
/// LOCK register
#[register(offset = 0x0000_0000, read_fn = on_read_lock, write_fn = on_write_lock)]
_lock: ReadWriteRegister<u32, Lock::Register>,
/// USER register
#[register(offset = 0x0000_0004)]
user: ReadOnlyRegister<u32>,
/// MODE register
#[register(offset = 0x0000_0008, write_fn = on_write_mode)]
mode: ReadWriteRegister<u32, ShaMode::Register>,
/// START_ADDRESS register
#[register(offset = 0x0000_000c, write_fn = on_write_start_address)]
start_address: ReadWriteRegister<u32>,
/// DLEN register
#[register(offset = 0x0000_0010, write_fn = on_write_dlen)]
dlen: ReadWriteRegister<u32>,
/// DATAIN register
#[register(offset = 0x0000_0014, write_fn = on_write_data_in)]
data_in: ReadWriteRegister<u32>,
/// EXECUTE register
#[register(offset = 0x0000_0018, write_fn = on_write_execute)]
execute: ReadWriteRegister<u32, Execute::Register>,
/// STATUS register
#[register(offset = 0x0000_001c)]
status: ReadOnlyRegister<u32, Status::Register>,
/// SHA512 Hash Memory
#[peripheral(offset = 0x0000_0020, len = 0x20)]
hash_lower: ReadOnlyMemory<SHA512_HASH_HALF_SIZE>,
#[peripheral(offset = 0x0000_0040, len = 0x20)]
hash_upper: ReadOnlyMemory<SHA512_HASH_HALF_SIZE>,
/// Control register
#[register(offset = 0x0000_0060, write_fn = on_write_control)]
control: ReadWriteRegister<u32, Control::Register>,
/// Mailbox Memory
mailbox_ram: MailboxRam,
/// Timer
timer: Timer,
/// State Machine
state_machine: StateMachine<Context>,
/// Operation complete action
op_complete_action: Option<ActionHandle>,
/// Hasher for streamed hash data
sha_stream: Sha512,
}
impl Sha512AcceleratorRegs {
pub fn new(clock: &Clock, mailbox_ram: MailboxRam) -> Self {
let mut result = Self {
status: ReadOnlyRegister::new(Status::VALID::CLEAR.value),
hash_lower: ReadOnlyMemory::new(),
hash_upper: ReadOnlyMemory::new(),
mailbox_ram,
timer: Timer::new(clock),
_lock: ReadWriteRegister::new(0),
user: ReadOnlyRegister::new(0),
dlen: ReadWriteRegister::new(0),
data_in: ReadWriteRegister::new(0),
execute: ReadWriteRegister::new(0),
mode: ReadWriteRegister::new(0),
start_address: ReadWriteRegister::new(0),
op_complete_action: None,
state_machine: StateMachine::new(Context::new()),
control: ReadWriteRegister::new(0),
sha_stream: Sha512::new(Sha512Mode::Sha512),
};
// The peripheral needs to be locked at boot by the uC.
result
.state_machine
.process_event(Events::RdLock(Owner(0)))
.unwrap();
result
}
/// On Read callback for `lock` register
///
/// # Arguments
///
/// * `size` - Size of the read
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::LoadAccessFault`
pub fn on_read_lock(&mut self, size: RvSize) -> Result<u32, BusError> {
// Reads have to be Word aligned
if size != RvSize::Word {
Err(BusError::LoadAccessFault)?
}
if self
.state_machine
.process_event(Events::RdLock(Owner(0)))
.is_ok()
{
Ok(0)
} else {
Ok(1)
}
}
/// On Write callback for `lock` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_lock(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
let val_reg = InMemoryRegister::<u32, Lock::Register>::new(val);
if val_reg.read(Lock::LOCK) == 1
&& self
.state_machine
.process_event(Events::WrLock(Owner(0)))
.is_ok()
{
// Reset the state.
self.status.reg.modify(Status::VALID::CLEAR);
self.dlen.reg.set(0);
self.start_address.reg.set(0);
self.execute.reg.set(0);
self.data_in.reg.set(0);
self.mode.reg.set(0);
}
Ok(())
}
/// On Write callback for `mode` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_mode(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.mode.reg.set(val);
let mode = self.mode.reg.read(ShaMode::MODE);
if mode == ShaMode::MODE::SHA512_ACC_MODE_SHA_STREAM_384.value {
self.sha_stream = Sha512::new(Sha512Mode::Sha384);
} else if mode == ShaMode::MODE::SHA512_ACC_MODE_SHA_STREAM_512.value {
self.sha_stream = Sha512::new(Sha512Mode::Sha512);
}
Ok(())
}
/// On Write callback for `start_address` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_start_address(
&mut self,
size: RvSize,
start_address: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word
|| start_address % (RvSize::Word as RvData) != 0
|| start_address >= (MAX_MAILBOX_CAPACITY_WORDS as RvData)
{
Err(BusError::StoreAccessFault)?
}
// Set the start_address register
self.start_address.reg.set(start_address);
Ok(())
}
/// On Write callback for `dlen` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_dlen(&mut self, size: RvSize, dlen: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
let mode = self.mode.reg.read(ShaMode::MODE);
if (mode == ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value
|| mode == ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value)
&& dlen > (MAX_MAILBOX_CAPACITY_BYTES as RvData)
{
Err(BusError::StoreAccessFault)?
}
// Set the start_address register
self.dlen.reg.set(dlen);
Ok(())
}
/// On Write callback for `data_in` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_data_in(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Check ENDIAN_TOGGLE bit. If set to 1, data from the mailbox is in big-endian format.
// Convert it to little-endian for padding operation.
let val = if self.mode.reg.read(ShaMode::ENDIAN_TOGGLE) == 1 {
val.to_be_bytes()
} else {
val.to_le_bytes()
};
self.sha_stream
.update_bytes(&val, Some(self.dlen.reg.get()));
Ok(())
}
/// On Write callback for `execute` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_execute(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the execute register
self.execute.reg.set(val);
if self.execute.reg.read(Execute::EXECUTE) == 1 {
let mode = self.mode.reg.read(ShaMode::MODE);
if mode == ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value
|| mode == ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value
{
self.compute_mbox_hash();
// Schedule a future call to poll() complete the operation.
self.op_complete_action = Some(self.timer.schedule_poll_in(SHA_ACC_OP_TICKS));
} else if mode == ShaMode::MODE::SHA512_ACC_MODE_SHA_STREAM_384.value
|| mode == ShaMode::MODE::SHA512_ACC_MODE_SHA_STREAM_512.value
{
self.finalize_stream_hash();
} else {
return Err(BusError::StoreAccessFault);
}
} else {
Err(BusError::StoreAccessFault)?
}
Ok(())
}
/// On Write callback for `control` register
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
pub fn on_write_control(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
// Set the control register
self.control.reg.set(val);
if self.control.reg.is_set(Control::ZEROIZE) {
self.zeroize();
}
Ok(())
}
/// Function to retrieve data from the mailbox and compute it's hash.
///
/// # Arguments
///
/// * None
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
fn compute_mbox_hash(&mut self) {
let data_len = self.dlen.reg.get() as usize;
let totaldwords = data_len.div_ceil(RvSize::Word as usize);
let totalblocks = ((data_len + 16) + SHA512_BLOCK_SIZE) / SHA512_BLOCK_SIZE;
let totalbytes = totalblocks * SHA512_BLOCK_SIZE;
let mut block_arr: Vec<u8> = vec![0; totalbytes];
let start_address = self.start_address.reg.get();
// Read data from mailbox ram.
for idx in 0..totaldwords {
let byte_offset = idx << 2;
let word = self
.mailbox_ram
.read(RvSize::Word, start_address + byte_offset as u32)
.unwrap();
block_arr[byte_offset..byte_offset + 4].copy_from_slice(&word.to_le_bytes());
}
// Check ENDIAN_TOGGLE bit. If set to 1, data from the mailbox is in big-endian format.
// Convert it to little-endian for padding operation.
if self.mode.reg.read(ShaMode::ENDIAN_TOGGLE) == 1 {
block_arr.to_little_endian();
}
// Add block padding.
block_arr[data_len] = 0b1000_0000;
// Add block length.
let len = (data_len as u128) * 8;
block_arr[totalbytes - 16..].copy_from_slice(&len.to_be_bytes());
block_arr.to_big_endian();
// Set mode based on the mode reg (default to 384)
let mode =
if self.mode.reg.read(ShaMode::MODE) == ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value {
Sha512Mode::Sha512
} else {
Sha512Mode::Sha384
};
let mut sha = Sha512::new(mode);
for block_count in 0..totalblocks {
sha.update(array_ref![
block_arr,
block_count * SHA512_BLOCK_SIZE,
SHA512_BLOCK_SIZE
]);
}
let mut hash = [0u8; SHA512_HASH_SIZE];
sha.copy_hash(&mut hash);
// Place the hash in the DIGEST registers.
self.hash_lower
.data_mut()
.copy_from_slice(&hash[..SHA512_HASH_HALF_SIZE]);
self.hash_upper
.data_mut()
.copy_from_slice(&hash[SHA512_HASH_HALF_SIZE..]);
}
fn finalize_stream_hash(&mut self) {
self.sha_stream.finalize(self.dlen.reg.get());
let mut hash = [0u8; SHA512_HASH_SIZE];
self.sha_stream.copy_hash(&mut hash);
// Place the hash in the DIGEST registers.
self.hash_lower
.data_mut()
.copy_from_slice(&hash[..SHA512_HASH_HALF_SIZE]);
self.hash_upper
.data_mut()
.copy_from_slice(&hash[SHA512_HASH_HALF_SIZE..]);
self.op_complete();
}
/// Called by Bus::poll() to indicate that time has passed
fn poll(&mut self) {
if self.timer.fired(&mut self.op_complete_action) {
self.op_complete();
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
self.state_machine.process_event(Events::Reset).unwrap();
self.state_machine
.process_event(Events::RdLock(Owner(0)))
.unwrap();
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
// TODO: Reset registers
}
fn op_complete(&mut self) {
// Update the 'Valid' status bit
self.status.reg.modify(Status::VALID::SET);
}
/// Get the length of the hash
#[cfg(test)]
pub fn hash_len(&self) -> usize {
let mode = self.mode.reg.read(ShaMode::MODE);
if mode == ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value
|| mode == ShaMode::MODE::SHA512_ACC_MODE_SHA_STREAM_384.value
{
SHA384_HASH_SIZE
} else {
SHA512_HASH_SIZE
}
}
#[cfg(test)]
pub fn copy_hash(&self, hash_out: &mut [u8]) {
let mut hash = [0u8; SHA512_HASH_SIZE];
hash[..SHA512_HASH_HALF_SIZE].copy_from_slice(&self.hash_lower.data()[..]);
hash[SHA512_HASH_HALF_SIZE..].copy_from_slice(&self.hash_upper.data()[..]);
hash.iter()
.flat_map(|i| i.to_be_bytes())
.take(self.hash_len())
.zip(hash_out)
.for_each(|(src, dest)| *dest = src);
}
fn zeroize(&mut self) {
self.hash_lower.data_mut().fill(0);
self.hash_upper.data_mut().fill(0);
}
}
#[derive(Clone)]
pub struct Sha512Accelerator {
regs: Rc<RefCell<Sha512AcceleratorRegs>>,
}
impl Sha512Accelerator {
/// Create a new instance of SHA-512 Accelerator
pub fn new(clock: &Clock, mailbox_ram: MailboxRam) -> Self {
Self {
regs: Rc::new(RefCell::new(Sha512AcceleratorRegs::new(clock, mailbox_ram))),
}
}
}
impl Bus for Sha512Accelerator {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.regs.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
self.regs.borrow_mut().write(size, addr, val)
}
fn poll(&mut self) {
self.regs.borrow_mut().poll();
}
fn warm_reset(&mut self) {
self.regs.borrow_mut().warm_reset();
}
fn update_reset(&mut self) {
self.regs.borrow_mut().update_reset();
}
}
pub struct Owner(pub u32);
statemachine! {
transitions: {
// CurrentState Event [guard] / action = NextState
*Idle + RdLock(Owner) [is_not_locked] / lock = RdyForExc,
RdyForExc + WrLock(Owner) [is_locked] / unlock = Idle,
Idle + Reset / reset = Idle,
RdyForExc + Reset / reset = Idle
}
}
/// State machine extended variables.
pub struct Context {
/// lock state
pub locked: u32,
/// Who acquired the lock.
pub user: u32,
}
impl Context {
fn new() -> Self {
Self { locked: 0, user: 0 }
}
}
impl StateMachineContext for Context {
// guards
fn is_not_locked(&self, _user: &Owner) -> Result<bool, ()> {
if self.locked == 1 {
// no transition
Err(())
} else {
Ok(true)
}
}
fn is_locked(&self, _user: &Owner) -> Result<bool, ()> {
if self.locked != 0 {
Ok(true)
} else {
// no transition
Err(())
}
}
fn reset(&mut self) -> Result<(), ()> {
self.locked = 0;
Ok(())
}
fn lock(&mut self, user: Owner) -> Result<(), ()> {
self.locked = 1;
self.user = user.0;
Ok(())
}
fn unlock(&mut self, _user: Owner) -> Result<(), ()> {
self.locked = 0;
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::{sha512_acc::*, MailboxRam};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvAddr;
use tock_registers::registers::InMemoryRegister;
const OFFSET_LOCK: RvAddr = 0x00;
const OFFSET_MODE: RvAddr = 0x08;
const OFFSET_START_ADDRESS: RvAddr = 0x0c;
const OFFSET_DLEN: RvAddr = 0x10;
const OFFSET_DATAIN: RvAddr = 0x14;
const OFFSET_EXECUTE: RvAddr = 0x18;
const OFFSET_STATUS: RvAddr = 0x1c;
fn test_sha_accelerator(data: &[u8], expected: &[u8], start_address: usize, sha_mode: u32) {
// Write to the mailbox.
let mut mb_ram = MailboxRam::default();
if !data.is_empty() {
assert!((start_address % 4) == 0);
let mut data_word_multiples = vec![0u8; ((start_address + data.len() + 3) / 4) * 4];
data_word_multiples[start_address..start_address + data.len()].copy_from_slice(data);
for idx in (0..data_word_multiples.len()).step_by(4) {
// Convert to big-endian.
let dword = ((data_word_multiples[idx] as u32) << 24)
| ((data_word_multiples[idx + 1] as u32) << 16)
| ((data_word_multiples[idx + 2] as u32) << 8)
| (data_word_multiples[idx + 3] as u32);
mb_ram.write(RvSize::Word, idx as u32, dword).unwrap();
}
}
let clock = Clock::new();
let mut sha_accl = Sha512Accelerator::new(&clock, mb_ram.clone());
// Unlock the initial state
sha_accl.write(RvSize::Word, OFFSET_LOCK, 1).unwrap();
// Acquire the accelerator lock.
loop {
let lock = sha_accl.read(RvSize::Word, OFFSET_LOCK).unwrap();
if lock == 0 {
break;
}
}
// Confirm it is locked
let lock = sha_accl.read(RvSize::Word, OFFSET_LOCK).unwrap();
assert_eq!(lock, 1);
// Set the mode.
let mode = InMemoryRegister::<u32, ShaMode::Register>::new(0);
mode.write(ShaMode::MODE.val(sha_mode) + ShaMode::ENDIAN_TOGGLE.val(1));
assert_eq!(
sha_accl.write(RvSize::Word, OFFSET_MODE, mode.get()).ok(),
Some(())
);
// Set the start address.
assert_eq!(
sha_accl
.write(
RvSize::Word,
OFFSET_START_ADDRESS,
start_address.try_into().unwrap()
)
.ok(),
Some(())
);
// Set data length.
assert_eq!(
sha_accl
.write(RvSize::Word, OFFSET_DLEN, data.len() as u32)
.ok(),
Some(())
);
// Trigger the accelerator by writing to the execute register.
let execute = InMemoryRegister::<u32, Execute::Register>::new(0);
execute.write(Execute::EXECUTE.val(1));
assert_eq!(
sha_accl
.write(RvSize::Word, OFFSET_EXECUTE, execute.get())
.ok(),
Some(())
);
// Wait for operation to complete.
loop {
let status = InMemoryRegister::<u32, Status::Register>::new(
sha_accl.read(RvSize::Word, OFFSET_STATUS).unwrap(),
);
if status.is_set(Status::VALID) {
break;
}
clock.increment_and_process_timer_actions(1, &mut sha_accl);
}
// Read the hash.
let mut hash: [u8; SHA512_HASH_SIZE] = [0; SHA512_HASH_SIZE];
sha_accl.regs.borrow().copy_hash(&mut hash);
// Release the lock.
assert_eq!(sha_accl.write(RvSize::Word, OFFSET_LOCK, 1).ok(), Some(()));
hash.to_little_endian();
// Choose length based on mode, default to 512
let digest_length = if sha_mode == ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value {
SHA384_HASH_SIZE
} else {
SHA512_HASH_SIZE
};
assert_eq!(&hash[..digest_length], expected);
}
#[test]
fn test_accelerator_sha384_1() {
let data = "abc".as_bytes();
let expected: [u8; SHA384_HASH_SIZE] = [
0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B, 0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6,
0x50, 0x07, 0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63, 0x1A, 0x8B, 0x60, 0x5A,
0x43, 0xFF, 0x5B, 0xED, 0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23, 0x58, 0xBA,
0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7,
];
test_sha_accelerator(
data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha384_2() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x33, 0x91, 0xFD, 0xDD, 0xFC, 0x8D, 0xC7, 0x39, 0x37, 0x07, 0xA6, 0x5B, 0x1B, 0x47,
0x09, 0x39, 0x7C, 0xF8, 0xB1, 0xD1, 0x62, 0xAF, 0x05, 0xAB, 0xFE, 0x8F, 0x45, 0x0D,
0xE5, 0xF3, 0x6B, 0xC6, 0xB0, 0x45, 0x5A, 0x85, 0x20, 0xBC, 0x4E, 0x6F, 0x5F, 0xE9,
0x5B, 0x1F, 0xE3, 0xC8, 0x45, 0x2B,
];
let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes();
test_sha_accelerator(
data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha384_3() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8, 0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD,
0x1B, 0x47, 0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2, 0x2F, 0xA0, 0x80, 0x86,
0xE3, 0xB0, 0xF7, 0x12, 0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9, 0x66, 0xC3,
0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39,
];
let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes();
test_sha_accelerator(
data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha384_4() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x55, 0x23, 0xcf, 0xb7, 0x7f, 0x9c, 0x55, 0xe0, 0xcc, 0xaf, 0xec, 0x5b, 0x87, 0xd7,
0x9c, 0xde, 0x64, 0x30, 0x12, 0x28, 0x3b, 0x71, 0x18, 0x8e, 0x40, 0x8c, 0x5a, 0xea,
0xe9, 0x19, 0xa3, 0xf2, 0x93, 0x37, 0x57, 0x4d, 0x5c, 0x72, 0x9b, 0x33, 0x9d, 0x95,
0x53, 0x98, 0x4a, 0xb0, 0x01, 0x4e,
];
let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefgh".as_bytes();
test_sha_accelerator(
data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha384_5() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x9c, 0x2f, 0x48, 0x76, 0x0d, 0x13, 0xac, 0x42, 0xea, 0xd1, 0x96, 0xe5, 0x4d, 0xcb,
0xaa, 0x5e, 0x58, 0x72, 0x06, 0x62, 0xa9, 0x6b, 0x91, 0x94, 0xe9, 0x81, 0x33, 0x29,
0xbd, 0xb6, 0x27, 0xc7, 0xc1, 0xca, 0x77, 0x15, 0x31, 0x16, 0x32, 0xc1, 0x39, 0xe7,
0xa3, 0x59, 0x14, 0xfc, 0x1e, 0xcd,
];
let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz".as_bytes();
test_sha_accelerator(
data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha384_6() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x33, 0x91, 0xFD, 0xDD, 0xFC, 0x8D, 0xC7, 0x39, 0x37, 0x07, 0xA6, 0x5B, 0x1B, 0x47,
0x09, 0x39, 0x7C, 0xF8, 0xB1, 0xD1, 0x62, 0xAF, 0x05, 0xAB, 0xFE, 0x8F, 0x45, 0x0D,
0xE5, 0xF3, 0x6B, 0xC6, 0xB0, 0x45, 0x5A, 0x85, 0x20, 0xBC, 0x4E, 0x6F, 0x5F, 0xE9,
0x5B, 0x1F, 0xE3, 0xC8, 0x45, 0x2B,
];
let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes();
test_sha_accelerator(
data,
&expected,
4,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
// SHA512 test vectors taken from https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/shs/shabytetestvectors.zip
#[test]
fn test_accelerator_sha384_no_data() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E, 0xB1, 0xB1,
0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43, 0x4C, 0x0C, 0xC7, 0xBF,
0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF, 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A,
0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B,
];
let data = [];
test_sha_accelerator(
&data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha384_mailbox_max_size() {
let expected: [u8; SHA384_HASH_SIZE] = [
0x9B, 0xF0, 0x66, 0xF5, 0x2C, 0xD8, 0x58, 0x8B, 0x21, 0x31, 0xD1, 0xD2, 0xDA, 0x24,
0xB2, 0xAD, 0xAC, 0xB8, 0xAD, 0x3E, 0xFC, 0x36, 0xF3, 0xCB, 0x77, 0x97, 0x72, 0xC1,
0x93, 0xA0, 0xB1, 0x40, 0xB1, 0x20, 0xBD, 0x13, 0xDF, 0xCB, 0x3E, 0x5E, 0x8C, 0x66,
0xB6, 0x85, 0x26, 0xD5, 0x31, 0x50,
];
let data: [u8; MAX_MAILBOX_CAPACITY_BYTES] = [0u8; MAX_MAILBOX_CAPACITY_BYTES];
test_sha_accelerator(
&data,
&expected,
0,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_384.value,
);
}
#[test]
fn test_accelerator_sha512_1() {
let expected: [u8; SHA512_HASH_SIZE] = [
0x55, 0x58, 0x6e, 0xbb, 0xa4, 0x87, 0x68, 0xae, 0xb3, 0x23, 0x65, 0x5a, 0xb6, 0xf4,
0x29, 0x8f, 0xc9, 0xf6, 0x70, 0x96, 0x4f, 0xc2, 0xe5, 0xf2, 0x73, 0x1e, 0x34, 0xdf,
0xa4, 0xb0, 0xc0, 0x9e, 0x6e, 0x1e, 0x12, 0xe3, 0xd7, 0x28, 0x6b, 0x31, 0x45, 0xc6,
0x1c, 0x20, 0x47, 0xfb, 0x1a, 0x2a, 0x12, 0x97, 0xf3, 0x6d, 0xa6, 0x41, 0x60, 0xb3,
0x1f, 0xa4, 0xc8, 0xc2, 0xcd, 0xdd, 0x2f, 0xb4,
];
let data = [0x90, 0x83];
test_sha_accelerator(
&data,
&expected,
4,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value,
);
}
#[test]
fn test_accelerator_sha512_2() {
let expected: [u8; SHA512_HASH_SIZE] = [
0xd3, 0x9e, 0xce, 0xdf, 0xe6, 0xe7, 0x05, 0xa8, 0x21, 0xae, 0xe4, 0xf5, 0x8b, 0xfc,
0x48, 0x9c, 0x3d, 0x94, 0x33, 0xeb, 0x4a, 0xc1, 0xb0, 0x3a, 0x97, 0xe3, 0x21, 0xa2,
0x58, 0x6b, 0x40, 0xdd, 0x05, 0x22, 0xf4, 0x0f, 0xa5, 0xae, 0xf3, 0x6a, 0xff, 0xf5,
0x91, 0xa7, 0x8c, 0x91, 0x6b, 0xfc, 0x6d, 0x1c, 0xa5, 0x15, 0xc4, 0x98, 0x3d, 0xd8,
0x69, 0x5b, 0x1e, 0xc7, 0x95, 0x1d, 0x72, 0x3e,
];
let data = [0xeb, 0x0c, 0xa9, 0x46, 0xc1];
test_sha_accelerator(
&data,
&expected,
4,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value,
);
}
#[test]
fn test_accelerator_sha512_3() {
let expected: [u8; SHA512_HASH_SIZE] = [
0xa3, 0x94, 0x1d, 0xef, 0x28, 0x03, 0xc8, 0xdf, 0xc0, 0x8f, 0x20, 0xc0, 0x6b, 0xa7,
0xe9, 0xa3, 0x32, 0xae, 0x0c, 0x67, 0xe4, 0x7a, 0xe5, 0x73, 0x65, 0xc2, 0x43, 0xef,
0x40, 0x05, 0x9b, 0x11, 0xbe, 0x22, 0xc9, 0x1d, 0xa6, 0xa8, 0x0c, 0x2c, 0xff, 0x07,
0x42, 0xa8, 0xf4, 0xbc, 0xd9, 0x41, 0xbd, 0xee, 0x0b, 0x86, 0x1e, 0xc8, 0x72, 0xb2,
0x15, 0x43, 0x3c, 0xe8, 0xdc, 0xf3, 0xc0, 0x31,
];
let data = [0x6f, 0x8d, 0x58, 0xb7, 0xca, 0xb1, 0x88, 0x8c];
test_sha_accelerator(
&data,
&expected,
4,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value,
);
}
#[test]
fn test_accelerator_sha512_4() {
let expected: [u8; SHA512_HASH_SIZE] = [
0x29, 0x9e, 0x0d, 0xaf, 0x66, 0x05, 0xe5, 0xb0, 0xc3, 0x0e, 0x1e, 0xc8, 0xbb, 0x98,
0xe7, 0xa3, 0xbd, 0x7b, 0x33, 0xb3, 0x88, 0xbd, 0xb4, 0x57, 0x45, 0x2d, 0xab, 0x50,
0x95, 0x94, 0x40, 0x6c, 0x8e, 0x7b, 0x84, 0x1e, 0x6f, 0x4e, 0x75, 0xc8, 0xd6, 0xfb,
0xd6, 0x14, 0xd5, 0xeb, 0x9e, 0x56, 0xc3, 0x59, 0xbf, 0xaf, 0xb4, 0x28, 0x57, 0x54,
0x78, 0x7a, 0xb7, 0x2b, 0x46, 0xdd, 0x33, 0xf0,
];
let data = [
0x3e, 0xdf, 0x93, 0x25, 0x13, 0x49, 0xd2, 0x28, 0x06, 0xbe, 0xd2, 0x53, 0x45, 0xfd,
0x5c, 0x19, 0x0a, 0xac, 0x96, 0xd6, 0xcd, 0xb2, 0xd7, 0x58, 0xb8,
];
test_sha_accelerator(
&data,
&expected,
4,
ShaMode::MODE::SHA512_ACC_MODE_MBOX_512.value,
);
}
#[test]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/csrng.rs | sw-emulator/lib/periph/src/csrng.rs | // Licensed under the Apache-2.0 license
use caliptra_emu_bus::{BusError, ReadOnlyRegister, WriteOnlyRegister};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use caliptra_registers::entropy_src::regs::{
AdaptpHiThresholdsReadVal, AdaptpLoThresholdsReadVal, ConfReadVal, HealthTestWindowsReadVal,
RepcntThresholdsReadVal,
};
use sha3::{Digest, Sha3_384};
use std::mem;
use tock_registers::interfaces::Readable;
mod health_test;
use health_test::HealthTester;
mod ctr_drbg;
use ctr_drbg::{Block, CtrDrbg, Instantiate, Seed, SEED_LEN_BYTES};
use crate::helpers::bytes_from_words_be;
type Word = u32;
const BITS_PER_NIBBLE: usize = 4;
const WORD_SIZE_BYTES: usize = mem::size_of::<Word>();
#[derive(Bus)]
pub struct Csrng {
// CSRNG registers
#[register(offset = 0x14)]
ctrl: u32,
#[register(offset = 0x18, write_fn = cmd_req_write)]
cmd_req: WriteOnlyRegister<u32>,
#[register(offset = 0x2c)]
sw_cmd_sts: ReadOnlyRegister<u32>,
#[register(offset = 0x30, read_fn = genbits_vld_read)]
genbits_vld: ReadOnlyRegister<u32>,
#[register(offset = 0x34, read_fn = genbits_read)]
genbits: ReadOnlyRegister<u32>,
#[register(offset = 0x54)]
err_code: ReadOnlyRegister<u32>,
// Entropy Source registers
#[register(offset = 0x1020, write_fn = module_enable_write)]
module_enable: u32,
#[register(offset = 0x1024)]
conf: u32,
#[register(offset = 0x1030)]
health_test_windows: ReadOnlyRegister<u32>,
#[register(offset = 0x1034, write_fn = repcnt_thresholds_write)]
repcnt_thresholds: u32,
#[register(offset = 0x103c, write_fn = adaptp_hi_thresholds_write)]
adaptp_hi_thresholds: u32,
#[register(offset = 0x1040, write_fn = adaptp_lo_thresholds_write)]
adaptp_lo_thresholds: u32,
#[register(offset = 0x10a4, read_fn = alert_summary_fail_counts_read)]
alert_summary_fail_counts: ReadOnlyRegister<u32>,
#[register(offset = 0x10a8, read_fn = alert_fail_counts_read)]
alert_fail_counts: ReadOnlyRegister<u32>,
#[register(offset = 0x10e0, read_fn = main_sm_state_read)]
main_sm_state: ReadOnlyRegister<u32>,
cmd_req_state: CmdReqState,
seed: Vec<u32>,
update: Vec<u32>,
ctr_drbg: CtrDrbg,
words: Words,
health_tester: HealthTester,
}
impl Csrng {
pub fn new(itrng_nibbles: Box<dyn Iterator<Item = u8>>) -> Self {
Self {
// These reset values come from register definitions
ctrl: 0x999,
cmd_req: WriteOnlyRegister::new(0),
sw_cmd_sts: ReadOnlyRegister::new(0b110), // cmd_rdy=1, cmd_ack=1, cmd_sts=0
genbits_vld: ReadOnlyRegister::new(0b01),
genbits: ReadOnlyRegister::new(0),
err_code: ReadOnlyRegister::new(0),
module_enable: 0x9,
conf: 0x909099,
health_test_windows: ReadOnlyRegister::new(0x600200),
repcnt_thresholds: 0xffffffff,
adaptp_hi_thresholds: 0xffffffff,
adaptp_lo_thresholds: 0,
alert_summary_fail_counts: ReadOnlyRegister::new(0),
alert_fail_counts: ReadOnlyRegister::new(0),
main_sm_state: ReadOnlyRegister::new(0x2c), // StartupHTStart, entropy_src_main_sm_pkg.sv
cmd_req_state: CmdReqState::NewCommand,
seed: vec![],
update: vec![],
ctr_drbg: CtrDrbg::new(),
words: Words::default(),
health_tester: HealthTester::new(itrng_nibbles),
}
}
fn cmd_req_write(&mut self, _: RvSize, data: RvData) -> Result<(), BusError> {
// Since the CMD_REQ register can be used to initiate new commands or
// supply words to an existing command, we need to track which "state"
// we're in for this register and branch accordingly.
match self.cmd_req_state {
CmdReqState::NewCommand => self.process_new_cmd(data),
CmdReqState::SeedWords { num_words } => {
self.seed.push(data);
if self.seed.len() == num_words {
self.ctr_drbg.instantiate(Instantiate::Words(&self.seed));
self.seed.clear();
self.cmd_req_state = CmdReqState::NewCommand;
}
}
CmdReqState::UpdateWords { num_words } => {
self.update.push(data);
if self.update.len() == num_words {
let seed32: [u32; SEED_LEN_BYTES / 4] =
self.update.as_slice().try_into().unwrap();
let seed = bytes_from_words_be(&seed32);
self.ctr_drbg.update(seed);
self.update.clear();
self.cmd_req_state = CmdReqState::NewCommand;
}
}
}
Ok(())
}
fn genbits_vld_read(&mut self, _: RvSize) -> Result<RvData, BusError> {
if self.words.is_empty() {
// Check if the CTR_DRBG has any bits for us.
if let Some(block) = self.ctr_drbg.pop_block() {
self.words = Words::new(block);
Ok(0b01)
} else {
Ok(0b00)
}
} else {
Ok(0b01)
}
}
fn genbits_read(&mut self, _: RvSize) -> Result<RvData, BusError> {
Ok(self.words.next().unwrap_or(0xCAFE_F00D))
}
fn module_enable_write(&mut self, _: RvSize, data: RvData) -> Result<(), BusError> {
self.module_enable = data;
if data == MultiBitBool::False as u32 {
return Ok(());
}
if ConfReadVal::from(self.conf).fips_enable() == MultiBitBool::False as u32 {
unimplemented!("emulation of non-FIPS mode");
}
self.health_tester.test_boot_window();
Ok(())
}
fn repcnt_thresholds_write(&mut self, _: RvSize, data: RvData) -> Result<(), BusError> {
self.health_tester
.repcnt
.set_threshold(RepcntThresholdsReadVal::from(data));
Ok(())
}
fn adaptp_hi_thresholds_write(&mut self, _: RvSize, data: RvData) -> Result<(), BusError> {
self.health_tester
.adaptp
.set_hi_threshold(AdaptpHiThresholdsReadVal::from(data));
Ok(())
}
fn adaptp_lo_thresholds_write(&mut self, _: RvSize, data: RvData) -> Result<(), BusError> {
self.health_tester
.adaptp
.set_lo_threshold(AdaptpLoThresholdsReadVal::from(data));
Ok(())
}
fn alert_summary_fail_counts_read(&mut self, _: RvSize) -> Result<RvData, BusError> {
let failures = self.health_tester.failures();
self.alert_summary_fail_counts = ReadOnlyRegister::new(failures);
Ok(failures)
}
fn alert_fail_counts_read(&mut self, _: RvSize) -> Result<RvData, BusError> {
// Don't have a `AlertFailCountsWriteVal` from ureg, so let's pack counts manually.
let adapt_lo = self.health_tester.adaptp.lo_failures().min(0xf) & 0xf;
let adapt_hi = self.health_tester.adaptp.hi_failures().min(0xf) & 0xf;
let repcnt = self.health_tester.repcnt.failures().min(0xf) & 0xf;
let fail_counts = (adapt_lo << 12) | (adapt_hi << 8) | (repcnt << 4);
self.alert_fail_counts = ReadOnlyRegister::new(fail_counts);
Ok(fail_counts)
}
fn main_sm_state_read(&mut self, _: RvSize) -> Result<RvData, BusError> {
// https://opentitan.org/book/hw/ip/entropy_src/doc/theory_of_operation.html#main-state-machine-diagram
// https://github.com/chipsalliance/caliptra-rtl/blob/main/src/entropy_src/rtl/entropy_src_main_sm_pkg.sv
const ALERT_HANG: u32 = 0x1fb;
const CONT_HT_RUNNING: u32 = 0x1a2;
let state = if self.health_tester.failures() > 0 {
ALERT_HANG
} else {
CONT_HT_RUNNING
};
self.main_sm_state = ReadOnlyRegister::new(state);
Ok(state)
}
fn process_new_cmd(&mut self, data: RvData) {
const INSTANTIATE: u32 = 1;
const GENERATE: u32 = 3;
const UPDATE: u32 = 4;
const UNINSTANTIATE: u32 = 5;
let acmd = data & 0xf;
let clen = (data >> 4) & 0xf;
let flag0 = (data >> 8) & 0xf;
let glen = (data >> 12) & 0x1fff;
match acmd {
INSTANTIATE => {
const FALSE: u32 = MultiBitBool::False as u32;
const TRUE: u32 = MultiBitBool::True as u32;
// https://opentitan.org/book/hw/ip/csrng/doc/theory_of_operation.html#command-description
match [flag0, clen] {
[FALSE, 0] => {
// Seed from entropy_src.
let seed = self.get_conditioned_seed();
self.ctr_drbg.instantiate(Instantiate::Bytes(&seed));
}
[FALSE, _] => unimplemented!("seed: entropy_src XOR constant"),
[TRUE, 0] => {
// Zero seed.
self.ctr_drbg.instantiate(Instantiate::default());
}
[TRUE, _] => {
self.cmd_req_state = CmdReqState::SeedWords {
num_words: clen as usize,
};
}
_ => unreachable!("invalid INSTANTIATE state: flag0={flag0}, clen={clen}"),
}
}
GENERATE => {
self.ctr_drbg.generate(glen as usize);
}
UNINSTANTIATE => {
self.ctr_drbg.uninstantiate();
}
UPDATE => {
self.cmd_req_state = CmdReqState::UpdateWords {
num_words: SEED_LEN_BYTES / 4,
};
}
_ => {
unimplemented!("CSRNG cmd: {acmd}");
}
}
}
fn get_conditioned_seed(&mut self) -> Seed {
// Replicate the logic in caliptra-rtl/src/entropy_src/rtl/entropy_src_core.sv.
const NUM_TEST_WINDOWS: usize = 2;
const BITS_PER_CYCLE: usize = 4;
const BITS_PER_BLOCK: usize = 8 * mem::size_of::<u64>();
let window_size_bits = {
let w = HealthTestWindowsReadVal::from(self.health_test_windows.reg.get());
BITS_PER_CYCLE * w.fips_window() as usize
};
let num_blocks = NUM_TEST_WINDOWS * window_size_bits / BITS_PER_BLOCK;
let mut hasher = Sha3_384::new();
for _ in 0..num_blocks {
// Update the hasher in 64-bit packed entropy blocks.
const NUM_NIBBLES: usize = BITS_PER_BLOCK / BITS_PER_NIBBLE;
let packed_entropy = (0..NUM_NIBBLES).fold(0, |packed, i| {
let nibble = self.health_tester.next().expect(
"itrng iterator should provide at least two 2048 bit windows in FIPS mode",
);
packed | (u64::from(nibble) << (i * BITS_PER_NIBBLE))
});
hasher.update(packed_entropy.to_le_bytes());
}
let mut digest = hasher.finalize();
digest.as_mut_slice().reverse();
digest
.as_slice()
.try_into()
.expect("SHA3-384 should generate a 384 bit seed from raw entropy nibbles")
}
}
#[derive(Default)]
struct Words {
block: Block,
cursor: usize,
}
impl Words {
pub fn new(block: Block) -> Self {
Self {
block,
cursor: block.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Iterator for Words {
type Item = Word;
fn next(&mut self) -> Option<Self::Item> {
if self.cursor == 0 {
None
} else {
// We have to return, in reverse order, the words within this block.
// Reverse order because of https://opentitan.org/book/hw/ip/csrng/doc/programmers_guide.html#endianness-and-known-answer-tests
let start = self.cursor - WORD_SIZE_BYTES;
let end = self.cursor;
let word = &self.block[start..end];
let word = word.try_into().expect("byte slice to 4-byte array");
let word = u32::from_be_bytes(word);
self.cursor = start;
Some(word)
}
}
}
impl ExactSizeIterator for Words {
fn len(&self) -> usize {
self.cursor / WORD_SIZE_BYTES
}
}
enum CmdReqState {
NewCommand,
SeedWords { num_words: usize },
UpdateWords { num_words: usize },
}
#[repr(u32)]
enum MultiBitBool {
False = 9,
True = 6,
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/key_vault.rs | sw-emulator/lib/periph/src/key_vault.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
key_vault.rs
Abstract:
File contains Key Vault Implementation
--*/
use bitfield::bitfield;
use caliptra_emu_bus::{Bus, BusError, ReadWriteMemory, ReadWriteRegisterArray};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use std::cell::RefCell;
use std::rc::Rc;
use tock_registers::{register_bitfields, LocalRegisterCopy};
pub mod constants {
#![allow(unused)]
// Key Vault
pub const KEY_CONTROL_REG_START_OFFSET: u32 = crate::KeyVault::KEY_CONTROL_REG_OFFSET;
pub const KEY_CONTROL_REG_END_OFFSET: u32 = KEY_CONTROL_REG_START_OFFSET
+ (crate::KeyVault::KEY_COUNT - 1) * crate::KeyVault::KEY_CONTROL_REG_WIDTH;
// PCR Vault
pub const PCR_SIZE_BYTES: usize = 48;
pub const PCR_SIZE_WORDS: usize = PCR_SIZE_BYTES / 4;
pub const PCR_COUNT: u32 = 32;
pub const PCR_CONTROL_REG_OFFSET: u32 = 0x2000;
pub const PCR_CONTROL_REG_WIDTH: u32 = 0x4;
pub const PCR_CONTROL_REG_START_OFFSET: u32 = PCR_CONTROL_REG_OFFSET;
pub const PCR_CONTROL_REG_END_OFFSET: u32 =
PCR_CONTROL_REG_START_OFFSET + (PCR_COUNT - 1) * PCR_CONTROL_REG_WIDTH;
pub const PCR_REG_OFFSET: u32 = 0x2600;
// Sticky Data Vault. Unlocked on Cold Reset.
pub const STICKY_DATAVAULT_CTRL_REG_COUNT: u32 = 10;
pub const STICKY_DATAVAULT_CTRL_REG_WIDTH: u32 = 4;
pub const STICKY_DATAVAULT_CTRL_REG_START_OFFSET: u32 = 0x4000;
pub const STICKY_DATAVAULT_CTRL_REG_END_OFFSET: u32 = STICKY_DATAVAULT_CTRL_REG_START_OFFSET
+ (STICKY_DATAVAULT_CTRL_REG_COUNT - 1) * STICKY_DATAVAULT_CTRL_REG_WIDTH;
pub const STICKY_DATAVAULT_ENTRY_COUNT: u32 = 10;
pub const STICKY_DATAVAULT_ENTRY_WIDTH: u32 = 48;
pub const STICKY_DATAVAULT_ENTRY_WORD_START_OFFSET: u32 = 0x4028;
pub const STICKY_DATAVAULT_ENTRY_WORD_END_OFFSET: u32 = STICKY_DATAVAULT_ENTRY_WORD_START_OFFSET
+ STICKY_DATAVAULT_ENTRY_COUNT * STICKY_DATAVAULT_ENTRY_WIDTH
- 4;
// Lockable Data Vault. Unlocked on Warm Reset.
pub const DATAVAULT_CTRL_REG_COUNT: u32 = 10;
pub const DATAVAULT_CTRL_REG_WIDTH: u32 = 4;
pub const DATAVAULT_CTRL_REG_START_OFFSET: u32 = 0x4208;
pub const DATAVAULT_CTRL_REG_END_OFFSET: u32 =
DATAVAULT_CTRL_REG_START_OFFSET + (DATAVAULT_CTRL_REG_COUNT - 1) * DATAVAULT_CTRL_REG_WIDTH;
pub const DATAVAULT_ENTRY_COUNT: u32 = 10;
pub const DATAVAULT_ENTRY_WIDTH: u32 = 48;
pub const DATAVAULT_ENTRY_WORD_START_OFFSET: u32 = 0x4230;
pub const DATAVAULT_ENTRY_WORD_END_OFFSET: u32 =
DATAVAULT_ENTRY_WORD_START_OFFSET + DATAVAULT_ENTRY_COUNT * DATAVAULT_ENTRY_WIDTH - 4;
// Lockable Scratch. Unlocked on Warm Reset.
pub const LOCKABLE_SCRATCH_CTRL_REG_COUNT: u32 = 10;
pub const LOCKABLE_SCRATCH_CTRL_REG_WIDTH: u32 = 4;
pub const LOCKABLE_SCRATCH_CTRL_REG_START_OFFSET: u32 = 0x4410;
pub const LOCKABLE_SCRATCH_CTRL_REG_END_OFFSET: u32 = LOCKABLE_SCRATCH_CTRL_REG_START_OFFSET
+ (LOCKABLE_SCRATCH_CTRL_REG_COUNT - 1) * LOCKABLE_SCRATCH_CTRL_REG_WIDTH;
pub const LOCKABLE_SCRATCH_REG_COUNT: u32 = 10;
pub const LOCKABLE_SCRATCH_REG_WIDTH: u32 = 4;
pub const LOCKABLE_SCRATCH_REG_START_OFFSET: u32 = 0x4438;
pub const LOCKABLE_SCRATCH_REG_END_OFFSET: u32 = LOCKABLE_SCRATCH_REG_START_OFFSET
+ (LOCKABLE_SCRATCH_REG_COUNT - 1) * LOCKABLE_SCRATCH_REG_WIDTH;
// Non-Sticky Generic Scratch. Unlocked and Cleared on Warm Reset.
pub const NONSTICKY_GENERIC_SCRATCH_REG_COUNT: u32 = 8;
pub const NONSTICKY_GENERIC_SCRATCH_REG_WIDTH: u32 = 4;
pub const NONSTICKY_GENERIC_SCRATCH_REG_START_OFFSET: u32 = 0x4460;
pub const NONSTICKY_GENERIC_SCRATCH_REG_END_OFFSET: u32 =
NONSTICKY_GENERIC_SCRATCH_REG_START_OFFSET
+ (NONSTICKY_GENERIC_SCRATCH_REG_COUNT - 1) * NONSTICKY_GENERIC_SCRATCH_REG_WIDTH;
// Sticky Lockable Scratch. Unlocked on Cold Reset.
pub const STICKY_LOCKABLE_SCRATCH_CTRL_REG_COUNT: u32 = 8;
pub const STICKY_LOCKABLE_SCRATCH_CTRL_REG_WIDTH: u32 = 4;
pub const STICKY_LOCKABLE_SCRATCH_CTRL_REG_START_OFFSET: u32 = 0x4480;
pub const STICKY_LOCKABLE_SCRATCH_CTRL_REG_END_OFFSET: u32 =
STICKY_LOCKABLE_SCRATCH_CTRL_REG_START_OFFSET
+ (STICKY_LOCKABLE_SCRATCH_CTRL_REG_COUNT - 1) * STICKY_LOCKABLE_SCRATCH_CTRL_REG_WIDTH;
pub const STICKY_LOCKABLE_SCRATCH_REG_COUNT: u32 = 8;
pub const STICKY_LOCKABLE_SCRATCH_REG_WIDTH: u32 = 4;
pub const STICKY_LOCKABLE_SCRATCH_REG_START_OFFSET: u32 = 0x44a0;
pub const STICKY_LOCKABLE_SCRATCH_REG_END_OFFSET: u32 = STICKY_LOCKABLE_SCRATCH_REG_START_OFFSET
+ (STICKY_LOCKABLE_SCRATCH_REG_COUNT - 1) * STICKY_LOCKABLE_SCRATCH_REG_WIDTH;
/// PCR Register Size
pub const PCR_REG_SIZE: usize = 0x600;
pub const PCR_REG_SIZE_WORDS: usize = 0x600 >> 2;
/// PCR Control register reset value
pub const PCR_CONTROL_REG_RESET_VAL: u32 = 0;
/// Key Memory Size
pub const KEY_REG_SIZE: usize = 0x800;
/// Key control register reset value
pub const KEY_CONTROL_REG_RESET_VAL: u32 = 0;
/// Sticky DataVault Control Register Reset Value.
pub const STICKY_DATAVAULT_CTRL_REG_RESET_VAL: u32 = 0x0;
/// Non-Sticky DataVault Control Register Reset Value.
pub const DATAVAULT_CTRL_REG_RESET_VAL: u32 = 0x0;
/// Non-Sticky Lockable Scratch Control Register Reset Value.
pub const LOCKABLE_SCRATCH_CTRL_REG_RESET_VAL: u32 = 0x0;
/// Sticky DataVault Entry Size.
pub const STICKY_DATAVAULT_ENTRY_SIZE_WORDS: usize = 48 >> 2;
/// Sticky DataVault Size.
pub const STICKY_DATAVAULT_SIZE_WORDS: usize = 0x1e0 >> 2;
/// Non-Sticky DataVault Entry Size.
pub const NONSTICKY_DATAVAULT_ENTRY_SIZE_WORDS: usize = 48 >> 2;
/// Non-Sticky Entry Size.
pub const DATAVAULT_SIZE_WORDS: usize = 0x1e0 >> 2;
/// Sticky Lockable Scratch Control Register Reset Value.
pub const STICKY_LOCKABLE_SCRATCH_CTRL_REG_RESET_VAL: u32 = 0x0;
}
#[derive(Clone)]
pub struct KeyVault {
regs: Rc<RefCell<KeyVaultRegs>>,
}
impl KeyVault {
pub const PCR_SIZE: usize = 48;
pub const KEY_COUNT: u32 = 24;
pub const KEY_SIZE: usize = 64;
pub const KEY_CONTROL_REG_OFFSET: u32 = 0;
pub const KEY_CONTROL_REG_WIDTH: u32 = 0x4;
/// Create a new instance of KeyVault
pub fn new() -> Self {
Self {
regs: Rc::new(RefCell::new(KeyVaultRegs::new())),
}
}
/// Internal emulator interface to read key from key vault
pub fn read_key(
&self,
key_id: u32,
desired_usage: KeyUsage,
) -> Result<[u8; KeyVault::KEY_SIZE], BusError> {
self.regs.borrow().read_key(key_id, desired_usage)
}
/// Internal emulator interface to read key from key vault, make sure not to export the keys
pub fn read_key_locked(
&self,
key_id: u32,
desired_usage: KeyUsage,
) -> Result<[u8; KeyVault::KEY_SIZE], BusError> {
self.regs.borrow().read_key_locked(key_id, desired_usage)
}
pub fn read_key_as_data(
&self,
key_id: u32,
desired_usage: KeyUsage,
) -> Result<Vec<u8>, BusError> {
self.regs.borrow().read_key_as_data(key_id, desired_usage)
}
/// Internal emulator interface to write key to key vault
pub fn write_key(&mut self, key_id: u32, key: &[u8], key_usage: u32) -> Result<(), BusError> {
self.regs.borrow_mut().write_key(key_id, key, key_usage)
}
/// Internal emulator interface to read pcr from key vault
pub fn read_pcr(&self, pcr_id: u32) -> [u8; constants::PCR_SIZE_BYTES] {
self.regs.borrow().read_pcr(pcr_id)
}
/// Internal emulator interface to write pcr to key vault
pub fn write_pcr(
&mut self,
pcr_id: u32,
pcr: &[u8; constants::PCR_SIZE_BYTES],
) -> Result<(), BusError> {
self.regs.borrow_mut().write_pcr(pcr_id, pcr)
}
pub fn clear_keys_with_debug_values(&mut self, sel_debug_value: bool) {
self.regs
.borrow_mut()
.clear_with_debug_values(sel_debug_value);
}
}
impl Default for KeyVault {
fn default() -> Self {
Self::new()
}
}
impl Bus for KeyVault {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
self.regs.borrow_mut().read(size, addr)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
self.regs.borrow_mut().write(size, addr, val)
}
fn warm_reset(&mut self) {
self.regs.borrow_mut().warm_reset();
}
fn update_reset(&mut self) {
self.regs.borrow_mut().update_reset();
}
}
bitfield! {
/// Key Usage
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub struct KeyUsage(u32);
/// Flag indicating if the key can be used as HMAC key
pub hmac_key, set_hmac_key: 0;
/// Flag indicating if the key can be used as HMAC data
pub hmac_data, set_hmac_data: 1;
/// Flag indicating if the key can be used as MLDSA seed
pub mldsa_seed, set_mldsa_key_gen_seed: 2;
/// Flag indicating if the key can be used as ECC Private Key
pub ecc_private_key, set_ecc_private_key: 3;
/// Flag indicating if the key can be used as ECC Key Generation Seed
pub ecc_key_gen_seed, set_ecc_key_gen_seed: 4;
/// Flag indicating if the key can be used as AES key.
pub aes_key, set_aes_key: 5;
/// Flag indicating if the key can be used as ML-KEM seed
pub mlkem_seed, set_mlkem_seed: 6;
/// Flag indicating if the key can be used as ML-KEM message
pub mlkem_msg, set_mlkem_msg: 7;
}
impl From<KeyUsage> for u32 {
/// Converts to this type from the input type.
fn from(key_usage: KeyUsage) -> Self {
key_usage.0
}
}
register_bitfields! [
u32,
/// KV Control Register Fields
pub KV_CONTROL [
WRITE_LOCK OFFSET(0) NUMBITS(1) [],
USE_LOCK OFFSET(1) NUMBITS(1) [],
CLEAR OFFSET(2) NUMBITS(1) [],
RSVD0 OFFSET(3) NUMBITS(1) [],
RSVD1 OFFSET(4) NUMBITS(5) [],
USAGE OFFSET(9) NUMBITS(8) [],
LAST_DWORD OFFSET(17) NUMBITS(4) [],
RSVD OFFSET(21) NUMBITS(11) [],
],
/// Clear Secrets Register Fields
pub CLEAR_SECRETS [
SEL_DEBUG_VALUE OFFSET(0) NUMBITS(1) [],
WR_DEBUG_VALUES OFFSET(1) NUMBITS(1) [],
RSVD OFFSET(2) NUMBITS(30) [],
],
/// DataVault Control Register Fields
pub DV_CONTROL [
LOCK_ENTRY OFFSET(0) NUMBITS(1) [],
RSVD OFFSET(1) NUMBITS(31) [],
],
/// PCR Control Register Fields
pub PV_CONTROL [
LOCK OFFSET(0) NUMBITS(1) [],
CLEAR OFFSET(1) NUMBITS(1) [],
RSVD0 OFFSET(2) NUMBITS(1) [],
RSVD1 OFFSET(3) NUMBITS(5) [],
RSVD OFFSET(8) NUMBITS(24) [],
],
];
use constants::*;
use crate::helpers::{bytes_from_words_le, words_from_bytes_le};
/// Key Vault Peripheral
#[derive(Bus)]
#[warm_reset_fn(warm_reset)]
#[update_reset_fn(update_reset)]
pub struct KeyVaultRegs {
/// Key Control Registers
#[register_array(offset = 0x0000_0000, write_fn = write_key_ctrl)]
key_control:
ReadWriteRegisterArray<u32, { KeyVault::KEY_COUNT as usize }, KV_CONTROL::Register>,
/// Key Registers
keys: ReadWriteMemory<{ KEY_REG_SIZE }>,
/// PCR Control Registers
#[register_array(offset = 0x0000_2000, write_fn = write_pcr_ctrl)]
pcr_control: ReadWriteRegisterArray<u32, { PCR_COUNT as usize }, PV_CONTROL::Register>,
/// PCR Registers
#[register_array(offset = 0x0000_2600)]
pcrs: [u32; PCR_REG_SIZE_WORDS],
/// Sticky Data Vault Control Registers
#[register_array(offset = 0x0000_4000, write_fn = write_sticky_datavault_ctrl)]
sticky_datavault_control: ReadWriteRegisterArray<
u32,
{ STICKY_DATAVAULT_CTRL_REG_COUNT as usize },
DV_CONTROL::Register,
>,
/// Sticky DataVault Entry Registers.
#[register_array(offset = 0x0000_4028, write_fn = write_sticky_datavault_entry)]
sticky_datavault_entry: [u32; STICKY_DATAVAULT_SIZE_WORDS],
/// Non-Sticky Data Vault Control Registers
#[register_array(offset = 0x0000_4208, write_fn = write_nonsticky_datavault_ctrl)]
datavault_control:
ReadWriteRegisterArray<u32, { DATAVAULT_CTRL_REG_COUNT as usize }, DV_CONTROL::Register>,
/// Non-Sticky DataVault Entry Registers.
#[register_array(offset = 0x0000_4230, write_fn = write_nonsticky_datavault_entry)]
datavault_entry: [u32; DATAVAULT_SIZE_WORDS],
/// Non-Sticky Lockable Scratch Control Registers
#[register_array(offset = 0x0000_4410, write_fn = write_nonsticky_lockable_scratch_ctrl)]
lockable_scratch_control: ReadWriteRegisterArray<
u32,
{ LOCKABLE_SCRATCH_CTRL_REG_COUNT as usize },
DV_CONTROL::Register,
>,
/// Non-Sticky Lockable Scratch Registers.
#[register_array(offset = 0x0000_4438, write_fn = write_nonsticky_lockable_scratch)]
lockable_scratch: ReadWriteRegisterArray<u32, { LOCKABLE_SCRATCH_REG_COUNT as usize }>,
/// Non-Sticky Generic Scratch Registers.
#[register_array(offset = 0x0000_4460)]
nonsticky_generic_scratch:
ReadWriteRegisterArray<u32, { NONSTICKY_GENERIC_SCRATCH_REG_COUNT as usize }>,
/// Sticky Lockable Scratch Control Registers.
#[register_array(offset = 0x0000_4480, write_fn = write_sticky_lockable_scratch_ctrl)]
sticky_lockable_scratch_control: ReadWriteRegisterArray<
u32,
{ STICKY_LOCKABLE_SCRATCH_CTRL_REG_COUNT as usize },
DV_CONTROL::Register,
>,
/// Sticky Lockable Scratch Registers.
#[register_array(offset = 0x0000_44a0, write_fn = write_sticky_lockable_scratch)]
sticky_lockable_scratch:
ReadWriteRegisterArray<u32, { STICKY_LOCKABLE_SCRATCH_REG_COUNT as usize }>,
}
impl KeyVaultRegs {
/// Create a new instance of KeyVault registers
pub fn new() -> Self {
Self {
pcr_control: ReadWriteRegisterArray::new(PCR_CONTROL_REG_RESET_VAL),
pcrs: [0; PCR_REG_SIZE_WORDS],
key_control: ReadWriteRegisterArray::new(KEY_CONTROL_REG_RESET_VAL),
keys: ReadWriteMemory::new(),
sticky_datavault_control: ReadWriteRegisterArray::new(
STICKY_DATAVAULT_CTRL_REG_RESET_VAL,
),
datavault_control: ReadWriteRegisterArray::new(DATAVAULT_CTRL_REG_RESET_VAL),
lockable_scratch_control: ReadWriteRegisterArray::new(
LOCKABLE_SCRATCH_CTRL_REG_RESET_VAL,
),
sticky_datavault_entry: [0; STICKY_DATAVAULT_SIZE_WORDS],
datavault_entry: [0; DATAVAULT_SIZE_WORDS],
lockable_scratch: ReadWriteRegisterArray::new(0),
nonsticky_generic_scratch: ReadWriteRegisterArray::new(0),
sticky_lockable_scratch_control: ReadWriteRegisterArray::new(
STICKY_LOCKABLE_SCRATCH_CTRL_REG_RESET_VAL,
),
sticky_lockable_scratch: ReadWriteRegisterArray::new(0),
}
}
fn unlock_vault_registers(&mut self) {
// Unlock PCRs.
for pcr_ctrl_reg in self.pcr_control.iter_mut() {
pcr_ctrl_reg.modify(PV_CONTROL::LOCK::CLEAR);
}
// Unlock KV.
for kv_ctrl_reg in self.key_control.iter_mut() {
kv_ctrl_reg.modify(KV_CONTROL::WRITE_LOCK::CLEAR + KV_CONTROL::USE_LOCK::CLEAR);
}
// Unlock DV.
for dv_ctrl_reg in self.datavault_control.iter_mut() {
dv_ctrl_reg.modify(DV_CONTROL::LOCK_ENTRY::CLEAR);
}
// Unlock lockable scratch registers.
for lockable_scratch_ctrl_reg in self.lockable_scratch_control.iter_mut() {
lockable_scratch_ctrl_reg.modify(DV_CONTROL::LOCK_ENTRY::CLEAR);
}
}
/// Called by Bus::warm_reset() to indicate a warm reset
fn warm_reset(&mut self) {
self.unlock_vault_registers();
}
/// Called by Bus::update_reset() to indicate an update reset
fn update_reset(&mut self) {
self.unlock_vault_registers();
}
fn write_pcr_ctrl(&mut self, _size: RvSize, index: usize, val: u32) -> Result<(), BusError> {
let val = LocalRegisterCopy::<u32, PV_CONTROL::Register>::new(val);
let pcr_ctrl_reg = &mut self.pcr_control[index];
pcr_ctrl_reg.modify(
PV_CONTROL::LOCK.val(pcr_ctrl_reg.read(PV_CONTROL::LOCK) | val.read(PV_CONTROL::LOCK)),
);
if pcr_ctrl_reg.read(PV_CONTROL::LOCK) == 0 && val.is_set(PV_CONTROL::CLEAR) {
let pcr_start = index * constants::PCR_SIZE_WORDS;
self.pcrs[pcr_start..(pcr_start + PCR_SIZE_WORDS)].fill(0);
}
Ok(())
}
// Does not write to usage, usage bits aren't directly writable outside of
// key creation.
fn write_key_ctrl(&mut self, _size: RvSize, index: usize, val: u32) -> Result<(), BusError> {
let val = LocalRegisterCopy::<u32, KV_CONTROL::Register>::new(val);
let key_ctrl_reg = &mut self.key_control[index];
key_ctrl_reg.modify(
KV_CONTROL::WRITE_LOCK
.val(key_ctrl_reg.read(KV_CONTROL::WRITE_LOCK) | val.read(KV_CONTROL::WRITE_LOCK)),
);
key_ctrl_reg.modify(
KV_CONTROL::USE_LOCK
.val(key_ctrl_reg.read(KV_CONTROL::USE_LOCK) | val.read(KV_CONTROL::USE_LOCK)),
);
if key_ctrl_reg.read(KV_CONTROL::WRITE_LOCK) == 0 && val.is_set(KV_CONTROL::CLEAR) {
let key_min = index * KeyVault::KEY_SIZE;
let key_max = key_min + KeyVault::KEY_SIZE;
self.keys.data_mut()[key_min..key_max].fill(0);
}
Ok(())
}
pub fn read_key(
&self,
key_id: u32,
desired_usage: KeyUsage,
) -> Result<[u8; KeyVault::KEY_SIZE], BusError> {
let key_ctrl_reg = &self.key_control[key_id as usize];
if (key_ctrl_reg.read(KV_CONTROL::USE_LOCK) != 0)
|| ((key_ctrl_reg.read(KV_CONTROL::USAGE) & u32::from(desired_usage)) == 0)
{
Err(BusError::LoadAccessFault)?
}
let key_start = key_id as usize * KeyVault::KEY_SIZE;
let key_end = key_id as usize * KeyVault::KEY_SIZE + KeyVault::KEY_SIZE;
let mut key = [0u8; KeyVault::KEY_SIZE];
key.copy_from_slice(&self.keys.data()[key_start..key_end]);
Ok(key)
}
pub fn read_key_locked(
&self,
key_id: u32,
desired_usage: KeyUsage,
) -> Result<[u8; KeyVault::KEY_SIZE], BusError> {
let key_ctrl_reg = &self.key_control[key_id as usize];
if (key_ctrl_reg.read(KV_CONTROL::USAGE) & u32::from(desired_usage)) == 0 {
Err(BusError::LoadAccessFault)?
}
let key_start = key_id as usize * KeyVault::KEY_SIZE;
let key_end = key_id as usize * KeyVault::KEY_SIZE + KeyVault::KEY_SIZE;
let mut key = [0u8; KeyVault::KEY_SIZE];
key.copy_from_slice(&self.keys.data()[key_start..key_end]);
Ok(key)
}
pub fn read_key_as_data(
&self,
key_id: u32,
desired_usage: KeyUsage,
) -> Result<Vec<u8>, BusError> {
let mut result: Vec<u8> = self.read_key(key_id, desired_usage)?.into();
let key_ctrl_reg = &self.key_control[key_id as usize];
let last_dword = key_ctrl_reg.read(KV_CONTROL::LAST_DWORD);
result.resize((last_dword + 1) as usize * 4, 0);
Ok(result)
}
pub fn write_key(&mut self, key_id: u32, key: &[u8], key_usage: u32) -> Result<(), BusError> {
if key.len() > KeyVault::KEY_SIZE || key.len() % 4 != 0 {
Err(BusError::StoreAccessFault)?
}
let key_wordlen = key.len() / 4;
let key_ctrl_reg = &mut self.key_control[key_id as usize];
if key_ctrl_reg.read(KV_CONTROL::WRITE_LOCK) != 0
|| key_ctrl_reg.read(KV_CONTROL::USE_LOCK) != 0
{
Err(BusError::StoreAccessFault)?
}
let key_start = key_id as usize * KeyVault::KEY_SIZE;
let key_end = key_start + key.len();
self.keys.data_mut()[key_start..key_end].copy_from_slice(key);
// Update the key usage.
key_ctrl_reg.modify(KV_CONTROL::USAGE.val(key_usage));
// Update the last dword in the key
key_ctrl_reg.modify(KV_CONTROL::LAST_DWORD.val(key_wordlen as u32 - 1));
Ok(())
}
pub fn clear_with_debug_values(&mut self, sel_debug_value: bool) {
let fill_byte = if sel_debug_value { 0x55 } else { 0xaa };
self.keys.data_mut().fill(fill_byte);
}
pub fn read_pcr(&self, pcr_id: u32) -> [u8; constants::PCR_SIZE_BYTES] {
let pcr_start = pcr_id as usize * constants::PCR_SIZE_WORDS;
let mut pcr = [0u32; constants::PCR_SIZE_WORDS];
pcr.copy_from_slice(&self.pcrs[pcr_start..(pcr_start + constants::PCR_SIZE_WORDS)]);
bytes_from_words_le(&pcr)
}
pub fn write_pcr(
&mut self,
pcr_id: u32,
pcr: &[u8; constants::PCR_SIZE_BYTES],
) -> Result<(), BusError> {
let pcr_start = pcr_id as usize * constants::PCR_SIZE_WORDS;
self.pcrs[pcr_start..(pcr_start + constants::PCR_SIZE_WORDS)]
.copy_from_slice(words_from_bytes_le(pcr).as_slice());
Ok(())
}
fn write_sticky_datavault_ctrl(
&mut self,
_size: RvSize,
index: usize,
val: u32,
) -> Result<(), BusError> {
let val = LocalRegisterCopy::<u32, DV_CONTROL::Register>::new(val);
let ctrl_reg = &mut self.sticky_datavault_control[index];
ctrl_reg.modify(
DV_CONTROL::LOCK_ENTRY
.val(ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) | val.read(DV_CONTROL::LOCK_ENTRY)),
);
Ok(())
}
fn write_sticky_datavault_entry(
&mut self,
_size: RvSize,
word_index: usize,
val: u32,
) -> Result<(), BusError> {
let ctrl_reg =
&mut self.sticky_datavault_control[word_index / STICKY_DATAVAULT_ENTRY_SIZE_WORDS];
if ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) != 0 {
Err(BusError::StoreAccessFault)?
}
self.sticky_datavault_entry[word_index] = val;
Ok(())
}
pub fn write_nonsticky_datavault_ctrl(
&mut self,
_size: RvSize,
index: usize,
val: u32,
) -> Result<(), BusError> {
let val = LocalRegisterCopy::<u32, DV_CONTROL::Register>::new(val);
let ctrl_reg = &mut self.datavault_control[index];
ctrl_reg.modify(
DV_CONTROL::LOCK_ENTRY
.val(ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) | val.read(DV_CONTROL::LOCK_ENTRY)),
);
Ok(())
}
pub fn write_nonsticky_datavault_entry(
&mut self,
_size: RvSize,
word_index: usize,
val: u32,
) -> Result<(), BusError> {
let ctrl_reg =
&mut self.datavault_control[word_index / (NONSTICKY_DATAVAULT_ENTRY_SIZE_WORDS)];
if ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) != 0 {
Err(BusError::StoreAccessFault)?
}
self.datavault_entry[word_index] = val;
Ok(())
}
pub fn write_nonsticky_lockable_scratch_ctrl(
&mut self,
_size: RvSize,
index: usize,
val: u32,
) -> Result<(), BusError> {
let val_reg = LocalRegisterCopy::<u32, DV_CONTROL::Register>::new(val);
let ctrl_reg = &mut self.lockable_scratch_control[index];
ctrl_reg.modify(
DV_CONTROL::LOCK_ENTRY
.val(ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) | val_reg.read(DV_CONTROL::LOCK_ENTRY)),
);
Ok(())
}
pub fn write_nonsticky_lockable_scratch(
&mut self,
_size: RvSize,
word_index: usize,
val: u32,
) -> Result<(), BusError> {
let ctrl_reg = &mut self.lockable_scratch_control[word_index];
if ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) != 0 {
Err(BusError::StoreAccessFault)?
}
self.lockable_scratch[word_index].set(val);
Ok(())
}
pub fn write_sticky_lockable_scratch_ctrl(
&mut self,
_size: RvSize,
index: usize,
val: u32,
) -> Result<(), BusError> {
let val = LocalRegisterCopy::<u32, DV_CONTROL::Register>::new(val);
let ctrl_reg = &mut self.sticky_lockable_scratch_control[index];
ctrl_reg.modify(
DV_CONTROL::LOCK_ENTRY
.val(ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) | val.read(DV_CONTROL::LOCK_ENTRY)),
);
Ok(())
}
pub fn write_sticky_lockable_scratch(
&mut self,
_size: RvSize,
word_index: usize,
val: u32,
) -> Result<(), BusError> {
let ctrl_reg = &mut self.sticky_lockable_scratch_control[word_index];
if ctrl_reg.read(DV_CONTROL::LOCK_ENTRY) != 0 {
Err(BusError::StoreAccessFault)?
}
self.sticky_lockable_scratch[word_index].set(val);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
const OFFSET_KEYS: RvAddr = 0x600;
#[test]
fn test_key_ctrl_reset_state() {
let mut vault = KeyVault::new();
for idx in 0u32..KeyVault::KEY_COUNT {
assert_eq!(
vault
.read(RvSize::Word, KeyVault::KEY_CONTROL_REG_OFFSET + (idx << 2))
.ok(),
Some(KEY_CONTROL_REG_RESET_VAL)
);
}
}
#[test]
fn test_key_read_write() {
let mut vault = KeyVault::new();
for idx in 0u32..KeyVault::KEY_COUNT {
let addr = OFFSET_KEYS + (idx * KeyVault::KEY_SIZE as u32);
assert_eq!(vault.write(RvSize::Word, addr, u32::MAX).ok(), None);
assert_eq!(vault.read(RvSize::Word, addr).ok(), None);
}
}
#[test]
fn test_key_private_read_write() {
let expected: &[u8] = &[
0x11, 0x65, 0xb3, 0x40, 0x6f, 0xf0, 0xb5, 0x2a, 0x3d, 0x24, 0x72, 0x1f, 0x78, 0x54,
0x62, 0xca, 0x22, 0x76, 0xc9, 0xf4, 0x54, 0xa1, 0x16, 0xc2, 0xb2, 0xba, 0x20, 0x17,
0x1a, 0x79, 0x05, 0xea, 0x5a, 0x02, 0x66, 0x82, 0xeb, 0x65, 0x9c, 0x4d, 0x5f, 0x11,
0x5c, 0x36, 0x3a, 0xa3, 0xc7, 0x9b,
];
let mut vault = KeyVault::new();
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_data(true); // dummy usage.
for idx in 0..KeyVault::KEY_COUNT {
vault
.write_key(idx, expected, u32::from(key_usage))
.unwrap();
let returned = vault.read_key(idx, key_usage).unwrap();
assert_eq!(&returned[..expected.len()], expected);
}
}
#[test]
fn test_key_private_read_write_small() {
// In this case, only 8 of the total 12 words in the key-entry are
// written to, so when they are retrieved as data, only those 8 words
// should be returned.
let expected: [u8; 32] = [
0x11, 0x65, 0xb3, 0x40, 0x6f, 0xf0, 0xb5, 0x2a, 0x3d, 0x24, 0x72, 0x1f, 0x78, 0x54,
0x62, 0xca, 0x22, 0x76, 0xc9, 0xf4, 0x54, 0xa1, 0x16, 0xc2, 0xb2, 0xba, 0x20, 0x17,
0x1a, 0x79, 0x05, 0xea,
];
let mut vault = KeyVault::new();
let mut key_usage = KeyUsage::default();
key_usage.set_hmac_data(true); // dummy usage.
for idx in 0..KeyVault::KEY_COUNT {
vault
.write_key(idx, &expected, u32::from(key_usage))
.unwrap();
let returned = vault.read_key_as_data(idx, key_usage).unwrap();
assert_eq!(&returned, &expected);
assert_eq!(
vault.read_key(idx, key_usage).unwrap(),
[
0x11, 0x65, 0xb3, 0x40, 0x6f, 0xf0, 0xb5, 0x2a, 0x3d, 0x24, 0x72, 0x1f, 0x78,
0x54, 0x62, 0xca, 0x22, 0x76, 0xc9, 0xf4, 0x54, 0xa1, 0x16, 0xc2, 0xb2, 0xba,
0x20, 0x17, 0x1a, 0x79, 0x05, 0xea, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]
);
}
}
#[test]
fn test_key_clear_with_debug_values() {
let mut vault = KeyVault::new();
vault.clear_keys_with_debug_values(false);
let key_mem: Vec<u8> = vault.regs.borrow().keys.data().to_vec();
assert_eq!(key_mem, vec![0xaa; key_mem.len()]);
vault.clear_keys_with_debug_values(true);
let key_mem: Vec<u8> = vault.regs.borrow().keys.data().to_vec();
assert_eq!(key_mem, vec![0x55; key_mem.len()]);
}
#[test]
fn test_pcr_read_write() {
let expected: [u8; constants::PCR_SIZE_BYTES] = [
0x11, 0x65, 0xb3, 0x40, 0x6f, 0xf0, 0xb5, 0x2a, 0x3d, 0x24, 0x72, 0x1f, 0x78, 0x54,
0x62, 0xca, 0x22, 0x76, 0xc9, 0xf4, 0x54, 0xa1, 0x16, 0xc2, 0xb2, 0xba, 0x20, 0x17,
0x1a, 0x79, 0x05, 0xea, 0x5a, 0x02, 0x66, 0x82, 0xeb, 0x65, 0x9c, 0x4d, 0x5f, 0x11,
0x5c, 0x36, 0x3a, 0xa3, 0xc7, 0x9b,
];
let mut vault = KeyVault::new();
for pcr_id in 0..constants::PCR_COUNT {
vault.write_pcr(pcr_id, &expected).unwrap();
// Test private read.
let returned = vault.read_pcr(pcr_id);
assert_eq!(&returned, &expected);
// Test public read.
let mut pcr: [u32; PCR_SIZE_WORDS] = [0u32; PCR_SIZE_WORDS];
let pcr_start_word_addr = PCR_REG_OFFSET + (pcr_id * PCR_SIZE_BYTES as u32);
for (word_idx, pcr_word) in pcr.iter_mut().enumerate().take(PCR_SIZE_WORDS) {
let result = vault.read(
RvSize::Word,
pcr_start_word_addr + (word_idx as u32 * RvSize::Word as u32),
);
assert!(result.is_ok());
*pcr_word = result.unwrap();
}
assert_eq!(&bytes_from_words_le(&pcr), &expected);
}
}
#[test]
fn test_pcr_lock_clear() {
let expected: [u8; constants::PCR_SIZE_BYTES] = [
0x11, 0x65, 0xb3, 0x40, 0x6f, 0xf0, 0xb5, 0x2a, 0x3d, 0x24, 0x72, 0x1f, 0x78, 0x54,
0x62, 0xca, 0x22, 0x76, 0xc9, 0xf4, 0x54, 0xa1, 0x16, 0xc2, 0xb2, 0xba, 0x20, 0x17,
0x1a, 0x79, 0x05, 0xea, 0x5a, 0x02, 0x66, 0x82, 0xeb, 0x65, 0x9c, 0x4d, 0x5f, 0x11,
0x5c, 0x36, 0x3a, 0xa3, 0xc7, 0x9b,
];
let cleared_pcr: [u8; constants::PCR_SIZE_BYTES] = [0u8; constants::PCR_SIZE_BYTES];
let mut vault = KeyVault::new();
let mut val_reg = LocalRegisterCopy::<u32, PV_CONTROL::Register>::new(0);
for pcr_id in 0..constants::PCR_COUNT {
vault.write_pcr(pcr_id, &expected).unwrap();
// Test private read.
let returned = vault.read_pcr(pcr_id);
assert_eq!(&returned, &expected);
let pcr_control_addr = PCR_CONTROL_REG_OFFSET + (pcr_id * PCR_CONTROL_REG_WIDTH);
// Clear the PCR.
val_reg.write(PV_CONTROL::CLEAR.val(1));
assert_eq!(
vault
.write(RvSize::Word, pcr_control_addr, val_reg.get())
.ok(),
Some(())
);
let returned = vault.read_pcr(pcr_id);
assert_eq!(&returned, &cleared_pcr);
// Lock PCR
vault.write_pcr(pcr_id, &expected).unwrap();
val_reg.write(PV_CONTROL::LOCK.val(1));
assert_eq!(
vault
.write(RvSize::Word, pcr_control_addr, val_reg.get())
.ok(),
Some(())
);
// Try clearing the PCR. This should be a no-op.
val_reg.write(PV_CONTROL::CLEAR.val(1));
assert_eq!(
vault
.write(RvSize::Word, pcr_control_addr, val_reg.get())
.ok(),
Some(())
);
let returned = vault.read_pcr(pcr_id);
assert_eq!(&returned, &expected);
// Unlock PCR. This should be a no-op.
val_reg.write(PV_CONTROL::LOCK.val(0));
assert_eq!(
vault
.write(RvSize::Word, pcr_control_addr, val_reg.get())
.ok(),
Some(())
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/csrng/health_test.rs | sw-emulator/lib/periph/src/csrng/health_test.rs | // Licensed under the Apache-2.0 license
use super::BITS_PER_NIBBLE;
use caliptra_registers::entropy_src::regs::{
AdaptpHiThresholdsReadVal, AdaptpLoThresholdsReadVal, RepcntThresholdsReadVal,
};
const HEALTH_TEST_WINDOW_BITS: usize = 2048;
pub struct HealthTester {
itrng_nibbles: Box<dyn Iterator<Item = u8>>,
pub repcnt: RepetitionCountTester,
pub adaptp: AdaptiveProportionTester,
boot_time_nibbles: Vec<u8>,
}
impl HealthTester {
pub fn new(itrng_nibbles: Box<dyn Iterator<Item = u8>>) -> Self {
Self {
itrng_nibbles,
repcnt: RepetitionCountTester::new(),
adaptp: AdaptiveProportionTester::new(),
boot_time_nibbles: Vec::new(),
}
}
pub fn test_boot_window(&mut self) {
const NUM_NIBBLES: usize = HEALTH_TEST_WINDOW_BITS / BITS_PER_NIBBLE;
self.boot_time_nibbles = self
.itrng_nibbles
.by_ref()
.take(NUM_NIBBLES)
.inspect(|nibble| {
self.repcnt.feed(*nibble);
self.adaptp.feed(*nibble);
})
.collect();
assert_eq!(self.boot_time_nibbles.len(), NUM_NIBBLES, "itrng iterator should provide at least {NUM_NIBBLES} nibbles for boot-time health testing");
// We'll want to pull these FIFO.
self.boot_time_nibbles.reverse();
}
pub fn failures(&self) -> u32 {
self.repcnt.failures() + self.adaptp.lo_failures() + self.adaptp.hi_failures()
}
}
impl Iterator for HealthTester {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
if let Some(nibble) = self.boot_time_nibbles.pop() {
// First yield any boot-time nibbles we saved while health testing.
Some(nibble)
} else {
// Then yield directly from the TRNG. Feed nibbles through health checks
// for continuous testing.
let nibble = self.itrng_nibbles.next()?;
self.repcnt.feed(nibble);
self.adaptp.feed(nibble);
Some(nibble)
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Bit {
Zero,
One,
}
pub struct RepetitionCountTester {
threshold: u32,
prev_nibble: [Option<Bit>; BITS_PER_NIBBLE],
repetition_count: [u32; BITS_PER_NIBBLE],
failures: u32,
}
impl RepetitionCountTester {
pub fn new() -> Self {
Self {
threshold: 0xffff,
prev_nibble: [None; BITS_PER_NIBBLE],
repetition_count: [1; BITS_PER_NIBBLE], // the hardware starts the counter at 1
failures: 0,
}
}
pub fn set_threshold(&mut self, threshold: RepcntThresholdsReadVal) {
self.threshold = threshold.fips_thresh();
}
pub fn failures(&self) -> u32 {
self.failures
}
pub fn feed(&mut self, nibble: u8) {
// Replicate the logic in caliptra-rtl/src/entropy_src/rtl/entropy_src_repcnt_ht.sv.
// If any of the four RNG wires repeats a bit, increment a wire-specific repetition counter.
// If any of those repetition counters exceed the health check threshold, then increment
// failures.
for i in 0..BITS_PER_NIBBLE {
let bit = match (nibble >> i) & 1 {
0 => Bit::Zero,
1 => Bit::One,
_ => unreachable!("bit {i} of nibble={nibble} should only be 0 or 1"),
};
let is_repeat = self.prev_nibble[i] == Some(bit);
if is_repeat {
self.repetition_count[i] += 1;
if self.repetition_count[i] >= self.threshold {
self.failures += 1;
}
} else {
self.repetition_count[i] = 1;
self.prev_nibble[i] = Some(bit);
}
}
}
}
pub struct AdaptiveProportionTester {
lo_threshold: u32,
hi_threshold: u32,
lo_failures: u32,
hi_failures: u32,
num_ones_seen: u32,
num_bits_seen: usize,
}
impl AdaptiveProportionTester {
pub fn new() -> Self {
Self {
lo_threshold: 0,
hi_threshold: 0xffff,
lo_failures: 0,
hi_failures: 0,
num_ones_seen: 0,
num_bits_seen: 0,
}
}
pub fn set_lo_threshold(&mut self, threshold: AdaptpLoThresholdsReadVal) {
self.lo_threshold = threshold.fips_thresh();
}
pub fn set_hi_threshold(&mut self, threshold: AdaptpHiThresholdsReadVal) {
self.hi_threshold = threshold.fips_thresh();
}
pub fn lo_failures(&self) -> u32 {
self.lo_failures
}
pub fn hi_failures(&self) -> u32 {
self.hi_failures
}
pub fn feed(&mut self, nibble: u8) {
// Replicate the logic in caliptra-rtl/src/entropy_src/rtl/entropy_src_adaptp_ht.sv.
assert!(
nibble.count_ones() <= 4,
"{nibble} should be a NIBBLE instead of a BYTE"
);
self.num_ones_seen += nibble.count_ones();
self.num_bits_seen += BITS_PER_NIBBLE;
if self.num_bits_seen >= HEALTH_TEST_WINDOW_BITS {
if self.num_ones_seen < self.lo_threshold {
self.lo_failures += 1;
}
if self.num_ones_seen > self.hi_threshold {
self.hi_failures += 1;
}
// The test windows are not sliding. Reset for the next window.
self.num_ones_seen = 0;
self.num_bits_seen = 0;
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/csrng/ctr_drbg.rs | sw-emulator/lib/periph/src/csrng/ctr_drbg.rs | // Licensed under the Apache-2.0 license
//! Unverified implementation of CTR_DRBG AES-256
//! Section 10.2 (page 48) of https://doi.org/10.6028/NIST.SP.800-90Ar1
use std::iter;
use super::WORD_SIZE_BYTES;
// Table 3 of Section 10.2.1 (page 49).
const BLOCK_LEN_BYTES: usize = 128 / 8;
const KEY_LEN_BYTES: usize = 256 / 8;
pub(crate) const SEED_LEN_BYTES: usize = BLOCK_LEN_BYTES + KEY_LEN_BYTES;
pub type Block = [u8; BLOCK_LEN_BYTES];
type Key = [u8; KEY_LEN_BYTES];
pub type Seed = [u8; SEED_LEN_BYTES];
#[derive(Copy, Clone)]
pub enum Instantiate<'a> {
Words(&'a [u32]),
Bytes(&'a Seed),
}
impl Default for Instantiate<'_> {
fn default() -> Self {
Self::Bytes(&[0; SEED_LEN_BYTES])
}
}
pub struct CtrDrbg {
v: Block,
key: Key,
generated_bytes: Vec<Block>,
}
impl CtrDrbg {
pub fn new() -> Self {
Self {
v: [0; BLOCK_LEN_BYTES],
key: [0; KEY_LEN_BYTES],
generated_bytes: vec![],
}
}
pub fn update(&mut self, provided_data: Seed) {
// Section 10.2.1.2 (page 51).
let mut temp = [0_u8; SEED_LEN_BYTES];
for chunk in temp.chunks_exact_mut(BLOCK_LEN_BYTES) {
block_increment(&mut self.v);
let output_block = block_encrypt(&self.key, &self.v);
chunk.copy_from_slice(output_block.as_slice());
}
for (t, d) in iter::zip(&mut temp, &provided_data) {
*t ^= d;
}
self.key.copy_from_slice(&temp[..KEY_LEN_BYTES]);
self.v.copy_from_slice(&temp[KEY_LEN_BYTES..]);
}
pub fn instantiate(&mut self, seed: Instantiate) {
// Section 10.2.1.3 (page 52).
let seed_material = match seed {
Instantiate::Words(words) => massage_seed(words),
Instantiate::Bytes(bytes) => *bytes,
};
self.key = [0; KEY_LEN_BYTES];
self.v = [0; BLOCK_LEN_BYTES];
self.update(seed_material);
}
pub fn generate(&mut self, num_128_bit_blocks: usize) {
// Section 10.2.1.5 (page 55).
let additional_input = [0; SEED_LEN_BYTES];
self.generated_bytes.clear();
for _ in 0..num_128_bit_blocks {
block_increment(&mut self.v);
let output_block = block_encrypt(&self.key, &self.v);
self.generated_bytes.push(output_block);
}
// https://opentitan.org/book/hw/ip/csrng/doc/programmers_guide.html#endianness-and-known-answer-tests
self.generated_bytes.reverse();
self.update(additional_input);
}
pub fn uninstantiate(&mut self) {
self.v = [0; BLOCK_LEN_BYTES];
self.key = [0; KEY_LEN_BYTES];
self.generated_bytes.clear();
}
pub fn pop_block(&mut self) -> Option<Block> {
self.generated_bytes.pop()
}
#[allow(dead_code)]
fn print_state(&self) {
println!("key={:x?}\nv={:x?}", self.key, self.v);
}
}
fn block_increment(block: &mut Block) {
for byte in block.iter_mut().rev() {
if *byte == u8::MAX {
*byte = 0;
} else {
*byte += 1;
break;
}
}
}
fn block_encrypt(key: &Key, block: &Block) -> Block {
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{BlockEncrypt, KeyInit};
use aes::Aes256Enc;
let cipher = Aes256Enc::new_from_slice(key).expect("construct AES-256");
let mut output_block = GenericArray::clone_from_slice(block);
cipher.encrypt_block(&mut output_block);
output_block
.as_slice()
.try_into()
.expect("block slice to block array")
}
fn massage_seed(input: &[u32]) -> Seed {
// Starting from the end of `input` words, paste the bytes (big-endian)
// of each word into `out`. This final form is what the NIST algorithm
// expects for seeds.
let mut out = [0; SEED_LEN_BYTES];
for (dst, word) in iter::zip(out.chunks_exact_mut(WORD_SIZE_BYTES), input.iter().rev()) {
dst.copy_from_slice(&word.to_be_bytes());
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn block_increment_zero() {
let mut actual = [0; BLOCK_LEN_BYTES];
block_increment(&mut actual);
let mut expected = [0; BLOCK_LEN_BYTES];
*expected.last_mut().unwrap() = 1;
assert_eq!(actual, expected);
}
#[test]
fn block_increment_max_first_byte() {
let mut actual = [0; BLOCK_LEN_BYTES];
*actual.last_mut().unwrap() = u8::MAX;
block_increment(&mut actual);
let mut expected = [0; BLOCK_LEN_BYTES];
expected[expected.len() - 2] = 1;
assert_eq!(actual, expected);
}
#[test]
fn block_increment_non_zero_first_byte() {
let mut actual = [0; BLOCK_LEN_BYTES];
*actual.last_mut().unwrap() = 0xa0;
block_increment(&mut actual);
let mut expected = [0; BLOCK_LEN_BYTES];
*expected.last_mut().unwrap() = 0xa1;
assert_eq!(actual, expected);
}
#[test]
fn block_increment_max() {
let mut actual = [u8::MAX; BLOCK_LEN_BYTES];
block_increment(&mut actual);
let expected = [0; BLOCK_LEN_BYTES];
assert_eq!(actual, expected);
}
#[test]
fn massage_seed_zero_words() {
let expected = [0; SEED_LEN_BYTES];
assert_eq!(massage_seed(&[]), expected);
}
#[test]
fn massage_seed_single_word() {
let input = 0xA1B2C3D4_u32;
let mut expected = [0; SEED_LEN_BYTES];
expected[0..4].copy_from_slice(&input.to_be_bytes());
assert_eq!(massage_seed(&[input]), expected);
}
#[test]
fn massage_seed_two_words() {
let word0 = 0xA1B2C3D4_u32;
let word1 = 0xC1D2E3F4_u32;
let mut expected = [0; SEED_LEN_BYTES];
expected[0..4].copy_from_slice(&word1.to_be_bytes());
expected[4..8].copy_from_slice(&word0.to_be_bytes());
assert_eq!(massage_seed(&[word0, word1]), expected);
}
#[test]
fn massage_seed_nist_test_vector() {
const SEED: [u32; 12] = [
0x73bec010, 0x9262474c, 0x16a30f76, 0x531b51de, 0x2ee494e5, 0xdfec9db3, 0xcb7a879d,
0x5600419c, 0xca79b0b0, 0xdda33b5c, 0xa468649e, 0xdf5d73fa,
];
assert_eq!(
massage_seed(&SEED),
*b"\xdf\x5d\x73\xfa\xa4\x68\x64\x9e\xdd\xa3\x3b\x5c\xca\x79\xb0\
\xb0\x56\x00\x41\x9c\xcb\x7a\x87\x9d\xdf\xec\x9d\xb3\x2e\xe4\
\x94\xe5\x53\x1b\x51\xde\x16\xa3\x0f\x76\x92\x62\x47\x4c\x73\
\xbe\xc0\x10",
);
}
#[test]
fn ctr_drbg_nist_test_vector() {
// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/drbg/drbgtestvectors.zip
// Count 2 of CTR_DRBG.txt (no reseed) with the section heading:
// [AES-256 no df]
// [PredictionResistance = False]
// [EntropyInputLen = 384]
// [NonceLen = 0]
// [PersonalizationStringLen = 0]
// [AdditionalInputLen = 0]
// [ReturnedBitsLen = 512]
const ENTROPY_INPUT: [u32; 12] = [
0x4835c677, 0xff87f32f, 0x98662f2d, 0x5592efed, 0xb4c78ead, 0x160d1ce0, 0x869dcbe2,
0x8d038018, 0xa694bca2, 0xab7bdcd5, 0xf2f8e2c4, 0x0217a8ac,
];
let mut ctr_drbg = CtrDrbg::new();
ctr_drbg.instantiate(Instantiate::Words(&ENTROPY_INPUT));
assert_eq!(
ctr_drbg.key,
[
0x51, 0x18, 0x22, 0x57, 0x35, 0xbd, 0xd4, 0x7d, 0x02, 0x18, 0x68, 0x24, 0x62, 0x5f,
0xcf, 0x29, 0x43, 0xa4, 0xc0, 0x25, 0xcb, 0xfd, 0xa0, 0x8c, 0x11, 0x43, 0xd9, 0x33,
0x0e, 0x34, 0x13, 0xb5
]
);
assert_eq!(
ctr_drbg.v,
[
0x27, 0xf2, 0xec, 0x27, 0xaf, 0xc0, 0x05, 0x59, 0x2e, 0x25, 0x06, 0xa1, 0x3d, 0x33,
0xf3, 0xf9
]
);
ctr_drbg.generate(4);
assert_eq!(
ctr_drbg.key,
[
0x89, 0x21, 0xa5, 0x8f, 0xe7, 0x4e, 0xbb, 0xaf, 0x81, 0xc0, 0xe2, 0x44, 0x1b, 0xf5,
0x6a, 0x11, 0x0e, 0x74, 0xbf, 0x47, 0x33, 0x9b, 0xad, 0xbf, 0x68, 0x79, 0x14, 0x67,
0xbf, 0x24, 0xa2, 0xc9
]
);
assert_eq!(
ctr_drbg.v,
[
0xec, 0x25, 0x56, 0x95, 0x17, 0x48, 0x09, 0xd8, 0x2b, 0xc3, 0x33, 0x99, 0x3f, 0xe3,
0x88, 0x56
]
);
ctr_drbg.generate(4);
assert_eq!(
ctr_drbg.key,
[
0x29, 0xa7, 0xba, 0xbe, 0xda, 0x56, 0x1b, 0xc3, 0x0e, 0x8e, 0xaa, 0xd7, 0x07, 0x1e,
0xfd, 0xe5, 0x1a, 0xa6, 0x11, 0xab, 0x42, 0xe9, 0x67, 0x6a, 0xfe, 0xf6, 0xad, 0x25,
0x85, 0x1c, 0x4b, 0x82
]
);
assert_eq!(
ctr_drbg.v,
[
0x98, 0x1f, 0x26, 0x0a, 0x2e, 0x69, 0xd2, 0x60, 0xd0, 0xdd, 0xcd, 0x94, 0x1a, 0xf0,
0x35, 0xfa
]
);
assert_eq!(
&ctr_drbg.generated_bytes,
&[
[
0x58, 0x31, 0xc9, 0xe6, 0x4f, 0x5b, 0x64, 0x10, 0xae, 0x90, 0x8d, 0x30, 0x61,
0xf7, 0x6c, 0x84
],
[
0x2e, 0x29, 0xf5, 0xa0, 0x93, 0x8a, 0x3b, 0xcd, 0x72, 0x2b, 0xb7, 0x18, 0xd0,
0x1b, 0xbf, 0xc3
],
[
0xd7, 0xf3, 0xf9, 0x46, 0x8a, 0x5b, 0x24, 0x6c, 0xcd, 0xe3, 0x16, 0xd2, 0xab,
0x91, 0x87, 0x9c
],
[
0xaa, 0x36, 0x77, 0x97, 0x26, 0xf5, 0x28, 0x75, 0x31, 0x25, 0x07, 0xfb, 0x08,
0x47, 0x44, 0xd4
],
]
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/dma/otp_fc.rs | sw-emulator/lib/periph/src/dma/otp_fc.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
otp_fc.rs
Abstract:
File contains the axi subsystem fuse controller.
--*/
use bitfield::size_of;
use caliptra_emu_bus::{BusError, ReadOnlyRegister, WriteOnlyRegister};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::RvSize;
use smlang::statemachine;
use tock_registers::register_bitfields;
use crate::SocRegistersInternal;
register_bitfields! {
u32,
/// Status Register
pub Status [
DAI_ERROR OFFSET(7) NUMBITS(1) [],
/// Data Access Interface Idle Status
DAI_IDLE OFFSET(30) NUMBITS(1) [
Busy = 0,
Idle = 1
]
]
}
#[derive(PartialEq)]
pub enum DaiCmd {
Write = 0x2,
Digest = 0x4,
Zeroize = 0x8,
}
impl TryFrom<u32> for DaiCmd {
type Error = ();
fn try_from(val: u32) -> Result<Self, Self::Error> {
match val {
0x2 => Ok(DaiCmd::Write),
0x4 => Ok(DaiCmd::Digest),
0x8 => Ok(DaiCmd::Zeroize),
_ => Err(()),
}
}
}
statemachine! {
transitions: {
*Idle + Write [is_valid_write] / start_write = Writing,
Idle + Digest [is_valid_digest] / start_digest = Computing,
Idle + Zeroize [is_valid_zeroize] / start_zeroize = Zeroizing,
Writing + Complete / finish_write = Idle,
Computing + Complete / finish_digest = Idle,
Zeroizing + Complete / finish_zeroize = Idle,
}
}
#[derive(Clone, Copy, PartialEq)]
pub enum Granularity {
Bits32,
Bits64,
}
// [TODO][CAP2] Used for both UDS (flow correct) and field entropy (needs implementation).
// 80 bytes (UDS) + 96 bytes (FE partitions) = 176 bytes (0xB0)
const FUSE_BANK_SIZE_BYTES: usize = 176;
pub struct Context {
pub address: Option<u32>,
pub wdata0: Option<u32>,
pub wdata1: Option<u32>,
pub rdata0: Option<u32>,
pub rdata1: Option<u32>,
pub fuse_bank: [u32; FUSE_BANK_SIZE_BYTES / size_of::<u32>()],
pub dai_error: bool,
pub soc_reg: SocRegistersInternal,
}
impl Context {
fn new(soc_reg: SocRegistersInternal) -> Self {
Self {
address: None,
wdata0: None,
wdata1: None,
rdata0: None,
rdata1: None,
fuse_bank: [0; FUSE_BANK_SIZE_BYTES / size_of::<u32>()],
dai_error: false,
soc_reg,
}
}
fn granularity(&self) -> Granularity {
// Get granularity from generic_input_wires[0] bit 31
// Bit 31 = 0 → 64-bit granularity
// Bit 31 = 1 → 32-bit granularity
let input_wires = self.soc_reg.get_generic_input_wires();
if (input_wires[0] >> 31) & 1 == 0 {
Granularity::Bits64
} else {
Granularity::Bits32
}
}
}
impl StateMachineContext for Context {
fn is_valid_write(&self) -> Result<bool, ()> {
// Check that we have a valid address and required write data
match (self.address, self.wdata0) {
(None, _) | (_, None) => Err(()),
(Some(addr), Some(_)) => {
// Check address bounds
if (addr as usize) >= self.fuse_bank.len() * 4 {
return Err(());
}
// For 64-bit writes, we need wdata1 too
if self.granularity() == Granularity::Bits64 && self.wdata1.is_none() {
return Err(());
}
Ok(true)
}
}
}
fn is_valid_zeroize(&self) -> Result<bool, ()> {
// Check that we have a valid address
match self.address {
None => Err(()),
Some(addr) => {
// Check address bounds
if (addr as usize) >= self.fuse_bank.len() * 4 {
return Err(());
}
Ok(true)
}
}
}
// Validate digest command parameters.
// The digest operation is only valid when the address points to the base of the UDS fuses (relative address 0).
fn is_valid_digest(&self) -> Result<bool, ()> {
match self.address {
None => Err(()),
Some(0) => Ok(true),
Some(_) => Err(()),
}
}
fn start_write(&mut self) -> Result<(), ()> {
if let (Some(addr), Some(wdata0)) = (self.address, self.wdata0) {
let idx = (addr as usize) / 4;
self.fuse_bank[idx] = wdata0;
self.rdata0 = Some(wdata0);
if self.granularity() == Granularity::Bits64 && idx + 1 < self.fuse_bank.len() {
if let Some(wdata1) = self.wdata1 {
self.fuse_bank[idx + 1] = wdata1;
self.rdata1 = Some(wdata1);
}
}
// Reset the options after command is handled
self.address = None;
self.wdata0 = None;
self.wdata1 = None;
}
Ok(())
}
fn start_digest(&mut self) -> Result<(), ()> {
use sha2::{Digest, Sha512};
// Compute SHA-512 hash of fuse bank contents
let mut hasher = Sha512::new();
for word in self.fuse_bank.iter() {
hasher.update(word.to_be_bytes());
}
let hash = hasher.finalize();
// Convert 64-byte hash into 16 u32 words
let mut uds_seed = [0u32; 16];
for (i, chunk) in hash.chunks(4).enumerate() {
uds_seed[i] = u32::from_be_bytes(chunk.try_into().unwrap());
}
// Set the UDS seed in SoC registers
self.soc_reg.set_uds_seed(&uds_seed);
// Zeroize the fuse bank
self.fuse_bank.fill(0);
Ok(())
}
fn finish_write(&mut self) -> Result<(), ()> {
Ok(())
}
fn finish_digest(&mut self) -> Result<(), ()> {
Ok(())
}
fn start_zeroize(&mut self) -> Result<(), ()> {
if let Some(addr) = self.address {
let idx = (addr as usize) / 4;
// Determine if this is a marker or digest address (which are always 64-bit)
// We need to check if the address aligns with marker or digest locations
// For UDS: digest at offset 64, marker at offset 72
// For FE partitions: each partition is 24 bytes (8 seed + 8 digest + 8 marker)
// FE0: starts at 80, digest at 88, marker at 96
// FE1: starts at 104, digest at 112, marker at 120
// FE2: starts at 128, digest at 136, marker at 144
// FE3: starts at 152, digest at 160, marker at 168
// Check if address is a digest or marker address (always ends at +0 or +8 from base)
// Digest addresses: 64, 88, 112, 136, 160
// Marker addresses: 72, 96, 120, 144, 168
let is_marker_or_digest =
matches!(addr, 64 | 72 | 88 | 96 | 112 | 120 | 136 | 144 | 160 | 168);
// Zeroize the word at the address (set to 0xFFFFFFFF)
self.fuse_bank[idx] = 0xFFFFFFFF;
// Set rdata0 to show zeroized value
self.rdata0 = Some(0xFFFFFFFF);
// For 64-bit granularity OR marker/digest addresses, also zeroize the next word
if (self.granularity() == Granularity::Bits64 || is_marker_or_digest)
&& idx + 1 < self.fuse_bank.len()
{
self.fuse_bank[idx + 1] = 0xFFFFFFFF;
self.rdata1 = Some(0xFFFFFFFF);
}
// Reset address after command is handled
self.address = None;
}
Ok(())
}
fn finish_zeroize(&mut self) -> Result<(), ()> {
Ok(())
}
}
/// Fuse controller
#[derive(Bus)]
pub struct FuseController {
#[register(offset = 0x10, read_fn = read_status)]
status: ReadOnlyRegister<u32, Status::Register>,
#[register(offset = 0x80, write_fn = write_cmd)]
direct_access_cmd: WriteOnlyRegister<u32>,
#[register(offset = 0x84, write_fn = write_address)]
direct_access_address: WriteOnlyRegister<u32>,
#[register(offset = 0x88, write_fn = write_wdata0)]
direct_access_wdata_0: WriteOnlyRegister<u32>,
#[register(offset = 0x8c, write_fn = write_wdata1)]
direct_access_wdata_1: WriteOnlyRegister<u32>,
#[register(offset = 0x90, read_fn = read_rdata0)]
direct_access_rdata_0: ReadOnlyRegister<u32>,
#[register(offset = 0x94, read_fn = read_rdata1)]
direct_access_rdata_1: ReadOnlyRegister<u32>,
state_machine: StateMachine<Context>,
}
impl FuseController {
// The fuse banks is emulated as part of this peripheral
pub const FUSE_BANK_OFFSET: u64 = 0x800;
pub fn new(soc_reg: SocRegistersInternal) -> Self {
Self {
status: ReadOnlyRegister::new(Status::DAI_IDLE::Idle.value),
direct_access_cmd: WriteOnlyRegister::new(0),
direct_access_address: WriteOnlyRegister::new(0),
direct_access_wdata_0: WriteOnlyRegister::new(0),
direct_access_wdata_1: WriteOnlyRegister::new(0),
direct_access_rdata_0: ReadOnlyRegister::new(0),
direct_access_rdata_1: ReadOnlyRegister::new(0),
state_machine: StateMachine::new(Context::new(soc_reg)),
}
}
pub fn read_status(&self, _size: RvSize) -> Result<u32, BusError> {
let mut value = match self.state_machine.state() {
States::Idle => Status::DAI_IDLE::Idle,
_ => Status::DAI_IDLE::Busy,
}
.value;
if self.state_machine.context.dai_error {
value |= Status::DAI_ERROR::SET.value;
}
Ok(value)
}
pub fn write_cmd(&mut self, _size: RvSize, val: u32) -> Result<(), BusError> {
if let Ok(cmd) = DaiCmd::try_from(val) {
// Reset error state before new command
self.state_machine.context.dai_error = false;
let event = match cmd {
DaiCmd::Write => Events::Write,
DaiCmd::Digest => Events::Digest,
DaiCmd::Zeroize => Events::Zeroize,
};
if self.state_machine.process_event(event).is_err() {
self.state_machine.context.dai_error = true;
} else {
// Simulate HW delay before completing
let _ = self.state_machine.process_event(Events::Complete);
}
}
Ok(())
}
pub fn write_address(&mut self, _size: RvSize, val: u32) -> Result<(), BusError> {
// Only use lowest 12 bits and make relative to FUSE_BANK_OFFSET
let masked_addr = (val & 0xFFF) as u64;
if masked_addr < Self::FUSE_BANK_OFFSET {
return Err(BusError::StoreAccessFault);
}
let relative_addr = (masked_addr - Self::FUSE_BANK_OFFSET) as u32;
self.state_machine.context.address = Some(relative_addr);
Ok(())
}
pub fn write_wdata0(&mut self, _size: RvSize, val: u32) -> Result<(), BusError> {
self.state_machine.context.wdata0 = Some(val);
self.state_machine.context.rdata0 = Some(val);
Ok(())
}
pub fn write_wdata1(&mut self, _size: RvSize, val: u32) -> Result<(), BusError> {
self.state_machine.context.wdata1 = Some(val);
self.state_machine.context.rdata1 = Some(val);
Ok(())
}
pub fn read_rdata0(&self, _size: RvSize) -> Result<u32, BusError> {
Ok(self.state_machine.context.rdata0.unwrap_or(0))
}
pub fn read_rdata1(&self, _size: RvSize) -> Result<u32, BusError> {
Ok(self.state_machine.context.rdata1.unwrap_or(0))
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/dma/axi_root_bus.rs | sw-emulator/lib/periph/src/dma/axi_root_bus.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
axi_root_bus.rs
Abstract:
File contains the axi root bus peripheral.
--*/
use crate::dma::recovery::RecoveryRegisterInterface;
use crate::helpers::words_from_bytes_le_vec;
use crate::SocRegistersInternal;
use crate::{dma::otp_fc::FuseController, mci::Mci, Sha512Accelerator};
use caliptra_emu_bus::{
Bus,
BusError::{self, LoadAccessFault, StoreAccessFault},
Device, Event, EventData, ReadWriteMemory, Register,
};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use const_random::const_random;
use std::env;
use std::sync::LazyLock;
use std::{rc::Rc, sync::mpsc};
pub type AxiAddr = u64;
const TEST_SRAM_SIZE: usize = 64 * 1024;
const EXTERNAL_TEST_SRAM_SIZE: usize = 1024 * 1024;
const MCU_SRAM_SIZE: usize = 384 * 1024;
pub struct AxiRootBus {
pub reg: u32,
pub recovery: RecoveryRegisterInterface,
event_sender: Option<mpsc::Sender<Event>>,
pub dma_result: Option<Vec<u32>>,
pub otp_fc: FuseController,
pub mci: Mci,
sha512_acc: Sha512Accelerator,
pub test_sram: Option<ReadWriteMemory<TEST_SRAM_SIZE>>,
pub mcu_sram: ReadWriteMemory<MCU_SRAM_SIZE>,
pub indirect_fifo_status: u32,
pub use_mcu_recovery_interface: bool,
}
impl AxiRootBus {
const SHA512_ACC_OFFSET: AxiAddr = 0x3002_1000;
const SHA512_ACC_END: AxiAddr = 0x3002_10ff;
const TEST_REG_OFFSET: AxiAddr = 0xaa00;
// ROM and Runtime code should not depend on the exact values of these.
pub const RECOVERY_REGISTER_INTERFACE_OFFSET: AxiAddr =
const_random!(u64) & 0xffffffff_00000000;
pub const RECOVERY_REGISTER_INTERFACE_END: AxiAddr =
Self::RECOVERY_REGISTER_INTERFACE_OFFSET + 0xff;
pub fn ss_mci_offset() -> AxiAddr {
*SS_MCI_OFFSET
}
pub fn ss_mci_end() -> AxiAddr {
*SS_MCI_OFFSET + 0x1454 // 0x1454 is last MCI register offset + size
}
pub fn mcu_sram_offset() -> AxiAddr {
*SS_MCI_OFFSET + 0xc0_0000
}
pub fn mcu_sram_end() -> AxiAddr {
Self::mcu_sram_offset() + 2 * 1024 * 1024 - 1
}
pub fn mcu_mbox0_sram_offset() -> AxiAddr {
*SS_MCI_OFFSET + 0x40_0000
}
pub fn mcu_mbox0_sram_end() -> AxiAddr {
Self::mcu_mbox0_sram_offset() + 0x20_0000 - 1
}
pub fn mcu_mbox1_sram_offset() -> AxiAddr {
*SS_MCI_OFFSET + 0x80_0000
}
pub fn mcu_mbox1_sram_end() -> AxiAddr {
Self::mcu_mbox1_sram_offset() + 0x20_0000 - 1
}
pub const OTC_FC_OFFSET: AxiAddr = (const_random!(u64) & 0xffffffff_00000000) + 0x1000;
pub const OTC_FC_END: AxiAddr = Self::OTC_FC_OFFSET + 0xfff;
// Test SRAM is used for testing purposes and is not part of the actual design.
// An arbitratry offset is chosen to avoid overlap with other peripherals.
// Test SRAM is only accessible from the Caliptra Core, and is initialized by the emulator.
pub const TEST_SRAM_OFFSET: AxiAddr = 0x00000000_00500000;
pub const TEST_SRAM_END: AxiAddr = Self::TEST_SRAM_OFFSET + TEST_SRAM_SIZE as u64;
// External Test SRAM is used for testing purposes and is not part of the actual design.
// This SRAM is accessible from the Caliptra Core and the MCU emulators.
pub const EXTERNAL_TEST_SRAM_OFFSET: AxiAddr = 0x00000000_80000000;
pub const EXTERNAL_TEST_SRAM_END: AxiAddr =
Self::EXTERNAL_TEST_SRAM_OFFSET + EXTERNAL_TEST_SRAM_SIZE as u64;
pub fn new(
soc_reg: SocRegistersInternal,
sha512_acc: Sha512Accelerator,
mci: Mci,
test_sram_content: Option<&[u8]>,
use_mcu_recovery_interface: bool,
) -> Self {
let test_sram = if let Some(test_sram_content) = test_sram_content {
if test_sram_content.len() > TEST_SRAM_SIZE {
panic!("test_sram_content length exceeds TEST_SRAM_SIZE");
}
let mut sram_data = [0u8; TEST_SRAM_SIZE];
sram_data[..test_sram_content.len()].copy_from_slice(test_sram_content);
Some(ReadWriteMemory::new_with_data(sram_data))
} else {
None
};
let mcu_sram = ReadWriteMemory::new();
Self {
reg: 0xaabbccdd,
recovery: RecoveryRegisterInterface::new(),
otp_fc: FuseController::new(soc_reg),
mci,
sha512_acc,
event_sender: None,
dma_result: None,
test_sram,
mcu_sram,
indirect_fifo_status: 0,
use_mcu_recovery_interface,
}
}
pub fn must_schedule(&mut self, addr: AxiAddr) -> bool {
if self.use_mcu_recovery_interface {
(addr >= Self::mcu_sram_offset() && addr <= Self::mcu_sram_end())
|| matches!(
addr,
Self::EXTERNAL_TEST_SRAM_OFFSET..=Self::EXTERNAL_TEST_SRAM_END
)
|| (addr >= Self::mcu_mbox0_sram_offset() && addr <= Self::mcu_mbox0_sram_end())
|| (addr >= Self::mcu_mbox1_sram_offset() && addr <= Self::mcu_mbox1_sram_end())
|| matches!(
addr,
Self::RECOVERY_REGISTER_INTERFACE_OFFSET
..=Self::RECOVERY_REGISTER_INTERFACE_END
)
} else {
(addr >= Self::mcu_sram_offset() && addr <= Self::mcu_sram_end())
|| (addr >= Self::mcu_mbox0_sram_offset() && addr <= Self::mcu_mbox0_sram_end())
|| (addr >= Self::mcu_mbox1_sram_offset() && addr <= Self::mcu_mbox1_sram_end())
|| (Self::EXTERNAL_TEST_SRAM_OFFSET..=Self::EXTERNAL_TEST_SRAM_END).contains(&addr)
}
}
pub fn schedule_read(&mut self, addr: AxiAddr, len: u32) -> Result<(), BusError> {
if self.dma_result.is_some() {
println!("Cannot schedule read if previous DMA result has not been consumed");
return Err(BusError::LoadAccessFault);
}
if (Self::mcu_sram_offset()..=Self::mcu_sram_end()).contains(&addr) {
let addr = addr - Self::mcu_sram_offset();
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::MCU,
EventData::MemoryRead {
start_addr: addr as u32,
len,
},
))
.unwrap();
}
Ok(())
} else if (Self::mcu_mbox0_sram_offset()..=Self::mcu_mbox0_sram_end()).contains(&addr) {
let addr = addr - Self::mcu_mbox0_sram_offset();
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::McuMbox0Sram,
EventData::MemoryRead {
start_addr: addr as u32,
len,
},
))
.unwrap();
}
Ok(())
} else if (Self::mcu_mbox1_sram_offset()..=Self::mcu_mbox1_sram_end()).contains(&addr) {
let addr = addr - Self::mcu_mbox1_sram_offset();
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::McuMbox1Sram,
EventData::MemoryRead {
start_addr: addr as u32,
len,
},
))
.unwrap();
}
Ok(())
} else if (Self::EXTERNAL_TEST_SRAM_OFFSET..=Self::EXTERNAL_TEST_SRAM_END).contains(&addr) {
let addr = addr - Self::EXTERNAL_TEST_SRAM_OFFSET;
println!("Sending read event for ExternalTestSram");
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::ExternalTestSram,
EventData::MemoryRead {
start_addr: addr as u32,
len,
},
))
.unwrap();
}
Ok(())
} else if (Self::RECOVERY_REGISTER_INTERFACE_OFFSET..=Self::RECOVERY_REGISTER_INTERFACE_END)
.contains(&addr)
{
let addr = addr - Self::RECOVERY_REGISTER_INTERFACE_OFFSET;
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::RecoveryIntf,
EventData::MemoryRead {
start_addr: addr as u32,
len,
},
))
.unwrap();
}
Ok(())
} else {
Err(BusError::LoadAccessFault)
}
}
pub fn read(&mut self, size: RvSize, addr: AxiAddr) -> Result<RvData, BusError> {
match addr {
Self::SHA512_ACC_OFFSET..=Self::SHA512_ACC_END => {
let addr = ((addr - Self::SHA512_ACC_OFFSET) & 0xffff_ffff) as RvAddr;
return Bus::read(&mut self.sha512_acc, size, addr);
}
Self::TEST_REG_OFFSET => return Register::read(&self.reg, size),
Self::RECOVERY_REGISTER_INTERFACE_OFFSET..=Self::RECOVERY_REGISTER_INTERFACE_END => {
let addr = (addr - Self::RECOVERY_REGISTER_INTERFACE_OFFSET) as RvAddr;
return Bus::read(&mut self.recovery, size, addr);
}
Self::OTC_FC_OFFSET..=Self::OTC_FC_END => {
let addr = (addr - Self::OTC_FC_OFFSET) as RvAddr;
return Bus::read(&mut self.otp_fc, size, addr);
}
Self::TEST_SRAM_OFFSET..=Self::TEST_SRAM_END => {
if let Some(test_sram) = self.test_sram.as_mut() {
let addr = (addr - Self::TEST_SRAM_OFFSET) as RvAddr;
return Bus::read(test_sram, size, addr);
} else {
return Err(LoadAccessFault);
}
}
_ => {}
};
if (Self::mcu_sram_offset()..=Self::mcu_sram_end()).contains(&addr) {
let addr = (addr - Self::mcu_sram_offset()) as RvAddr;
return Bus::read(&mut self.mcu_sram, size, addr);
} else if (*SS_MCI_OFFSET..=Self::mcu_sram_end()).contains(&addr) {
let addr = (addr - *SS_MCI_OFFSET) as RvAddr;
return Bus::read(&mut self.mci, size, addr);
}
Err(LoadAccessFault)
}
pub fn write(&mut self, size: RvSize, addr: AxiAddr, val: RvData) -> Result<(), BusError> {
match addr {
Self::SHA512_ACC_OFFSET..=Self::SHA512_ACC_END => {
return self.sha512_acc.write(
size,
((addr - Self::SHA512_ACC_OFFSET) & 0xffff_ffff) as u32,
val,
)
}
Self::TEST_REG_OFFSET => return Register::write(&mut self.reg, size, val),
Self::RECOVERY_REGISTER_INTERFACE_OFFSET..=Self::RECOVERY_REGISTER_INTERFACE_END => {
if self.use_mcu_recovery_interface {
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::RecoveryIntf,
EventData::MemoryWrite {
start_addr: (addr - Self::RECOVERY_REGISTER_INTERFACE_OFFSET)
as u32,
data: val.to_le_bytes().to_vec(),
},
))
.unwrap();
}
return Ok(());
} else {
let addr = (addr - Self::RECOVERY_REGISTER_INTERFACE_OFFSET) as RvAddr;
return Bus::write(&mut self.recovery, size, addr, val);
}
}
Self::OTC_FC_OFFSET..=Self::OTC_FC_END => {
let addr = (addr - Self::OTC_FC_OFFSET) as RvAddr;
return Bus::write(&mut self.otp_fc, size, addr, val);
}
Self::TEST_SRAM_OFFSET..=Self::TEST_SRAM_END => {
if let Some(test_sram) = self.test_sram.as_mut() {
let addr = (addr - Self::TEST_SRAM_OFFSET) as RvAddr;
return Bus::write(test_sram, size, addr, val);
} else {
return Err(StoreAccessFault);
}
}
_ => {}
};
if (Self::mcu_sram_offset()..=Self::mcu_sram_end()).contains(&addr) {
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::MCU,
EventData::MemoryWrite {
start_addr: (addr - Self::mcu_sram_offset()) as u32,
data: val.to_le_bytes().to_vec(),
},
))
.unwrap();
}
// There is nothing responding to this events but we still want to see them happen.
// This is why we do both and event and a Bus::write
if !self.use_mcu_recovery_interface {
let addr = (addr - Self::mcu_sram_offset()) as RvAddr;
return Bus::write(&mut self.mcu_sram, size, addr, val);
} else {
return Ok(());
}
} else if (Self::mcu_mbox0_sram_offset()..=Self::mcu_mbox0_sram_end()).contains(&addr) {
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::McuMbox0Sram,
EventData::MemoryWrite {
start_addr: (addr - Self::mcu_mbox0_sram_offset()) as u32,
data: val.to_le_bytes().to_vec(),
},
))
.unwrap();
}
// There is nothing responding to this events but we still want to see them happen.
// This is why we do both and event and a Bus::write
return Ok(());
} else if (Self::mcu_mbox1_sram_offset()..=Self::mcu_mbox1_sram_end()).contains(&addr) {
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::McuMbox1Sram,
EventData::MemoryWrite {
start_addr: (addr - Self::mcu_mbox1_sram_offset()) as u32,
data: val.to_le_bytes().to_vec(),
},
))
.unwrap();
}
// There is nothing responding to this events but we still want to see them happen.
// This is why we do both and event and a Bus::write
return Ok(());
} else if (*SS_MCI_OFFSET..=Self::mcu_sram_end()).contains(&addr) {
let addr = (addr - *SS_MCI_OFFSET) as RvAddr;
return Bus::write(&mut self.mci, size, addr, val);
}
Err(StoreAccessFault)
}
pub fn send_get_recovery_indirect_fifo_status(&mut self) {
if let Some(sender) = self.event_sender.as_mut() {
sender
.send(Event::new(
Device::CaliptraCore,
Device::RecoveryIntf,
EventData::RecoveryFifoStatusRequest,
))
.unwrap();
}
}
pub fn get_recovery_indirect_fifo_status(&self) -> u32 {
self.indirect_fifo_status
}
pub fn incoming_event(&mut self, event: Rc<Event>) {
self.recovery.incoming_event(event.clone());
match &event.event {
EventData::MemoryReadResponse {
start_addr: _,
data,
} => {
// we only allow read responses from the MCU, ExternalTestSram and RecoveryIntf
if event.src == Device::MCU
|| event.src == Device::ExternalTestSram
|| Device::RecoveryIntf == event.src
{
self.dma_result = Some(words_from_bytes_le_vec(&data.clone()));
}
}
EventData::RecoveryFifoStatusResponse { status } => {
self.indirect_fifo_status = *status;
}
_ => {}
}
}
pub fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
self.event_sender = Some(sender.clone());
self.recovery.register_outgoing_events(sender);
}
}
static SS_MCI_OFFSET: LazyLock<AxiAddr> = LazyLock::new(|| {
if let Ok(s) = env::var("CPTRA_EMULATOR_SS_MCI_OFFSET") {
parse_u64(&s)
} else {
const_random!(u64) & 0xffffffff_00000000
}
});
fn parse_u64(s: &str) -> u64 {
let s = s.trim();
if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
u64::from_str_radix(hex, 16).unwrap()
} else {
s.parse::<u64>().unwrap()
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/periph/src/dma/recovery.rs | sw-emulator/lib/periph/src/dma/recovery.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
recovery.rs
Abstract:
File contains the recovery register interface peripheral
--*/
use caliptra_emu_bus::{
BusError, Event, EventData, ReadOnlyRegister, ReadWriteRegister, RecoveryCommandCode,
};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
use std::rc::Rc;
use std::sync::mpsc;
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::register_bitfields;
register_bitfields! [
u32,
/// Recovery Control
pub RecoveryControl [
CMS OFFSET(0) NUMBITS(8) [],
IMAGE_SELECTION OFFSET(8) NUMBITS(8) [
NoOperation = 0,
RecoveryFromCms = 1,
RecoveryStoredOnDevice = 2,
// Other bits are reserved
],
ACTIVATE_RECOVERY_IMAGE OFFSET(16) NUMBITS(8) [
DoNotActivate = 0,
Activate = 0xf,
],
],
/// Recovery Status
pub RecoveryStatus [
DEVICE_RECOVERY OFFSET(0) NUMBITS(4) [
NotInRecovery = 0x0,
AwaitingRecoveryImage = 0x1,
BootingRecoveryImage = 0x2,
RecoverySuccessful = 0x3,
RecoveryFailed = 0xc,
AuthenticationError = 0xd,
ErrorEnteringRecovery = 0xe,
InvalidComponentAddressSpace = 0xf,
// 0x10-ff Reserved
],
RECOVERY_IMAGE_INDEX OFFSET(4) NUMBITS(4) [],
VENDOR_SPECIFIC OFFSET(8) NUMBITS(8) [],
],
/// HW Status
pub HwStatus [
HW_STATUS OFFSET(0) NUMBITS(8) [
TemperatureCritial = 0x0,
HardwareSoftError = 0x1,
HardwareFatalError = 0x2,
],
VENDOR_HW_STATUS OFFSET(8) NUMBITS(8) [],
// 0x00-0x7e: 0 to 126 C
// 0x7f: 127 C or higher
// 0x80: no temperature data, or data is older than 5 seconds
// 0x81: temperature sensor failure
// 0x82-0x83: reserved
// 0xc4: -60 C or lower
// 0xc5-0xff: -1 to -59 C (in twoʼs complement)
COMPOSITE_TEMP OFFSET(16) NUMBITS(8) [],
],
/// Indirect FIFO Control 0
IndirectCtrl0 [
CMS OFFSET(0) NUMBITS(8),
RESET OFFSET(8) NUMBITS(1),
],
/// Indirect FIFO Status
pub IndirectStatus [
FIFO_EMPTY OFFSET(0) NUMBITS(1) [],
FIFO_FULL OFFSET(1) NUMBITS(1) [],
REGION_TYPE OFFSET(8) NUMBITS(3) [
CodeSpaceRecovery = 0, // Write Only
LogWithDebugFormat = 1, // Read Only
VendorDefinedRegionWriteOnly = 4,
VendorDefinedRegionReadOnly = 5,
UnsupportedRegion = 7,
],
],
];
/// Recovery register interface
#[derive(Bus)]
#[incoming_event_fn(incoming_event)]
#[register_outgoing_events_fn(register_outgoing_events)]
pub struct RecoveryRegisterInterface {
// Capability registers
#[register(offset = 0x0)]
pub extcap_header: ReadOnlyRegister<u32>,
#[register(offset = 0x4)]
pub prot_cap_0: ReadWriteRegister<u32>,
#[register(offset = 0x8)]
pub prot_cap_1: ReadWriteRegister<u32>,
#[register(offset = 0xc)]
pub prot_cap_2: ReadWriteRegister<u32>,
#[register(offset = 0x10)]
pub prot_cap_3: ReadWriteRegister<u32>,
// Device ID registers
#[register(offset = 0x14)]
pub device_id_0: ReadWriteRegister<u32>,
#[register(offset = 0x18)]
pub device_id_1: ReadWriteRegister<u32>,
#[register(offset = 0x1c)]
pub device_id_2: ReadWriteRegister<u32>,
#[register(offset = 0x20)]
pub device_id_3: ReadWriteRegister<u32>,
#[register(offset = 0x24)]
pub device_id_4: ReadWriteRegister<u32>,
#[register(offset = 0x28)]
pub device_id_5: ReadWriteRegister<u32>,
#[register(offset = 0x2c)]
pub device_id_6: ReadWriteRegister<u32>,
// Status and control registers
#[register(offset = 0x30)]
pub device_status_0: ReadWriteRegister<u32>,
#[register(offset = 0x34)]
pub device_status_1: ReadWriteRegister<u32>,
#[register(offset = 0x38)]
pub device_reset: ReadWriteRegister<u32>,
#[register(offset = 0x3c)]
pub recovery_ctrl: ReadWriteRegister<u32, RecoveryControl::Register>,
#[register(offset = 0x40, write_fn = recovery_status_write)]
pub recovery_status: ReadWriteRegister<u32>,
#[register(offset = 0x44)]
pub hw_status: ReadWriteRegister<u32>,
// Indirect FIFO registers
#[register(offset = 0x48, write_fn = indirect_fifo_ctrl_0_write)]
pub indirect_fifo_ctrl_0: ReadWriteRegister<u32, IndirectCtrl0::Register>,
#[register(offset = 0x4c, read_fn = indirect_fifo_ctrl_image_size_read)]
pub indirect_fifo_ctrl_image_size: ReadWriteRegister<u32>,
#[register(offset = 0x50)]
pub indirect_fifo_status_0: ReadOnlyRegister<u32, IndirectStatus::Register>,
#[register(offset = 0x54)]
pub indirect_fifo_status_1: ReadWriteRegister<u32>, // Write index
#[register(offset = 0x58)]
pub indirect_fifo_status_2: ReadOnlyRegister<u32>, // Read index
#[register(offset = 0x5c)]
pub indirect_fifo_status_3: ReadWriteRegister<u32>, // FIFO size
#[register(offset = 0x60)]
pub indirect_fifo_status_4: ReadWriteRegister<u32>, // Max transfer size
#[register(offset = 0x64)]
pub indirect_fifo_status_5: ReadWriteRegister<u32>,
#[register(offset = 0x68, read_fn = indirect_fifo_data_read)]
pub indirect_fifo_data: ReadWriteRegister<u32>,
pub cms_data: Vec<Vec<u8>>,
pub event_sender: Option<mpsc::Sender<Event>>,
}
impl RecoveryRegisterInterface {
pub fn new() -> Self {
Self {
// Capability registers
extcap_header: ReadOnlyRegister::new(0x0020C0), // CAP_LENGTH = 0x0020, CAP_ID = 0xC0
prot_cap_0: ReadWriteRegister::new(0x2050_434f), // "OCP RECV" in ASCII
prot_cap_1: ReadWriteRegister::new(0x5643_4552),
// lower two bytes are version 1.1
// required: device id = bit 0
// required: device status = bit 4
// recovery memory access / indirect ctrl = bit 5
// c-image = bit 7
// fifo cms support / indirect ctrl= bit 12
prot_cap_2: ReadWriteRegister::new(0x10b1_0101),
prot_cap_3: ReadWriteRegister::new(0x0000_0017), // maximum response time of 128ms, no heartbeat
// Device ID registers
device_id_0: ReadWriteRegister::new(0),
device_id_1: ReadWriteRegister::new(0),
device_id_2: ReadWriteRegister::new(0),
device_id_3: ReadWriteRegister::new(0),
device_id_4: ReadWriteRegister::new(0),
device_id_5: ReadWriteRegister::new(0),
device_id_6: ReadWriteRegister::new(0),
// Status and control registers
device_status_0: ReadWriteRegister::new(0),
device_status_1: ReadWriteRegister::new(0),
device_reset: ReadWriteRegister::new(0),
recovery_ctrl: ReadWriteRegister::new(
RecoveryControl::ACTIVATE_RECOVERY_IMAGE::Activate.into(),
),
recovery_status: ReadWriteRegister::new(0),
hw_status: ReadWriteRegister::new(0),
// Indirect FIFO registers
indirect_fifo_ctrl_0: ReadWriteRegister::new(0),
indirect_fifo_ctrl_image_size: ReadWriteRegister::new(0),
indirect_fifo_status_0: ReadOnlyRegister::new(0x1), // EMPTY=1
indirect_fifo_status_1: ReadWriteRegister::new(0),
indirect_fifo_status_2: ReadOnlyRegister::new(0),
indirect_fifo_status_3: ReadWriteRegister::new(0),
indirect_fifo_status_4: ReadWriteRegister::new(0),
indirect_fifo_status_5: ReadWriteRegister::new(0),
indirect_fifo_data: ReadWriteRegister::new(0),
cms_data: vec![],
event_sender: None,
}
}
pub fn indirect_fifo_data_read(&mut self, size: RvSize) -> Result<RvData, BusError> {
if size != RvSize::Word {
Err(BusError::LoadAccessFault)?;
}
if self.cms_data.is_empty() {
println!("No image set in RRI");
return Ok(0xffff_ffff);
}
let image_index = ((self.recovery_status.reg.get() >> 4) & 0xf) as usize;
let Some(image) = self.cms_data.get(image_index) else {
println!("Recovery image index out of bounds");
return Ok(0xffff_ffff);
};
let cms = self.indirect_fifo_ctrl_0.reg.read(IndirectCtrl0::CMS);
if cms != 0 {
println!("CMS {cms} not supported");
return Ok(0xffff_ffff);
}
let read_index = self.indirect_fifo_status_2.reg.get();
let address = read_index * 4;
let image_len = image.len().try_into().unwrap();
if address >= image_len {
return Ok(0xffff_ffff);
};
if address >= image_len - 4 {
self.indirect_fifo_status_0
.reg
.modify(IndirectStatus::FIFO_EMPTY::SET);
} else {
self.indirect_fifo_status_0
.reg
.modify(IndirectStatus::FIFO_FULL::SET);
}
let address: usize = address.try_into().unwrap();
let range = address..(address + 4);
let data = &image[range];
self.indirect_fifo_status_2.reg.set(read_index + 1);
Ok(u32::from_le_bytes(data.try_into().unwrap()))
}
pub fn indirect_fifo_data_write(&mut self, data: &[u8]) {
if self.cms_data.is_empty() {
println!("No image set in RRI");
return;
}
let image_index = ((self.recovery_status.reg.get() >> 4) & 0xf) as usize;
let Some(image) = self.cms_data.get_mut(image_index) else {
println!("Recovery image index out of bounds");
return;
};
let cms = self.indirect_fifo_ctrl_0.reg.read(IndirectCtrl0::CMS);
if cms != 0 {
println!("CMS {cms} not supported");
return;
}
let write_index = self.indirect_fifo_status_1.reg.get();
let address = (write_index * 4) as usize;
image.resize(address + data.len(), 0);
image[address..address + data.len()].copy_from_slice(data);
// head pointer must be aligned to 4 bytes at the end
self.indirect_fifo_status_1
.reg
.set(((address + data.len()).next_multiple_of(4) / 4) as u32);
}
pub fn indirect_fifo_ctrl_0_write(
&mut self,
size: RvSize,
val: RvData,
) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
let load: ReadWriteRegister<u32, IndirectCtrl0::Register> = ReadWriteRegister::new(val);
if load.reg.is_set(IndirectCtrl0::RESET) {
self.load_image();
}
Ok(())
}
pub fn recovery_status_write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
// Writes have to be Word aligned
if size != RvSize::Word {
Err(BusError::StoreAccessFault)?
}
self.recovery_status.reg.set(val);
self.load_image();
Ok(())
}
fn load_image(&mut self) {
let image_index = ((self.recovery_status.reg.get() >> 4) & 0xf) as usize;
if let Some(image) = self.cms_data.get(image_index) {
let len_dwords = image.len() as u32 / 4;
self.indirect_fifo_ctrl_0
.reg
.modify(IndirectCtrl0::CMS.val(0));
self.indirect_fifo_ctrl_0
.reg
.modify(IndirectCtrl0::RESET::CLEAR);
self.indirect_fifo_ctrl_image_size.reg.set(len_dwords);
self.indirect_fifo_status_0
.reg
.set(IndirectStatus::REGION_TYPE::CodeSpaceRecovery.value);
self.indirect_fifo_status_1.reg.set(0);
self.indirect_fifo_status_2.reg.set(0);
self.indirect_fifo_status_0
.reg
.modify(IndirectStatus::FIFO_EMPTY::CLEAR + IndirectStatus::FIFO_FULL::CLEAR);
} else {
println!(
"No Image in RRI ({} >= {})",
image_index,
self.cms_data.len()
);
self.indirect_fifo_status_0
.reg
.set(IndirectStatus::REGION_TYPE::UnsupportedRegion.value);
}
}
pub fn indirect_fifo_ctrl_image_size_read(&mut self, size: RvSize) -> Result<RvData, BusError> {
if size != RvSize::Word {
Err(BusError::LoadAccessFault)?
}
let image_index = (((self.recovery_status.reg.get()) >> 4) & 0xf) as usize;
Ok(match self.cms_data.get(image_index) {
Some(d) => (d.len() / std::mem::size_of::<u32>()) as u32,
None => 0,
})
}
pub fn indirect_fifo_ctrl_1_read(&mut self, size: RvSize) -> Result<RvData, BusError> {
if size != RvSize::Word {
Err(BusError::LoadAccessFault)?
}
let image_index = ((self.recovery_status.reg.get() >> 4) & 0xf) as usize;
let size_dwords = match self.cms_data.get(image_index) {
Some(d) => ((d.len() / std::mem::size_of::<u32>()) & 0xffff) as u32,
None => 0,
};
Ok(size_dwords)
}
pub fn register_outgoing_events(&mut self, sender: mpsc::Sender<Event>) {
self.event_sender = Some(sender);
}
fn read_max_bytes(payload: &[u8], max: usize) -> u32 {
let mut padded_payload = [0; 4];
let len = payload.len().min(max);
padded_payload[..len].copy_from_slice(&payload[0..len]);
u32::from_le_bytes(padded_payload)
}
pub fn incoming_event(&mut self, event: Rc<Event>) {
let sender = self
.event_sender
.as_ref()
.expect("Incoming event but we have no sender registered");
match &event.event {
EventData::RecoveryImageAvailable { image_id, image } => {
let idx = *image_id as usize;
// ensure we have space for the image
if idx >= self.cms_data.len() {
self.cms_data
.extend(std::iter::repeat(vec![]).take(idx - self.cms_data.len() + 1));
}
while idx >= self.cms_data.len() {
self.cms_data.push(vec![]);
}
// replace any existing image
self.cms_data[idx].clear();
self.cms_data[idx].extend_from_slice(image);
}
EventData::RecoveryBlockWrite {
source_addr: _,
target_addr: _,
command_code,
payload,
} => {
match command_code {
RecoveryCommandCode::ProtCap => (), // read-only
RecoveryCommandCode::DeviceId => (), // read-only
RecoveryCommandCode::DeviceStatus => (), // read-only
RecoveryCommandCode::DeviceReset => {
self.device_reset.reg.set(Self::read_max_bytes(payload, 3));
}
RecoveryCommandCode::RecoveryCtrl => {
self.recovery_ctrl.reg.set(Self::read_max_bytes(payload, 3));
}
RecoveryCommandCode::RecoveryStatus => (), // read-only,
RecoveryCommandCode::HwStatus => (), // read-only
RecoveryCommandCode::IndirectCtrl => {
// unsupported
}
RecoveryCommandCode::IndirectStatus => (), // read-only
RecoveryCommandCode::IndirectData => {
// not supported
}
RecoveryCommandCode::Vendor => {
// not supported
}
RecoveryCommandCode::IndirectFifoCtrl => {
if payload.len() < 6 {
return;
}
let a = Self::read_max_bytes(&payload[0..2], 2);
self.indirect_fifo_ctrl_0.reg.set(a);
let size = u32::from_le_bytes(payload[2..6].try_into().unwrap());
self.indirect_fifo_ctrl_image_size.reg.set(size);
}
RecoveryCommandCode::IndirectFifoStatus => (), // read-only
RecoveryCommandCode::IndirectFifoData => {
self.indirect_fifo_data_write(payload);
}
}
}
EventData::RecoveryBlockReadRequest {
source_addr,
target_addr,
command_code,
} => {
let resp: Option<Vec<u8>> = match command_code {
RecoveryCommandCode::ProtCap => to_payload(
&[
self.prot_cap_0.reg.get(),
self.prot_cap_1.reg.get(),
self.prot_cap_2.reg.get(),
self.prot_cap_3.reg.get(),
],
15,
),
RecoveryCommandCode::DeviceId => to_payload(
&[
self.device_id_0.reg.get(),
self.device_id_1.reg.get(),
self.device_id_2.reg.get(),
self.device_id_3.reg.get(),
self.device_id_4.reg.get(),
self.device_id_5.reg.get(),
self.device_id_6.reg.get(),
],
24,
),
RecoveryCommandCode::DeviceStatus => to_payload(
&[
self.device_status_0.reg.get(),
self.device_status_1.reg.get(),
],
7,
),
RecoveryCommandCode::RecoveryStatus => {
to_payload(&[self.recovery_status.reg.get()], 2)
}
RecoveryCommandCode::RecoveryCtrl => {
to_payload(&[self.recovery_ctrl.reg.get()], 3)
}
_ => None,
};
if let Some(resp) = resp {
sender
.send(Event {
src: event.dest,
dest: event.src,
event: EventData::RecoveryBlockReadResponse {
source_addr: *target_addr,
target_addr: *source_addr,
command_code: *command_code,
payload: resp,
},
})
.expect("Could not send event");
}
}
_ => {}
}
}
}
fn to_payload(data: &[u32], len: usize) -> Option<Vec<u8>> {
Some(
data.iter()
.flat_map(|x| x.to_le_bytes().to_vec())
.take(len)
.collect(),
)
}
impl Default for RecoveryRegisterInterface {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvAddr;
use super::*;
const INDIRECT_FIFO_CTRL0: RvAddr = 0x48;
const INDIRECT_FIFO_RESET: RvData = 0x100;
const INDIRECT_FIFO_CTRL1: RvAddr = 0x4c;
const INDIRECT_FIFO_STATUS: RvAddr = 0x50;
const INDIRECT_FIFO_DATA: RvAddr = 0x68;
#[test]
fn test_get_image() {
let image = vec![0xab; 512];
let image_len = image.len();
let mut rri = RecoveryRegisterInterface::new();
rri.cms_data = vec![image.clone()];
// Reset
rri.write(RvSize::Word, INDIRECT_FIFO_CTRL0, INDIRECT_FIFO_RESET)
.unwrap();
let a = rri.read(RvSize::Word, INDIRECT_FIFO_CTRL0).unwrap();
let b = rri.read(RvSize::Word, INDIRECT_FIFO_CTRL1).unwrap();
let image_size = (a & 0xffff_0000) | (b & 0xffff);
assert_eq!(image_len, image_size as usize * 4);
let mut read_image = Vec::new();
while rri.read(RvSize::Word, INDIRECT_FIFO_STATUS).unwrap() & 1 == 0 {
let dword_read = rri.read(RvSize::Word, INDIRECT_FIFO_DATA).unwrap();
let bytes = dword_read.to_le_bytes();
read_image.extend_from_slice(&bytes);
}
assert_eq!(read_image, image);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/src/lib.rs | sw-emulator/lib/derive/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
token_iter.rs
Abstract:
Contains derive procedural macros used in caliptra-emulator.
--*/
mod bus;
mod util;
use proc_macro::TokenStream;
#[proc_macro_derive(
Bus,
attributes(
peripheral,
poll_fn,
warm_reset_fn,
update_reset_fn,
incoming_event_fn,
register_outgoing_events_fn,
register,
register_array,
)
)]
pub fn derive_bus(input: TokenStream) -> TokenStream {
crate::bus::derive_bus(input.into()).into()
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/src/bus.rs | sw-emulator/lib/derive/src/bus.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
bus.rs
Abstract:
Implements #[derive(Bus)], used for dispatching Bus::read() Bus::write() to
fields of a struct.
--*/
use crate::util::literal::{self, hex_literal_u32};
use crate::util::token_iter::{
expect_ident, skip_to_field_with_attributes, skip_to_group, skip_to_struct_with_attributes,
Attribute,
};
use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use quote::{format_ident, quote};
pub fn derive_bus(input: TokenStream) -> TokenStream {
let mut iter = input.into_iter();
let struct_attrs = skip_to_struct_with_attributes(&mut iter);
let poll_fn = get_fn(&struct_attrs, "poll_fn");
let warm_reset_fn = get_fn(&struct_attrs, "warm_reset_fn");
let update_reset_fn = get_fn(&struct_attrs, "update_reset_fn");
let incoming_event_fn = get_fn(&struct_attrs, "incoming_event_fn");
let register_outgoing_events_fn = get_fn(&struct_attrs, "register_outgoing_events_fn");
let struct_name = expect_ident(&mut iter);
let struct_fields = skip_to_group(&mut iter, Delimiter::Brace);
let peripheral_fields = parse_peripheral_fields(struct_fields.stream());
let register_fields = parse_register_fields(struct_fields.stream());
let offset_matches = build_match_tree_from_fields(&peripheral_fields);
let read_bus_match_tokens = if let Some(offset_matches) = &offset_matches {
gen_bus_match_tokens(offset_matches, AccessType::Read)
} else {
quote! {}
};
let write_bus_match_tokens = if let Some(offset_matches) = &offset_matches {
gen_bus_match_tokens(offset_matches, AccessType::Write)
} else {
quote! {}
};
let read_reg_match_tokens = gen_register_match_tokens(®ister_fields, AccessType::Read);
let write_reg_match_tokens = gen_register_match_tokens(®ister_fields, AccessType::Write);
let self_poll_tokens = if let Some(poll_fn) = &poll_fn {
let poll_fn = Ident::new(poll_fn, Span::call_site());
quote! { Self::#poll_fn(self); }
} else {
quote! {}
};
let self_warm_reset_tokens = if let Some(warm_reset_fn) = &warm_reset_fn {
let warm_reset_fn = Ident::new(warm_reset_fn, Span::call_site());
quote! { Self::#warm_reset_fn(self); }
} else {
quote! {}
};
let self_update_reset_tokens = if let Some(update_reset_fn) = &update_reset_fn {
let update_reset_fn = Ident::new(update_reset_fn, Span::call_site());
quote! { Self::#update_reset_fn(self); }
} else {
quote! {}
};
let self_incoming_event_tokens = if let Some(incoming_event_fn) = &incoming_event_fn {
let incoming_event_fn = Ident::new(incoming_event_fn, Span::call_site());
quote! {
Self::#incoming_event_fn(self, event);
}
} else {
quote! {}
};
let self_register_outgoing_events_tokens =
if let Some(register_outgoing_events_fn) = ®ister_outgoing_events_fn {
let register_outgoing_events_fn =
Ident::new(register_outgoing_events_fn, Span::call_site());
quote! { Self::#register_outgoing_events_fn(self, sender); }
} else {
quote! {}
};
let field_idents: Vec<_> = peripheral_fields
.iter()
.filter(|f| !f.refcell)
.map(|f| Ident::new(&f.name, Span::call_site()))
.collect();
let field_idents_refcell: Vec<_> = peripheral_fields
.iter()
.filter(|f| f.refcell)
.map(|f| Ident::new(&f.name, Span::call_site()))
.collect();
quote! {
impl caliptra_emu_bus::Bus for #struct_name {
fn read(&mut self, size: caliptra_emu_types::RvSize, addr: caliptra_emu_types::RvAddr) -> Result<caliptra_emu_types::RvData, caliptra_emu_bus::BusError> {
#read_reg_match_tokens
#read_bus_match_tokens
Err(caliptra_emu_bus::BusError::LoadAccessFault)
}
fn write(&mut self, size: caliptra_emu_types::RvSize, addr: caliptra_emu_types::RvAddr, val: caliptra_emu_types::RvData) -> Result<(), caliptra_emu_bus::BusError> {
#write_reg_match_tokens
#write_bus_match_tokens
Err(caliptra_emu_bus::BusError::StoreAccessFault)
}
fn poll(&mut self) {
#(self.#field_idents.poll();)*
#(self.#field_idents_refcell.borrow_mut().poll();)*
#self_poll_tokens
}
fn warm_reset(&mut self) {
#(self.#field_idents.warm_reset();)*
#(self.#field_idents_refcell.borrow_mut().warm_reset();)*
#self_warm_reset_tokens
}
fn update_reset(&mut self) {
#(self.#field_idents.update_reset();)*
#(self.#field_idents_refcell.borrow_mut().update_reset();)*
#self_update_reset_tokens
}
fn incoming_event(&mut self, event: std::rc::Rc<caliptra_emu_bus::Event>) {
#(self.#field_idents.incoming_event(event.clone());)*
#self_incoming_event_tokens
}
fn register_outgoing_events(&mut self, sender: std::sync::mpsc::Sender<caliptra_emu_bus::Event>) {
#(self.#field_idents.register_outgoing_events(sender.clone());)*
#self_register_outgoing_events_tokens
}
}
}
}
fn get_fn(struct_attrs: &[Group], name: &str) -> Option<String> {
for attr in struct_attrs {
let mut iter = attr.stream().into_iter();
if let Some(TokenTree::Ident(ident)) = iter.next() {
if ident == name {
if let Some(TokenTree::Group(group)) = iter.next() {
if let Some(TokenTree::Ident(ident)) = group.stream().into_iter().next() {
return Some(ident.to_string());
}
}
}
}
}
None
}
#[derive(Clone, Debug)]
struct RegisterField {
// If this is None, read_fn and write_fn will be Some
name: Option<String>,
ty_tokens: TokenStream,
offset: u32,
read_fn: Option<String>,
write_fn: Option<String>,
is_array: bool,
// Only used if ty_tokens is empty
array_item_size: Option<usize>,
// Only used if ty_tokens is empty
array_len: Option<usize>,
}
fn has_read_and_write_fn(attr: &Attribute) -> bool {
attr.args.contains_key("read_fn") && attr.args.contains_key("write_fn")
}
fn parse_register_fields(stream: TokenStream) -> Vec<RegisterField> {
let mut iter = stream.into_iter();
let mut result = Vec::new();
while let Some(field) = skip_to_field_with_attributes(
&mut iter,
|name| name == "register" || name == "register_array",
has_read_and_write_fn,
) {
if field.attributes.is_empty() {
continue;
}
if field.attributes.len() > 1 {
panic!("More than one #[peripheral] attribute attached to field");
}
let attr = &field.attributes[0];
if let Some(offset) = attr.args.get("offset").cloned() {
result.push(RegisterField {
name: field.field_name.map(|i| i.to_string()),
ty_tokens: field.field_type,
offset: literal::parse_hex_u32(offset),
read_fn: attr.args.get("read_fn").map(|t| t.to_string()),
write_fn: attr.args.get("write_fn").map(|t| t.to_string()),
is_array: field.attr_name == "register_array",
array_len: attr.args.get("len").map(literal::parse_usize),
array_item_size: attr.args.get("item_size").map(literal::parse_usize),
})
} else {
panic!(
"register attribute on field {} must have offset parameter",
field
.field_name
.map(|i| i.to_string())
.unwrap_or(attr.args.get("read_fn").unwrap().to_string())
);
}
}
result
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct PeripheralField {
name: String,
offset: u32,
len: u32,
refcell: bool,
}
fn contains_refcell(stream: TokenStream) -> bool {
stream.into_iter().any(|t| match t {
TokenTree::Group(group) => contains_refcell(group.stream()),
TokenTree::Ident(ident) => ident == "RefCell",
_ => false,
})
}
fn parse_peripheral_fields(stream: TokenStream) -> Vec<PeripheralField> {
let mut iter = stream.into_iter();
let mut result = Vec::new();
while let Some(field) =
skip_to_field_with_attributes(&mut iter, |name| name == "peripheral", |_| false)
{
if field.attributes.is_empty() {
continue;
}
if field.attributes.len() > 1 {
panic!("More than one #[peripheral] attribute attached to field");
}
let attr = &field.attributes[0];
if let (Some(offset), Some(len)) = (
attr.args.get("offset").cloned(),
attr.args.get("len").cloned(),
) {
result.push(PeripheralField {
name: field.field_name.unwrap().to_string(),
offset: literal::parse_hex_u32(offset),
len: literal::parse_hex_u32(len),
refcell: contains_refcell(field.field_type),
})
} else {
panic!("peripheral attribute must have offset and len parameters and be placed before a field offset={:?} len={:?}", attr.args.get("offset"), attr.args.get("len"));
}
}
result
}
/// The arms of the match block.
type LengthMatchBlock = Vec<MatchArm>;
/// Represents a match arm of the form `offset` => `body`.
#[derive(Debug, Eq, PartialEq)]
struct MatchArm {
/// The offset used in the pattern of a mask arm.
offset: u32,
/// The offset + len used in the pattern of a mask arm.
len: u32,
/// Whether the type is a RefCell.
refcell: bool,
/// The expression right of "=>" in the match arm.
body: String,
}
/// Given a list of fields (with their peripheral arguments), generate a tree of
/// offset and len match blocks (to be converted to Rust tokens later).
fn build_match_tree_from_fields(fields: &[PeripheralField]) -> Option<LengthMatchBlock> {
if fields.is_empty() {
return None;
}
let mut fields_by_offset = fields.to_vec();
fields_by_offset.sort_unstable_by_key(|field| field.offset);
// NOTE: for now this implementation generates match blocks rather simplistically
// This could be optimised further - if we split the address space into different
// spans, like a tree, we can decrease the number of comparisons on average.
let mut matches: LengthMatchBlock = Vec::new();
for field in fields_by_offset.iter() {
matches.push(MatchArm {
offset: field.offset,
len: field.len,
body: field.name.clone(),
refcell: field.refcell,
});
}
Some(matches)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AccessType {
Read,
Write,
}
/// Serialize `offset_matches` into a stream of Rust tokens. `access_type`
/// influences whether the generated code calls [`Bus::read()`] or [`Bus::write()`] on
/// the matching peripheral field.
fn gen_bus_match_tokens(offset_matches: &LengthMatchBlock, access_type: AccessType) -> TokenStream {
let match_arms = offset_matches.iter().map(|m| {
let offset = hex_literal_u32(m.offset);
let offset_len = if m.len > 0 {
hex_literal_u32(m.offset + (m.len - 1))
} else {
hex_literal_u32(m.offset)
};
match access_type {
AccessType::Read => {
let field_name = Ident::new(&m.body, Span::call_site());
if m.refcell {
quote! {
#offset..=#offset_len => return self.#field_name.borrow_mut().read(size, addr - #offset),
}
} else {
quote! {
#offset..=#offset_len => return caliptra_emu_bus::Bus::read(&mut self.#field_name, size, addr - #offset),
}
}
},
AccessType::Write => {
let field_name = Ident::new(&m.body, Span::call_site());
if m.refcell {
quote! {
#offset..=#offset_len => return self.#field_name.borrow_mut().write(size, addr - #offset, val),
}
} else {
quote! {
#offset..=#offset_len => return caliptra_emu_bus::Bus::write(&mut self.#field_name, size, addr - #offset, val),
}
}
},
}
});
quote! {
match addr {
#(#match_arms)*
_ => {}
}
}
}
fn gen_register_match_tokens(registers: &[RegisterField], access_type: AccessType) -> TokenStream {
let mut constant_tokens = TokenStream::new();
let mut next_const_id = 0usize;
let mut add_constant = |expr: TokenStream| -> Ident {
let const_ident = format_ident!("CONST{}", next_const_id);
next_const_id += 1;
constant_tokens.extend(quote! {
const #const_ident: u32 = #expr;
});
const_ident
};
if registers.is_empty() {
return quote! {};
}
let match_arms: Vec<_> = registers.iter().map(|reg| {
let offset = hex_literal_u32(reg.offset);
let ty = ®.ty_tokens;
let item_size = || {
if reg.ty_tokens.is_empty() {
let item_size = reg.array_item_size.unwrap_or_else(|| panic!("item_size must be defined for register_array at offset 0x{:08x}", reg.offset));
quote! { #item_size }
} else {
quote! { <#ty as caliptra_emu_bus::RegisterArray>::ITEM_SIZE }
}
};
let mut array_match_pattern = || -> TokenStream {
let item_size = item_size();
let len = if reg.ty_tokens.is_empty() {
let array_len = reg.array_len.unwrap_or_else(|| panic!("len must be defined for register_array at offset 0x{:08x}", reg.offset));
quote! { #array_len }
} else {
quote! { <#ty as caliptra_emu_bus::RegisterArray>::LEN }
};
let end_offset = add_constant(quote! { (#offset + (#len - 1) * #item_size) as u32 });
quote! {
#offset..=#end_offset if (addr as usize) % #item_size == 0
}
};
let array_index = || {
let item_size = item_size();
quote! {
(addr - #offset) as usize / #item_size
}
};
match access_type {
AccessType::Read => {
if let Some(ref read_fn) = reg.read_fn {
let read_fn = Ident::new(read_fn, Span::call_site());
if reg.is_array {
let pattern = array_match_pattern();
let array_index = array_index();
quote! {
#pattern => return std::result::Result::Ok(
std::convert::Into::<caliptra_emu_types::RvAddr>::into(
self.#read_fn(size, #array_index)?
)
),
}
} else {
quote! {
#offset => return std::result::Result::Ok(
std::convert::Into::<caliptra_emu_types::RvAddr>::into(
self.#read_fn(size)?
)
),
}
}
} else if let Some(ref reg_name) = reg.name {
let reg_name = Ident::new(reg_name, Span::call_site());
if reg.is_array {
let pattern = array_match_pattern();
let array_index = array_index();
quote! {
#pattern => return caliptra_emu_bus::Register::read(&self.#reg_name[#array_index], size),
}
} else {
quote! {
#offset => return caliptra_emu_bus::Register::read(&self.#reg_name, size),
}
}
} else {
unreachable!();
}
},
AccessType::Write => {
if let Some(ref write_fn) = reg.write_fn {
let write_fn = Ident::new(write_fn, Span::call_site());
if reg.is_array {
let pattern = array_match_pattern();
let array_index = array_index();
quote! {
#pattern => return self.#write_fn(size, #array_index, std::convert::From::<caliptra_emu_types::RvAddr>::from(val)),
}
} else {
quote! {
#offset => return self.#write_fn(size, std::convert::From::<caliptra_emu_types::RvAddr>::from(val)),
}
}
} else if let Some(ref reg_name) = reg.name {
let reg_name = Ident::new(reg_name, Span::call_site());
if reg.is_array {
let pattern = array_match_pattern();
let array_index = array_index();
quote! {
#pattern => return caliptra_emu_bus::Register::write(&mut self.#reg_name[#array_index], size, val),
}
} else {
quote! {
#offset => return caliptra_emu_bus::Register::write(&mut self.#reg_name, size, val),
}
}
} else {
unreachable!();
}
}
}
}).collect();
quote! {
#constant_tokens
match addr {
#(#match_arms)*
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_peripheral_fields() {
let tokens = parse_peripheral_fields(quote! {
ignore_me: u32,
#[peripheral(offset = 0x3000_0000, len = 0xffff)]
#[ignore_me(foo = bar)]
ram: Ram,
#[peripheral(offset = 0x6000_0000, len = 0x34)]
pub uart: Uart,
});
assert_eq!(
tokens,
vec![
PeripheralField {
name: "ram".into(),
offset: 0x3000_0000,
len: 0xffff,
refcell: false,
},
PeripheralField {
name: "uart".into(),
offset: 0x6000_0000,
len: 0x34,
refcell: false,
},
]
);
}
#[test]
#[should_panic(expected = "More than one #[peripheral] attribute attached to field")]
fn test_parse_peripheral_fields_duplicate() {
parse_peripheral_fields(quote! {
#[peripheral(offset = 0x3000_0000, len = 0xffff)]
#[peripheral(offset = 0x4000_0000, len = 0xffff)]
ram: Ram,
});
}
#[test]
#[rustfmt::skip]
fn test_organize_fields_by_mask() {
let foo = build_match_tree_from_fields(&[
PeripheralField { name: "rom".into(), offset: 0x0000_0000, len: 0xffff, refcell: false },
PeripheralField { name: "sram".into(), offset: 0x1000_0000, len: 0xffff, refcell: false },
PeripheralField { name: "dram".into(), offset: 0x2000_0000, len: 0xffff, refcell: false },
PeripheralField { name: "uart0".into(), offset: 0xaa00_0000, len: 0x34, refcell: false },
PeripheralField { name: "uart1".into(), offset: 0xaa01_0000, len: 0x34, refcell: false },
PeripheralField { name: "i2c0".into(), offset: 0xaa02_0000, len: 0x80, refcell: false },
PeripheralField { name: "i2c1".into(), offset: 0xaa02_0040, len: 0x80, refcell: false },
PeripheralField { name: "i2c2".into(), offset: 0xaa02_0080, len: 0x80, refcell: false },
PeripheralField { name: "spi0".into(), offset: 0xbb42_0000, len: 0x10000, refcell: false },
]);
assert_eq!(foo, Some(vec![
MatchArm { offset: 0x0000_0000, len: 0xffff, body: "rom".into(), refcell: false },
MatchArm { offset: 0x1000_0000, len: 0xffff, body: "sram".into(), refcell: false },
MatchArm { offset: 0x2000_0000, len: 0xffff, body: "dram".into(), refcell: false },
MatchArm { offset: 0xaa00_0000, len: 0x34, body: "uart0".into(), refcell: false },
MatchArm { offset: 0xaa01_0000, len: 0x34, body: "uart1".into(), refcell: false },
MatchArm { offset: 0xaa02_0000, len: 0x80, body: "i2c0".into(), refcell: false },
MatchArm { offset: 0xaa02_0040, len: 0x80, body: "i2c1".into(), refcell: false },
MatchArm { offset: 0xaa02_0080, len: 0x80, body: "i2c2".into(), refcell: false },
MatchArm { offset: 0xbb42_0000, len: 0x10000, body: "spi0".into(), refcell: false },
]));
}
/* TODO: fix this test for new system
#[test]
fn test_derive_bus() {
let tokens = derive_bus(quote! {
#[poll_fn(bus_poll)]
struct MyBus {
#[peripheral(offset = 0x0000_0000, len = 0x0100_0000)]
pub rom: Rom,
#[peripheral(offset = 0x1000_0000, len = 0x0100_0000)]
pub sram: Ram,
#[peripheral(offset = 0x2000_0000, len = 0x0100_0000)]
pub dram: Ram,
#[peripheral(offset = 0xaa00_0000, len = 0x34)]
pub uart0: Uart,
#[peripheral(offset = 0xaa01_0000, len = 0x34)]
pub uart1: Uart,
#[peripheral(offset = 0xaa02_0000, len = 0x80)]
pub i2c0: I2c,
#[peripheral(offset = 0xaa02_0400, len = 0x80)]
pub i2c1: I2c,
#[peripheral(offset = 0xaa02_0800, len = 0x80)]
pub i2c2: I2c,
#[peripheral(offset = 0xbb42_0000, len = 0x10000)]
pub spi0: Spi,
#[register(offset = 0xcafe_f0d0)]
pub reg_u32: u32,
#[register(offset = 0xcafe_f0d4)]
pub reg_u16: u16,
#[register(offset = 0xcafe_f0d8)]
pub reg_u8: u8,
#[register(offset = 0xcafe_f0e0, read_fn = reg_action0_read)]
pub reg_action0: u32,
#[register(offset = 0xcafe_f0e4, write_fn = reg_action1_write)]
pub reg_action1: u32,
#[register_array(offset = 0xcafe_f0f4)]
pub reg_array: [u32; 5],
#[register_array(offset = 0xcafe_f114, read_fn = reg_array_action0_read)]
pub reg_array_action0: [u32; 2],
#[register_array(offset = 0xcafe_f11c, write_fn = reg_array_action1_write)]
pub reg_array_action1: [u32; 2],
#[register(offset = 0xcafe_f0e8, read_fn = reg_action2_read, write_fn = reg_action2_write)]
#[register(offset = 0xcafe_f0ec, read_fn = reg_action3_read, write_fn = reg_action3_write)]
#[register_array(offset = 0xcafe_f134, item_size = 4, len = 5, read_fn = reg_array_action2_read, write_fn = reg_array_action2_write)]
_fieldless_regs: (),
}
});
// TODO
assert_eq!(tokens.to_string(),
quote! {...})
*/
#[test]
fn test_derive_empty_bus() {
let tokens = derive_bus(quote! {
pub struct MyBus {}
});
assert_eq!(tokens.to_string(),
quote! {
impl caliptra_emu_bus::Bus for MyBus {
fn read(&mut self, size: caliptra_emu_types::RvSize, addr: caliptra_emu_types::RvAddr) -> Result<caliptra_emu_types::RvData, caliptra_emu_bus::BusError> {
Err(caliptra_emu_bus::BusError::LoadAccessFault)
}
fn write(&mut self, size: caliptra_emu_types::RvSize, addr: caliptra_emu_types::RvAddr, val: caliptra_emu_types::RvData) -> Result<(), caliptra_emu_bus::BusError> {
Err(caliptra_emu_bus::BusError::StoreAccessFault)
}
fn poll(&mut self) {
}
fn warm_reset(&mut self) {
}
fn update_reset(&mut self) {
}
fn incoming_event(&mut self, event: std::rc::Rc<caliptra_emu_bus::Event>) {
}
fn register_outgoing_events(&mut self, sender: std::sync::mpsc::Sender<caliptra_emu_bus::Event>) {
}
}
}.to_string()
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/src/util/sort.rs | sw-emulator/lib/derive/src/util/sort.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
sort.rs
Abstract:
General-purpose functions for sorting.
--*/
pub fn sorted_by_key<K: Ord, T>(
iter: impl Iterator<Item = T>,
f: impl FnMut(&T) -> K,
) -> impl DoubleEndedIterator<Item = T> {
let mut result = Vec::from_iter(iter);
result.sort_by_key(f);
result.into_iter()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sorted_by_key() {
assert_eq!(
vec![5, 3, 1, 0],
Vec::from_iter(sorted_by_key(vec![5i32, 1, 3, 0].into_iter(), |v| -v))
);
assert_eq!(
vec![0, 1, 3, 5],
Vec::from_iter(sorted_by_key(vec![5i32, 1, 3, 0].into_iter(), |v| -v).rev())
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/src/util/literal.rs | sw-emulator/lib/derive/src/util/literal.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
literal.rs
Abstract:
General-purpose functions for manipulating literal tokens.
--*/
use std::str::FromStr;
use proc_macro2::{Literal, TokenTree};
use crate::util::token_iter::DisplayToken;
pub fn parse_usize(literal: &TokenTree) -> usize {
if let TokenTree::Literal(literal) = literal {
let s = literal.to_string();
if let Some(s) = s.strip_prefix("0x") {
if let Ok(val) = usize::from_str_radix(&s.replace('_', ""), 16) {
return val;
}
}
if let Ok(val) = usize::from_str(&s.replace('_', "")) {
return val;
}
}
panic!(
"Can't parse {} as hex",
&DisplayToken(&Some(literal.clone()))
);
}
pub fn parse_hex_u32(literal: TokenTree) -> u32 {
if let TokenTree::Literal(literal) = &literal {
let s = literal.to_string();
if let Some(s) = s.strip_prefix("0x") {
if let Ok(val) = u32::from_str_radix(&s.replace('_', ""), 16) {
return val;
}
}
}
panic!("Can't parse {} as hex", &DisplayToken(&Some(literal)));
}
pub fn hex_literal_u32(val: u32) -> TokenTree {
TokenTree::Literal(
Literal::from_str(&format!("0x{:04x}_{:04x}", val >> 16, val & 0xffff)).unwrap(),
)
}
#[cfg(test)]
mod tests {
use proc_macro2::{Ident, Span};
use super::*;
#[test]
fn test_parse_usize() {
assert_eq!(42, parse_usize(&Literal::from_str("42").unwrap().into()));
assert_eq!(0, parse_usize(&Literal::from_str("0").unwrap().into()));
assert_eq!(
33_000,
parse_usize(&Literal::from_str("33_000").unwrap().into())
);
assert_eq!(
0x1234,
parse_usize(&Literal::from_str("0x1234").unwrap().into())
);
assert_eq!(
0x1234_5678,
parse_usize(&Literal::from_str("0x1234_5678").unwrap().into())
);
}
#[test]
fn test_parse_hex_u32() {
assert_eq!(0x0, parse_hex_u32(Literal::from_str("0x0").unwrap().into()));
assert_eq!(
0xabcd1234,
parse_hex_u32(Literal::from_str("0xabcd1234").unwrap().into())
);
assert_eq!(
0xabcd1234,
parse_hex_u32(Literal::from_str("0xabcd_1234").unwrap().into())
);
assert_eq!(
0xabcd1234,
parse_hex_u32(Literal::from_str("0xAB_cd_12_34").unwrap().into())
);
}
#[test]
#[should_panic(expected = "Can't parse literal 0 as hex")]
fn test_parse_hex_u32_panic1() {
parse_hex_u32(Literal::from_str("0").unwrap().into());
}
#[test]
#[should_panic(expected = "Can't parse literal 0o0 as hex")]
fn test_parse_hex_u32_panic2() {
parse_hex_u32(Literal::from_str("0o0").unwrap().into());
}
#[test]
#[should_panic(expected = "Can't parse identifier foo as hex")]
fn test_parse_hex_u32_panic3() {
parse_hex_u32(Ident::new("foo", Span::call_site()).into());
}
#[test]
fn test_hex_literal_u32() {
assert_eq!("0x0000_0000", hex_literal_u32(0).to_string());
assert_eq!("0x1234_abcd", hex_literal_u32(0x1234abcd).to_string());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/src/util/mod.rs | sw-emulator/lib/derive/src/util/mod.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
literal.rs
Abstract:
General-purpose code related to procedural macros.
--*/
pub mod literal;
pub mod token_iter;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/src/util/token_iter.rs | sw-emulator/lib/derive/src/util/token_iter.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
token_iter.rs
Abstract:
General-purpose functions for manipulating token iterators.
--*/
use std::{collections::HashMap, fmt::Display};
use proc_macro2::{Delimiter, Group, Ident, Literal, Spacing, TokenStream, TokenTree};
pub struct Attribute {
#[allow(dead_code)]
pub name: Ident,
pub args: HashMap<String, TokenTree>,
}
pub struct FieldWithAttributes {
pub attr_name: String,
pub field_name: Option<Ident>,
pub field_type: TokenStream,
pub attributes: Vec<Attribute>,
}
pub struct DisplayToken<'a>(pub &'a Option<TokenTree>);
impl Display for DisplayToken<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Some(TokenTree::Ident(i)) => write!(f, "identifier {}", i),
Some(TokenTree::Literal(l)) => write!(f, "literal {}", l),
Some(TokenTree::Punct(p)) => write!(f, "punctuation '{}'", p),
Some(TokenTree::Group(g)) => write!(f, "group {}", g),
None => write!(f, "<none>"),
}
}
}
#[allow(dead_code)]
pub fn expect_ident_of(iter: &mut impl Iterator<Item = TokenTree>, expected_name: &str) {
let token = iter.next();
if let Some(TokenTree::Ident(ref ident)) = token {
if ident == expected_name {
return;
}
}
panic!(
"Expected identifier {}, found {}",
expected_name,
DisplayToken(&token)
)
}
pub fn expect_ident(iter: &mut impl Iterator<Item = TokenTree>) -> Ident {
let token = iter.next();
if let Some(TokenTree::Ident(ref ident)) = token {
return ident.clone();
}
panic!("Expected identifier, found {}", DisplayToken(&token))
}
#[allow(dead_code)]
pub fn expect_literal(iter: &mut impl Iterator<Item = TokenTree>) -> Literal {
let token = iter.next();
if let Some(TokenTree::Literal(literal)) = token {
return literal;
}
panic!("Expected literal, found {}", DisplayToken(&token))
}
pub fn expect_literal_or_ident(iter: &mut impl Iterator<Item = TokenTree>) -> TokenTree {
let token = iter.next();
match token {
Some(TokenTree::Literal(literal)) => TokenTree::Literal(literal),
Some(TokenTree::Ident(ident)) => TokenTree::Ident(ident),
_ => panic!(
"Expected literal or identifier, found {}",
DisplayToken(&token)
),
}
}
pub fn expect_punct_of(iter: &mut impl Iterator<Item = TokenTree>, expected: char) {
let token = iter.next();
if let Some(TokenTree::Punct(ref punct)) = token {
if punct.as_char() == expected {
return;
}
}
panic!(
"Expected punctuation '{}', found {}",
expected,
DisplayToken(&token)
)
}
pub fn expect_group(iter: &mut impl Iterator<Item = TokenTree>, delimiter: Delimiter) -> Group {
let token = iter.next();
if let Some(TokenTree::Group(ref group)) = token {
if group.delimiter() == delimiter {
return group.clone();
}
}
panic!(
"Expected group with delimiter '{:?}', found {}",
delimiter,
DisplayToken(&token)
)
}
pub fn skip_to_struct_with_attributes(iter: &mut impl Iterator<Item = TokenTree>) -> Vec<Group> {
let mut prev_token_was_hash = false;
let mut attributes = Vec::new();
loop {
match iter.next() {
Some(TokenTree::Ident(ident)) => {
if ident == "struct" {
return attributes;
}
}
Some(TokenTree::Punct(punct)) if punct.as_char() == '#' => {
prev_token_was_hash = true;
continue;
}
Some(TokenTree::Group(group))
if group.delimiter() == Delimiter::Bracket && prev_token_was_hash =>
{
attributes.push(group);
}
None => panic!("Unexpected end of tokens while searching for struct"),
_ => {}
};
prev_token_was_hash = false;
}
}
pub fn collect_while(
iter: &mut impl Iterator<Item = TokenTree>,
mut pred: impl FnMut(&TokenTree) -> bool,
) -> TokenStream {
let mut result = TokenStream::new();
loop {
match iter.next() {
Some(t) => {
if pred(&t) {
result.extend(Some(t));
} else {
return result;
}
}
None => return result,
}
}
}
pub fn skip_to_group(iter: &mut impl Iterator<Item = TokenTree>, delimiter: Delimiter) -> Group {
loop {
match iter.next() {
Some(TokenTree::Group(group)) => {
if group.delimiter() == delimiter {
return group;
}
}
None => panic!("Unexpected end of tokens while searching for group"),
_ => {}
};
}
}
pub fn skip_to_attribute_or_ident(iter: &mut impl Iterator<Item = TokenTree>) -> Option<TokenTree> {
loop {
match iter.next() {
Some(TokenTree::Punct(punct)) => {
if punct.as_char() == '#' && punct.spacing() == Spacing::Alone {
if let Some(TokenTree::Group(group)) = iter.next() {
if group.delimiter() == Delimiter::Bracket {
return Some(TokenTree::Group(group));
}
}
}
}
Some(TokenTree::Ident(ident)) => {
if ident == "pub" {
continue;
}
return Some(TokenTree::Ident(ident));
}
None => return None,
_ => {}
};
}
}
pub fn skip_to_field_with_attributes(
iter: &mut impl Iterator<Item = TokenTree>,
attribute_name_pred: impl Fn(&str) -> bool,
no_field_required_pred: impl Fn(&Attribute) -> bool,
) -> Option<FieldWithAttributes> {
let mut attr_name = String::new();
let mut attributes = Vec::new();
loop {
match skip_to_attribute_or_ident(iter) {
Some(TokenTree::Group(group)) => {
let mut iter = group.stream().into_iter();
let attribute_ident = expect_ident(&mut iter);
attr_name = attribute_ident.to_string();
if !attribute_name_pred(&attr_name) {
continue;
}
let params = expect_group(&mut iter, Delimiter::Parenthesis);
let mut iter = params.stream().into_iter();
let mut args = HashMap::new();
loop {
let key = expect_ident(&mut iter);
expect_punct_of(&mut iter, '=');
let value = expect_literal_or_ident(&mut iter);
args.insert(key.to_string(), value);
let token = iter.next();
match token {
Some(TokenTree::Punct(ref punct)) => {
if punct.as_char() == ',' {
continue;
}
}
None => break,
_ => {}
}
panic!("Unexpected token {:?}", token)
}
let attribute = Attribute {
name: attribute_ident,
args,
};
attributes.push(attribute);
if no_field_required_pred(attributes.last().unwrap()) {
return Some(FieldWithAttributes {
attr_name,
field_name: None,
field_type: TokenStream::new(),
attributes,
});
}
}
Some(TokenTree::Ident(ident)) => {
expect_punct_of(iter, ':');
let mut depth = 0;
let field_type = collect_while(iter, |t| match t {
TokenTree::Punct(p) if p.as_char() == '<' => {
depth += 1;
true
}
TokenTree::Punct(p) if p.as_char() == '>' => {
depth -= 1;
true
}
TokenTree::Punct(p) => depth != 0 || p.as_char() != ',',
_ => true,
});
return Some(FieldWithAttributes {
attr_name,
field_name: Some(ident),
field_type,
attributes,
});
}
None => return None,
_ => unreachable!(),
}
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use proc_macro2::TokenStream;
use super::*;
fn tokens(s: &str) -> impl Iterator<Item = TokenTree> {
TokenStream::from_str(s).unwrap().into_iter()
}
#[test]
fn test_expect_ident_of() {
expect_ident_of(&mut tokens("foo"), "foo");
expect_ident_of(&mut tokens("baz"), "baz");
}
#[test]
#[should_panic(expected = "Expected identifier foo, found identifier bar")]
fn test_expect_ident_of_panic1() {
expect_ident_of(&mut tokens("bar"), "foo");
}
#[test]
#[should_panic(expected = "Expected identifier foo, found <none>")]
fn test_expect_ident_of_panic2() {
expect_ident_of(&mut tokens(""), "foo");
}
#[test]
#[should_panic(expected = "Expected identifier foo, found literal 35")]
fn test_expect_ident_of_panic3() {
expect_ident_of(&mut tokens("35"), "foo");
}
#[test]
fn test_expect_ident() {
assert_eq!("foo", expect_ident(&mut tokens("foo")).to_string());
}
#[test]
#[should_panic(expected = "Expected identifier, found literal 35")]
fn test_expect_ident_panic1() {
expect_ident(&mut tokens("35"));
}
#[test]
fn test_expect_literal() {
assert_eq!("42", expect_literal(&mut tokens("42")).to_string());
assert_eq!("'h'", expect_literal(&mut tokens("'h'")).to_string());
}
#[test]
#[should_panic(expected = "Expected literal, found identifier foo")]
fn test_expect_literal_panic1() {
expect_literal(&mut tokens("foo"));
}
#[test]
fn test_expect_punct_of() {
expect_punct_of(&mut tokens(","), ',');
expect_punct_of(&mut tokens("."), '.');
}
#[test]
#[should_panic(expected = "Expected punctuation '.', found punctuation ','")]
fn test_expect_punct_of_panic1() {
expect_punct_of(&mut tokens(","), '.');
}
#[test]
fn test_expect_group() {
expect_group(&mut tokens("[35, 42]"), Delimiter::Bracket);
expect_group(&mut tokens("(35, 42)"), Delimiter::Parenthesis);
expect_group(&mut tokens("{}"), Delimiter::Brace);
}
#[test]
#[should_panic(expected = "Expected group with delimiter 'Bracket', found group (35 , 42)")]
fn test_expect_group_panic1() {
expect_group(&mut tokens("(35, 42)"), Delimiter::Bracket);
}
#[test]
#[should_panic(expected = "Expected group with delimiter 'Bracket', found literal 35")]
fn test_expect_group_panic2() {
expect_group(&mut tokens("35"), Delimiter::Bracket);
}
#[test]
fn test_skip_to_struct() {
let iter = &mut tokens("struct { foo: u32 }");
let attrs = skip_to_struct_with_attributes(iter);
assert!(attrs.is_empty());
assert_eq!("{ foo : u32 }", iter.next().unwrap().to_string());
let iter = &mut tokens("pub struct { foo: u32 }");
let attrs = skip_to_struct_with_attributes(iter);
assert!(attrs.is_empty());
assert_eq!("{ foo : u32 }", iter.next().unwrap().to_string());
let iter = &mut tokens("pub(crate) struct { foo: u32 }");
let attrs = skip_to_struct_with_attributes(iter);
assert!(attrs.is_empty());
assert_eq!("{ foo : u32 }", iter.next().unwrap().to_string());
let iter = &mut tokens("#[foobar] pub(crate) struct { foo: u32 }");
let attrs = skip_to_struct_with_attributes(iter);
assert_eq!(attrs.len(), 1);
assert_eq!("[foobar]", attrs[0].to_string());
assert_eq!("{ foo : u32 }", iter.next().unwrap().to_string());
let iter = &mut tokens("#[foo(fn = blah)] #[bar] struct { foo: u32 }");
let attrs = skip_to_struct_with_attributes(iter);
assert_eq!(attrs.len(), 2);
assert_eq!("[foo (fn = blah)]", attrs[0].to_string());
assert_eq!("[bar]", attrs[1].to_string());
assert_eq!("{ foo : u32 }", iter.next().unwrap().to_string());
}
#[test]
fn test_skip_to_group() {
assert_eq!(
"(35 , 42)",
skip_to_group(&mut tokens("(35, 42)"), Delimiter::Parenthesis).to_string()
);
assert_eq!(
"(35 , 42)",
skip_to_group(
&mut tokens("foo bar baz 0xff #(35, 42)"),
Delimiter::Parenthesis
)
.to_string()
);
assert_eq!(
"(35 , 42)",
skip_to_group(&mut tokens("Hi [foo, 32] (35, 42)"), Delimiter::Parenthesis).to_string()
);
assert_eq!(
"[foo , 32]",
skip_to_group(&mut tokens("Hi [foo, 32] (35, 42)"), Delimiter::Bracket).to_string()
);
}
#[test]
#[should_panic(expected = "Unexpected end of tokens")]
fn test_skip_to_group_panic1() {
skip_to_group(&mut tokens("Hi [foo, 32] (35, 42)"), Delimiter::Brace);
}
#[test]
fn test_skip_to_attribute_or_ident() {
assert_eq!(
"[something (foo = 5)]",
skip_to_attribute_or_ident(&mut tokens(": , #[something(foo = 5)]"))
.unwrap()
.to_string()
);
assert_eq!(
"foo",
skip_to_attribute_or_ident(&mut tokens(": , foo"))
.unwrap()
.to_string()
);
assert_eq!(
"foo",
skip_to_attribute_or_ident(&mut tokens(": , pub foo"))
.unwrap()
.to_string()
);
assert!(skip_to_attribute_or_ident(&mut tokens(": , ")).is_none());
}
#[test]
fn test_skip_to_field_with_attributes() {
let result = skip_to_field_with_attributes(
&mut tokens(
"#[attr1(a = 35)] #[attr2(b = 42)] #[attr1(a = 65, baz=\"hi\")] pub foo: Foo,",
),
|name| name == "attr1",
|_| false,
)
.unwrap();
assert_eq!("foo", result.field_name.unwrap().to_string());
assert_eq!("attr1", result.attributes[0].name.to_string());
assert_eq!(
"35",
result.attributes[0].args.get("a").unwrap().to_string()
);
assert_eq!("attr1", result.attributes[1].name.to_string());
assert_eq!(
"65",
result.attributes[1].args.get("a").unwrap().to_string()
);
assert_eq!(
"\"hi\"",
result.attributes[1].args.get("baz").unwrap().to_string()
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/derive/tests/derive_bus_test.rs | sw-emulator/lib/derive/tests/derive_bus_test.rs | // Licensed under the Apache-2.0 license
use std::fmt::Write;
use caliptra_emu_bus::{
testing::{FakeBus, Log},
Bus, BusError, Ram,
};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvData, RvSize};
struct MyCustomField(RvData);
impl From<RvData> for MyCustomField {
fn from(val: RvData) -> Self {
MyCustomField(val)
}
}
impl From<MyCustomField> for RvData {
fn from(val: MyCustomField) -> RvData {
val.0
}
}
#[derive(Bus)]
#[poll_fn(poll)]
#[allow(clippy::manual_non_exhaustive)]
struct MyBus {
pub log: Log,
#[peripheral(offset = 0x0000_0000, len = 0x0fff_ffff)]
pub rom: Ram,
#[peripheral(offset = 0x1000_0000, len = 0x0fff_ffff)]
pub sram: Ram,
#[peripheral(offset = 0x2000_0000, len = 0x0fff_ffff)]
pub dram: Ram,
#[peripheral(offset = 0xaa00_0000, len = 0x80)]
pub uart0: Ram,
#[peripheral(offset = 0xaa01_0000, len = 0x80)]
pub uart1: Ram,
#[peripheral(offset = 0xaa02_0000, len = 0x80)]
pub i2c0: Ram,
#[peripheral(offset = 0xaa02_0400, len = 0x80)]
pub i2c1: Ram,
#[peripheral(offset = 0xaa02_0800, len = 0x80)]
pub i2c2: Ram,
#[peripheral(offset = 0xbb42_0000, len = 0x10000)]
pub spi0: Ram,
#[peripheral(offset = 0xaa05_0000, len = 0x10000)]
pub fake: FakeBus,
#[register(offset = 0xcafe_f0d0)]
pub reg_u32: u32,
#[register(offset = 0xcafe_f0d4)]
pub reg_u16: u16,
#[register(offset = 0xcafe_f0d8)]
pub reg_u8: u8,
#[register_array(offset = 0xcafe_f0f4)]
pub reg_array: [u32; 5],
#[register_array(offset = 0xcafe_f114, read_fn = reg_array_action0_read)]
pub reg_array_action0: [u32; 2],
#[register_array(offset = 0xcafe_f11c, write_fn = reg_array_action1_write)]
pub reg_array_action1: [u32; 2],
#[register(offset = 0xcafe_f0e0, read_fn = reg_action0_read)]
pub reg_action0: u32,
#[register(offset = 0xcafe_f0e4, write_fn = reg_action1_write)]
pub reg_action1: u32,
#[register(offset = 0xcafe_f0e8, read_fn = reg_action2_read, write_fn = reg_action2_write)]
#[register(offset = 0xcafe_f0ec, read_fn = reg_action3_read, write_fn = reg_action3_write)]
#[register_array(offset = 0xcafe_f134, item_size = 4, len = 5, read_fn = reg_array_action2_read, write_fn = reg_array_action2_write)]
_fieldless_regs: (),
}
impl MyBus {
fn reg_action0_read(&self, size: RvSize) -> Result<RvData, BusError> {
write!(self.log.w(), "reg_action0 read {:?}; ", size).unwrap();
Ok(0x4de0d4f5)
}
fn reg_action1_write(&self, size: RvSize, val: RvData) -> Result<(), BusError> {
write!(self.log.w(), "reg_action1 write {size:?} 0x{val:08x}; ").unwrap();
Ok(())
}
fn reg_action2_read(&self, size: RvSize) -> Result<MyCustomField, BusError> {
write!(self.log.w(), "reg_action2 read {size:?}; ").unwrap();
Ok(MyCustomField(0xba5eba11))
}
fn reg_action2_write(&self, size: RvSize, val: MyCustomField) -> Result<(), BusError> {
write!(self.log.w(), "reg_action2 write {size:?} 0x{:08x}; ", val.0).unwrap();
Ok(())
}
fn reg_action3_read(&self, size: RvSize) -> Result<MyCustomField, BusError> {
write!(self.log.w(), "reg_action2 read {size:?}; ").unwrap();
Ok(MyCustomField(0xba5eba11))
}
fn reg_action3_write(&self, size: RvSize, val: MyCustomField) -> Result<(), BusError> {
write!(self.log.w(), "reg_action2 write {size:?} 0x{:08x}; ", val.0).unwrap();
Ok(())
}
fn reg_array_action0_read(&self, size: RvSize, index: usize) -> Result<RvData, BusError> {
write!(
self.log.w(),
"reg_array_action0[{:x}] read {size:?}; ",
index
)
.unwrap();
Ok(0xf00d_0000 + index as u32)
}
fn reg_array_action1_write(
&self,
size: RvSize,
index: usize,
val: MyCustomField,
) -> Result<(), BusError> {
write!(
self.log.w(),
"reg_array_action1[{index}] write {size:?} 0x{:08x}; ",
val.0
)
.unwrap();
Ok(())
}
fn reg_array_action2_read(&self, size: RvSize, index: usize) -> Result<RvData, BusError> {
write!(
self.log.w(),
"reg_array_action2[{:x}] read {size:?}; ",
index
)
.unwrap();
Ok(0xd00d_0000 + index as u32)
}
fn reg_array_action2_write(
&self,
size: RvSize,
index: usize,
val: MyCustomField,
) -> Result<(), BusError> {
write!(
self.log.w(),
"reg_array_action2[{index}] write {size:?} 0x{:08x}; ",
val.0
)
.unwrap();
Ok(())
}
fn poll(&self) {
write!(self.log.w(), "poll; ").unwrap();
}
}
#[test]
fn test_read_dispatch() {
let mut bus = MyBus {
rom: Ram::new(vec![0u8; 65536]),
sram: Ram::new(vec![0u8; 65536]),
dram: Ram::new(vec![0u8; 65536]),
uart0: Ram::new(vec![0u8; 128]),
uart1: Ram::new(vec![0u8; 128]),
i2c0: Ram::new(vec![0u8; 128]),
i2c1: Ram::new(vec![0u8; 128]),
i2c2: Ram::new(vec![0u8; 128]),
spi0: Ram::new(vec![0u8; 65536]),
fake: FakeBus::new(),
reg_u32: 0xd149_b444,
reg_u16: 0x695c,
reg_u8: 0xc1,
reg_action0: 0,
reg_action1: 0xa813_c333,
reg_array: [
0x1043_0000,
0x1043_1000,
0x1043_2000,
0x1043_3000,
0x1043_4000,
],
reg_array_action0: [0x1001_1000, 0x1001_2000],
reg_array_action1: [0x2001_1000, 0x2001_2000],
_fieldless_regs: (),
log: Log::new(),
};
bus.rom.write(RvSize::Word, 0x3430, 0x3828_abcd).unwrap();
assert_eq!(bus.read(RvSize::Word, 0x3430).unwrap(), 0x3828_abcd);
bus.sram.write(RvSize::Word, 0x0, 0x892a_b38a).unwrap();
assert_eq!(bus.read(RvSize::HalfWord, 0x1000_0000).unwrap(), 0xb38a);
bus.dram.write(RvSize::Word, 0xfffc, 0x2a29_3072).unwrap();
assert_eq!(bus.read(RvSize::Byte, 0x2000_ffff).unwrap(), 0x2a);
bus.uart0.write(RvSize::Word, 0x20, 0x8e27_ab42).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xaa00_0020).unwrap(), 0x8e27_ab42);
bus.uart1.write(RvSize::Word, 0x74, 0x38b8_e201).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xaa01_0074).unwrap(), 0x38b8_e201);
bus.i2c0.write(RvSize::Word, 0x1c, 0xc1a4_823f).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xaa02_001c).unwrap(), 0xc1a4_823f);
bus.i2c0.write(RvSize::Word, 0x68, 0x0e8a_440b).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xaa02_0068).unwrap(), 0x0e8a_440b);
bus.i2c1.write(RvSize::Word, 0x00, 0x0e8a_440b).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xaa02_0400).unwrap(), 0x0e8a_440b);
bus.i2c2.write(RvSize::Word, 0x54, 0x70fa_81c9).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xaa02_0854).unwrap(), 0x70fa_81c9);
bus.spi0.write(RvSize::Word, 0xd87c, 0x48ba_38c1).unwrap();
assert_eq!(bus.read(RvSize::Word, 0xbb42_d87c).unwrap(), 0x48ba_38c1);
assert_eq!(
bus.read(RvSize::Word, 0x0001_0000).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::Word, 0xf000_0000).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::Word, 0xaa03_0000).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::Word, 0xaa02_0900).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::Word, 0xbb41_0000).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0d0).unwrap(), 0xd149_b444);
assert_eq!(bus.read(RvSize::HalfWord, 0xcafe_f0d4).unwrap(), 0x695c);
assert_eq!(bus.read(RvSize::Byte, 0xcafe_f0d8).unwrap(), 0xc1);
assert_eq!(
bus.read(RvSize::HalfWord, 0xcafe_f0d0).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::Word, 0xcafe_f0d4).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::HalfWord, 0xcafe_f0f0).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0f4).unwrap(), 0x1043_0000);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0f8).unwrap(), 0x1043_1000);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0fc).unwrap(), 0x1043_2000);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f100).unwrap(), 0x1043_3000);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f104).unwrap(), 0x1043_4000);
assert_eq!(
bus.read(RvSize::Word, 0xcafe_f108).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::HalfWord, 0xcafe_f0f6).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0e0).unwrap(), 0x4de0d4f5);
assert_eq!(bus.read(RvSize::HalfWord, 0xcafe_f0e0).unwrap(), 0x4de0d4f5);
assert_eq!(
bus.log.take(),
"reg_action0 read Word; reg_action0 read HalfWord; "
);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0e4).unwrap(), 0xa813_c333);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f0e8).unwrap(), 0xba5e_ba11);
assert_eq!(bus.log.take(), "reg_action2 read Word; ");
assert_eq!(bus.read(RvSize::Word, 0xcafe_f114).unwrap(), 0xf00d_0000);
assert_eq!(bus.log.take(), "reg_array_action0[0] read Word; ");
assert_eq!(bus.read(RvSize::Word, 0xcafe_f118).unwrap(), 0xf00d_0001);
assert_eq!(bus.log.take(), "reg_array_action0[1] read Word; ");
assert_eq!(bus.read(RvSize::Word, 0xcafe_f11c).unwrap(), 0x2001_1000);
assert_eq!(bus.log.take(), "");
assert_eq!(bus.read(RvSize::Word, 0xcafe_f120).unwrap(), 0x2001_2000);
assert_eq!(bus.log.take(), "");
assert_eq!(
bus.read(RvSize::Word, 0xcafe_f130).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(bus.read(RvSize::Word, 0xcafe_f134).unwrap(), 0xd00d_0000);
assert_eq!(bus.log.take(), "reg_array_action2[0] read Word; ");
assert_eq!(bus.read(RvSize::Word, 0xcafe_f138).unwrap(), 0xd00d_0001);
assert_eq!(bus.log.take(), "reg_array_action2[1] read Word; ");
assert_eq!(bus.read(RvSize::Word, 0xcafe_f144).unwrap(), 0xd00d_0004);
assert_eq!(bus.log.take(), "reg_array_action2[4] read Word; ");
assert_eq!(
bus.read(RvSize::Word, 0xcafe_f148).unwrap_err(),
BusError::LoadAccessFault
);
assert_eq!(
bus.read(RvSize::Byte, 0xcafe_f131).unwrap_err(),
BusError::LoadAccessFault
);
}
#[test]
fn test_write_dispatch() {
let mut bus = MyBus {
rom: Ram::new(vec![0u8; 65536]),
sram: Ram::new(vec![0u8; 65536]),
dram: Ram::new(vec![0u8; 65536]),
uart0: Ram::new(vec![0u8; 128]),
uart1: Ram::new(vec![0u8; 128]),
i2c0: Ram::new(vec![0u8; 128]),
i2c1: Ram::new(vec![0u8; 128]),
i2c2: Ram::new(vec![0u8; 128]),
spi0: Ram::new(vec![0u8; 65536]),
fake: FakeBus::new(),
reg_u32: 0,
reg_u16: 0,
reg_u8: 0,
reg_array: [0; 5],
reg_array_action0: [0; 2],
reg_array_action1: [0; 2],
reg_action0: 0,
reg_action1: 0,
_fieldless_regs: (),
log: Log::new(),
};
bus.write(RvSize::Word, 0x3430, 0x3828_abcd).unwrap();
assert_eq!(bus.rom.read(RvSize::Word, 0x3430).unwrap(), 0x3828_abcd);
bus.write(RvSize::HalfWord, 0x1000_0002, 0x892a).unwrap();
bus.write(RvSize::HalfWord, 0x1000_0000, 0xb38a).unwrap();
assert_eq!(bus.sram.read(RvSize::Word, 0x0).unwrap(), 0x892a_b38a);
bus.write(RvSize::Byte, 0x2000_fffc, 0x72).unwrap();
bus.write(RvSize::Byte, 0x2000_fffd, 0x30).unwrap();
bus.write(RvSize::Byte, 0x2000_fffe, 0x29).unwrap();
bus.write(RvSize::Byte, 0x2000_ffff, 0x2a).unwrap();
assert_eq!(bus.dram.read(RvSize::Word, 0xfffc).unwrap(), 0x2a29_3072);
bus.write(RvSize::Word, 0xaa00_0020, 0x8e27_ab42).unwrap();
assert_eq!(bus.uart0.read(RvSize::Word, 0x20).unwrap(), 0x8e27_ab42);
bus.write(RvSize::Word, 0xaa01_0074, 0x38b8_e201).unwrap();
assert_eq!(bus.uart1.read(RvSize::Word, 0x74).unwrap(), 0x38b8_e201);
bus.write(RvSize::Word, 0xaa02_001c, 0xc1a4_823f).unwrap();
assert_eq!(bus.i2c0.read(RvSize::Word, 0x1c).unwrap(), 0xc1a4_823f);
bus.write(RvSize::Word, 0xaa02_0068, 0x0e8a_440b).unwrap();
assert_eq!(bus.i2c0.read(RvSize::Word, 0x68).unwrap(), 0x0e8a_440b);
bus.write(RvSize::Word, 0xaa02_0400, 0x0e8a_440b).unwrap();
assert_eq!(bus.i2c1.read(RvSize::Word, 0x00).unwrap(), 0x0e8a_440b);
bus.write(RvSize::Word, 0xaa02_0854, 0x70fa_81c9).unwrap();
assert_eq!(bus.i2c2.read(RvSize::Word, 0x54).unwrap(), 0x70fa_81c9);
bus.write(RvSize::Word, 0xbb42_d87c, 0x48ba_38c1).unwrap();
assert_eq!(bus.spi0.read(RvSize::Word, 0xd87c).unwrap(), 0x48ba_38c1);
assert_eq!(
bus.write(RvSize::Word, 0x0001_0000, 0).unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::Word, 0xf000_0000, 0).unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::Word, 0xaa03_0000, 0).unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::Word, 0xaa02_0900, 0).unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::Word, 0xbb41_0000, 0).unwrap_err(),
BusError::StoreAccessFault
);
bus.write(RvSize::Word, 0xcafe_f0d0, 0xd149_b445).unwrap();
assert_eq!(bus.reg_u32, 0xd149_b445);
bus.write(RvSize::HalfWord, 0xcafe_f0d4, 0x695c).unwrap();
assert_eq!(bus.reg_u16, 0x695c);
bus.write(RvSize::Byte, 0xcafe_f0d8, 0xc1).unwrap();
assert_eq!(bus.reg_u8, 0xc1);
assert_eq!(
bus.write(RvSize::HalfWord, 0xcafe_f0d0, 0).unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::Word, 0xcafe_f0d4, 0).unwrap_err(),
BusError::StoreAccessFault
);
bus.write(RvSize::Word, 0xcafe_f0e0, 0x82d1_aa14).unwrap();
assert_eq!(bus.reg_action0, 0x82d1_aa14);
assert_eq!(
bus.write(RvSize::Word, 0xcafe_f0f0, 0xface_ff00)
.unwrap_err(),
BusError::StoreAccessFault
);
bus.write(RvSize::Word, 0xcafe_f0f4, 0xface_0000).unwrap();
bus.write(RvSize::Word, 0xcafe_f0f8, 0xface_0100).unwrap();
bus.write(RvSize::Word, 0xcafe_f0fc, 0xface_0200).unwrap();
bus.write(RvSize::Word, 0xcafe_f100, 0xface_0300).unwrap();
bus.write(RvSize::Word, 0xcafe_f104, 0xface_0400).unwrap();
assert_eq!(
bus.reg_array,
[
0xface_0000,
0xface_0100,
0xface_0200,
0xface_0300,
0xface_0400
]
);
assert_eq!(
bus.write(RvSize::Word, 0xcafe_f108, 0xface_f000)
.unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::HalfWord, 0xcafe_f0f6, 0xface_f000)
.unwrap_err(),
BusError::StoreAccessFault
);
bus.write(RvSize::Word, 0xcafe_f0e4, 0xbaf3_e991).unwrap();
bus.write(RvSize::Word, 0xcafe_f0e4, 0x6965_617f).unwrap();
bus.write(RvSize::HalfWord, 0xcafe_f0e4, 0xc8aa).unwrap();
assert_eq!(bus.log.take(), "reg_action1 write Word 0xbaf3e991; reg_action1 write Word 0x6965617f; reg_action1 write HalfWord 0x0000c8aa; ");
bus.write(RvSize::Word, 0xcafe_f0e8, 0xb01d_face).unwrap();
assert_eq!(bus.log.take(), "reg_action2 write Word 0xb01dface; ");
bus.write(RvSize::Word, 0xcafe_f114, 0x1255).unwrap();
assert_eq!(bus.log.take(), "");
bus.write(RvSize::Word, 0xcafe_f118, 0x1255).unwrap();
assert_eq!(bus.log.take(), "");
bus.write(RvSize::Word, 0xcafe_f11c, 0xface_b01d).unwrap();
assert_eq!(
bus.log.take(),
"reg_array_action1[0] write Word 0xfaceb01d; "
);
bus.write(RvSize::Word, 0xcafe_f120, 0xface_b01e).unwrap();
assert_eq!(
bus.log.take(),
"reg_array_action1[1] write Word 0xfaceb01e; "
);
assert_eq!(
bus.write(RvSize::Word, 0xcafe_f130, 0xface_f000)
.unwrap_err(),
BusError::StoreAccessFault
);
bus.write(RvSize::Word, 0xcafe_f134, 0xface_b0dd).unwrap();
assert_eq!(
bus.log.take(),
"reg_array_action2[0] write Word 0xfaceb0dd; "
);
bus.write(RvSize::Word, 0xcafe_f138, 0xface_b0de).unwrap();
assert_eq!(
bus.log.take(),
"reg_array_action2[1] write Word 0xfaceb0de; "
);
bus.write(RvSize::Word, 0xcafe_f144, 0xface_b0df).unwrap();
assert_eq!(
bus.log.take(),
"reg_array_action2[4] write Word 0xfaceb0df; "
);
assert_eq!(
bus.write(RvSize::Word, 0xcafe_f148, 0xface_f000)
.unwrap_err(),
BusError::StoreAccessFault
);
assert_eq!(
bus.write(RvSize::Byte, 0xcafe_f133, 0xface_f000)
.unwrap_err(),
BusError::StoreAccessFault
);
}
#[test]
fn test_poll() {
let mut bus = MyBus {
rom: Ram::new(vec![0u8; 65536]),
sram: Ram::new(vec![0u8; 65536]),
dram: Ram::new(vec![0u8; 65536]),
uart0: Ram::new(vec![0u8; 128]),
uart1: Ram::new(vec![0u8; 128]),
i2c0: Ram::new(vec![0u8; 128]),
i2c1: Ram::new(vec![0u8; 128]),
i2c2: Ram::new(vec![0u8; 128]),
spi0: Ram::new(vec![0u8; 65536]),
fake: FakeBus::new(),
reg_u32: 0,
reg_u16: 0,
reg_u8: 0,
reg_array: [0; 5],
reg_array_action0: [0; 2],
reg_array_action1: [0; 2],
reg_action0: 0,
reg_action1: 0,
_fieldless_regs: (),
log: Log::new(),
};
Bus::poll(&mut bus);
assert_eq!(bus.log.take(), "poll; ");
assert_eq!(bus.fake.log.take(), "poll()\n")
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/builder/src/lib.rs | builder/src/lib.rs | // Licensed under the Apache-2.0 license
use fslock::LockFile;
use serde_derive::Deserialize;
use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs;
use std::io::{self, ErrorKind};
use std::mem::size_of;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
#[cfg(feature = "openssl")]
use caliptra_image_crypto::OsslCrypto as Crypto;
#[cfg(feature = "rustcrypto")]
use caliptra_image_crypto::RustCrypto as Crypto;
use caliptra_image_elf::ElfExecutable;
use caliptra_image_gen::{
ImageGenerator, ImageGeneratorConfig, ImageGeneratorOwnerConfig, ImageGeneratorVendorConfig,
};
use caliptra_image_types::{FwVerificationPqcKeyType, ImageBundle, ImageRevision, RomInfo};
use elf::endian::LittleEndian;
use zerocopy::IntoBytes;
mod elf_symbols;
pub mod firmware;
mod sha256;
pub mod version;
pub use elf_symbols::{elf_symbols, Symbol, SymbolBind, SymbolType, SymbolVisibility};
use once_cell::sync::Lazy;
pub const THIS_WORKSPACE_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/..");
#[derive(Debug, PartialEq)]
pub enum CiRomVersion {
Latest,
}
fn other_err(e: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> io::Error {
io::Error::new(ErrorKind::Other, e)
}
fn run_cmd(cmd: &mut Command) -> io::Result<()> {
let status = cmd.status()?;
if status.success() {
Ok(())
} else {
Err(io::Error::new(
ErrorKind::Other,
format!(
"Process {:?} {:?} exited with status code {:?}",
cmd.get_program(),
cmd.get_args(),
status.code()
),
))
}
}
pub fn run_cmd_stdout(cmd: &mut Command, input: Option<&[u8]>) -> io::Result<String> {
cmd.stdin(Stdio::piped());
cmd.stdout(Stdio::piped());
let mut child = cmd.spawn()?;
if let (Some(mut stdin), Some(input)) = (child.stdin.take(), input) {
std::io::Write::write_all(&mut stdin, input)?;
}
let out = child.wait_with_output()?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).into())
} else {
Err(other_err(format!(
"Process {:?} {:?} exited with status code {:?} stderr {}",
cmd.get_program(),
cmd.get_args(),
out.status.code(),
String::from_utf8_lossy(&out.stderr)
)))
}
}
// Represent the Cargo identity of a firmware binary.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Ord, PartialOrd)]
pub struct FwId<'a> {
// The crate name (For example, "caliptra-rom")
pub crate_name: &'a str,
// The name of the binary inside the crate. Set to the same as crate_name
// for a binary crate.
pub bin_name: &'a str,
// The features to use the build the binary
pub features: &'a [&'a str],
}
impl FwId<'_> {
/// A reasonably unique filename to be used for saving elf files containing
/// this firmware.
pub fn elf_filename(&self) -> String {
use std::fmt::Write;
let mut result = String::new();
write!(&mut result, "{}", self.crate_name).unwrap();
if self.bin_name != self.crate_name {
write!(&mut result, "--{}", self.bin_name).unwrap();
}
if !self.features.is_empty() {
write!(&mut result, "--{}", self.features.join("-")).unwrap();
}
write!(&mut result, ".elf").unwrap();
result
}
}
pub fn get_elf_path(id: &FwId) -> Option<PathBuf> {
const TARGET: &str = "riscv32imc-unknown-none-elf";
const PROFILE: &str = "firmware";
if let Some(prebuilt_dir) = std::env::var_os("CALIPTRA_PREBUILT_FW_DIR") {
Some(PathBuf::from(prebuilt_dir).join(id.elf_filename()))
} else {
let target_dir = if let Some(dir) = std::env::var_os("CARGO_TARGET_DIR") {
PathBuf::from(dir)
} else {
Path::new(THIS_WORKSPACE_DIR).join("target")
};
Some(target_dir.join(TARGET).join(PROFILE).join(id.bin_name))
}
}
/// Calls out to Cargo to build a firmware elf file. `workspace_dir` is the
/// workspace dir to build from; defaults to this workspace. `id` is the id of
/// the firmware to build. The result is the raw elf bytes.
pub fn build_firmware_elf_uncached(workspace_dir: Option<&Path>, id: &FwId) -> io::Result<Vec<u8>> {
let fwids = [id];
let result = build_firmware_elfs_uncached(workspace_dir, &fwids)?;
if result.len() != 1 {
panic!("Bug: build_firmware_elfs_uncached built more firmware than expected");
}
Ok(result.into_iter().next().unwrap().1)
}
/// Calls out to Cargo to build a firmware elf file, combining targets to
/// extract as much parallelism as possible. `workspace_dir` is the workspace
/// dir to build from; defaults to this workspace. `fwids` are the ids of the
/// firmware to build. The results will be returned in the same order as fwids,
/// with any duplicates filtered out.
pub fn build_firmware_elfs_uncached<'a>(
workspace_dir: Option<&Path>,
fwids: &'a [&'a FwId<'a>],
) -> io::Result<Vec<(&'a FwId<'a>, Vec<u8>)>> {
const TARGET: &str = "riscv32imc-unknown-none-elf";
const PROFILE: &str = "firmware";
let cargo_invocations = cargo_invocations_from_fwids(fwids)?;
let mut result_map = HashMap::new();
for invocation in cargo_invocations {
let mut features_csv = invocation.features.join(",");
if !invocation.features.contains(&"riscv") {
if !features_csv.is_empty() {
features_csv.push(',');
}
features_csv.push_str("riscv");
}
let workspace_dir = workspace_dir.unwrap_or_else(|| Path::new(THIS_WORKSPACE_DIR));
// To prevent a race condition with concurrent calls to caliptra-builder
// from other threads or processes, hold a lock until we've read the output
// binary from the filesystem (it's possible that another thread will build
// the same binary with different features before we get a chance to read it).
let _ = fs::create_dir(workspace_dir.join("target"));
let mut lock = LockFile::open(&workspace_dir.join("target/.caliptra-builder.lock"))?;
lock.lock()?;
let mut cmd = Command::new(env!("CARGO"));
cmd.current_dir(workspace_dir);
cmd.env(
"RUSTC_WRAPPER",
workspace_dir.join("builder/no_meta_rustc_wrapper.sh"),
);
if option_env!("GITHUB_ACTIONS").is_some() {
// In continuous integration, warnings are always errors.
cmd.arg("--config")
.arg("target.'cfg(all())'.rustflags = [\"-Dwarnings\"]");
}
cmd.arg("build")
.arg("--quiet")
.arg("--locked")
.arg("--target")
.arg(TARGET)
.arg("--features")
.arg(features_csv)
.arg("--no-default-features")
.arg("--profile")
.arg(PROFILE);
cmd.arg("-p").arg(invocation.crate_name);
for &fwid in invocation.fwids.iter() {
cmd.arg("--bin").arg(fwid.bin_name);
}
run_cmd(&mut cmd)?;
let target_dir = if let Some(dir) = std::env::var_os("CARGO_TARGET_DIR") {
PathBuf::from(dir)
} else {
Path::new(workspace_dir).join("target")
};
for &fwid in invocation.fwids.iter() {
result_map.insert(
fwid,
fs::read(target_dir.join(TARGET).join(PROFILE).join(fwid.bin_name))?,
);
}
}
Ok(fwids
.iter()
.map(|&fwid| {
(
fwid,
result_map.remove(fwid).expect(
"Bug: cargo_invocations_from_fwid did not complain about duplicate fwid",
),
)
})
.collect())
}
/// Compute the minimum number of cargo invocations to build all the specified
/// fwids.
fn cargo_invocations_from_fwids<'a>(
fwids: &'a [&'a FwId<'a>],
) -> io::Result<Vec<CargoInvocation<'a>>> {
{
let mut fwid_set = HashSet::new();
for fwid in fwids {
if !fwid_set.insert(fwid) {
return Err(other_err(format!("Duplicate FwId: {fwid:?}")));
}
}
}
let mut result = vec![];
let mut remaining_fwids = fwids.to_vec();
while !remaining_fwids.is_empty() {
// Maps (crate_name, features) to CargoInvocation
let mut invocation_map: HashMap<(&str, &[&str]), CargoInvocation> = HashMap::new();
remaining_fwids.retain(|&fwid| {
let invocation = invocation_map
.entry((fwid.crate_name, fwid.features))
.or_insert_with(|| CargoInvocation::new(fwid.crate_name, fwid.features));
if invocation
.fwids
.iter()
.any(|&x| x.bin_name == fwid.bin_name)
{
// The binary filenames will collide in the target directory;
// keep fwid in remaining_fwids and build this one in a separate
// cargo invocation.
return true;
}
invocation.fwids.push(fwid);
// remove fwid from remaining_fwids
false
});
result.extend(invocation_map.into_values());
}
// Make the result order consistent for unit tests, and run the largest invocations first.
result.sort_unstable_by(|a, b| {
b.fwids
.len()
.cmp(&a.fwids.len())
.then_with(|| a.crate_name.cmp(b.crate_name))
.then_with(|| a.features.cmp(b.features))
.then_with(|| a.fwids.cmp(&b.fwids))
});
Ok(result)
}
#[derive(Debug, Eq, PartialEq)]
struct CargoInvocation<'a> {
features: &'a [&'a str],
crate_name: &'a str,
fwids: Vec<&'a FwId<'a>>,
}
impl<'a> CargoInvocation<'a> {
fn new(crate_name: &'a str, features: &'a [&'a str]) -> Self {
Self {
features,
crate_name,
fwids: Vec::new(),
}
}
}
// TODO: Rename this get_firmware_elf, as it doesn't build when the
// CALIPTRA_PREBUILT_FW_DIR environment variable is set.
pub fn build_firmware_elf(id: &FwId<'static>) -> io::Result<Arc<Vec<u8>>> {
if !crate::firmware::REGISTERED_FW.contains(&id) {
return Err(other_err(format!("FwId has not been registered. Make sure it has been added to the REGISTERED_FW array: {id:?}")));
}
if let Some(fw_dir) = std::env::var_os("CALIPTRA_PREBUILT_FW_DIR") {
let path = PathBuf::from(fw_dir).join(id.elf_filename());
let result = std::fs::read(&path).map_err(|e| {
io::Error::new(
e.kind(),
format!(
"CALIPTRA_PREBUILT_FW_DIR environment variable was set, while reading {}, {}",
path.display(),
e
),
)
})?;
return Ok(Arc::new(result));
}
type CacheEntry = Arc<Mutex<Arc<Vec<u8>>>>;
static CACHE: Lazy<Mutex<HashMap<FwId, CacheEntry>>> = Lazy::new(|| {
let result = HashMap::new();
Mutex::new(result)
});
let result_mutex: Arc<Mutex<Arc<Vec<u8>>>>;
let mut result_mutex_guard;
{
let mut cache_guard = CACHE.lock().unwrap();
let entry = cache_guard.entry(*id);
match entry {
Entry::Occupied(entry) => {
let result = entry.get().clone();
drop(cache_guard);
return Ok(result.lock().unwrap().clone());
}
Entry::Vacant(entry) => {
result_mutex = Default::default();
let result_mutex_cloned = result_mutex.clone();
result_mutex_guard = result_mutex.lock().unwrap();
// Add the already-locked mutex to the map so other threads
// needing the same firmware wait for us to populate it.
entry.insert(result_mutex_cloned);
}
}
}
let result = Arc::new(build_firmware_elf_uncached(None, id)?);
*result_mutex_guard = result.clone();
Ok(result)
}
// Returns the ROM version to be used for CI testing specified in the environment variable "CPTRA_CI_ROM_VERSION"
// Default is Latest
pub fn get_ci_rom_version() -> CiRomVersion {
match std::env::var("CPTRA_CI_ROM_VERSION").as_deref() {
Ok(version) => panic!("Unknown CI ROM version \'{}\'", version),
Err(_) => CiRomVersion::Latest,
}
}
/// Returns the most appropriate ROM for use when testing non-ROM code against
/// a particular hardware version. DO NOT USE this for ROM-only tests.
pub fn rom_for_fw_integration_tests() -> io::Result<Cow<'static, [u8]>> {
let rom_from_env = firmware::rom_from_env();
match get_ci_rom_version() {
CiRomVersion::Latest => Ok(build_firmware_rom(rom_from_env)?.into()),
}
}
/// Returns the most appropriate ROM for use when testing non-ROM code against
/// a particular hardware version. DO NOT USE this for ROM-only tests.
pub fn rom_for_fw_integration_tests_fpga(fpga: bool) -> io::Result<Cow<'static, [u8]>> {
let rom_from_env = firmware::rom_from_env_fpga(fpga);
match get_ci_rom_version() {
CiRomVersion::Latest => Ok(build_firmware_rom(rom_from_env)?.into()),
}
}
pub fn build_firmware_rom(id: &FwId<'static>) -> io::Result<Vec<u8>> {
let elf_bytes = build_firmware_elf(id)?;
elf2rom(&elf_bytes)
}
pub fn elf2rom(elf_bytes: &[u8]) -> io::Result<Vec<u8>> {
let mut result = vec![0u8; 0x18000];
let elf = elf::ElfBytes::<LittleEndian>::minimal_parse(elf_bytes).map_err(other_err)?;
let Some(segments) = elf.segments() else {
return Err(other_err("ELF file has no segments"));
};
for segment in segments {
if segment.p_type != elf::abi::PT_LOAD {
continue;
}
let file_offset = segment.p_offset as usize;
let mem_offset = segment.p_paddr as usize;
let len = segment.p_filesz as usize;
let Some(src_bytes) = elf_bytes.get(file_offset..file_offset + len) else {
return Err(other_err(format!(
"segment at 0x{:x} out of file bounds",
segment.p_offset
)));
};
if len == 0 {
continue;
}
let Some(dest_bytes) = result.get_mut(mem_offset..mem_offset + len) else {
return Err(other_err(format!(
"segment at 0x{mem_offset:04x}..0x{:04x} exceeds the ROM region \
of 0x0000..0x{:04x}",
mem_offset + len,
result.len()
)));
};
dest_bytes.copy_from_slice(src_bytes);
}
let symbols = elf_symbols(elf_bytes)?;
if let Some(rom_info_sym) = symbols.iter().find(|s| s.name == "CALIPTRA_ROM_INFO") {
let rom_info_start = rom_info_sym.value as usize;
let rom_info = RomInfo {
sha256_digest: sha256::sha256_word_reversed(&result[0..rom_info_start]),
revision: image_revision()?,
flags: 0,
version: version::get_rom_version(),
rsvd: Default::default(),
};
let rom_info_dest = result
.get_mut(rom_info_start..rom_info_start + size_of::<RomInfo>())
.ok_or_else(|| other_err("No space in ROM for CALIPTRA_ROM_INFO"))?;
rom_info_dest.copy_from_slice(rom_info.as_bytes());
}
Ok(result)
}
pub fn elf_size(elf_bytes: &[u8]) -> io::Result<u64> {
let elf = elf::ElfBytes::<LittleEndian>::minimal_parse(elf_bytes).map_err(other_err)?;
let Some(segments) = elf.segments() else {
return Err(other_err("ELF file has no segments"));
};
let mut min_addr = u64::MAX;
let mut max_addr = u64::MIN;
for segment in segments {
if segment.p_type != elf::abi::PT_LOAD || segment.p_filesz == 0 {
continue;
}
min_addr = min_addr.min(segment.p_paddr);
max_addr = max_addr.max(segment.p_paddr + segment.p_filesz);
}
Ok(max_addr.saturating_sub(min_addr))
}
#[derive(Clone, Deserialize)]
pub struct ImageOptions {
pub fmc_version: u16,
pub app_version: u32,
pub fw_svn: u32,
pub vendor_config: ImageGeneratorVendorConfig,
pub owner_config: Option<ImageGeneratorOwnerConfig>,
pub pqc_key_type: FwVerificationPqcKeyType,
}
impl Default for ImageOptions {
fn default() -> Self {
Self {
fmc_version: Default::default(),
app_version: Default::default(),
fw_svn: Default::default(),
vendor_config: caliptra_image_fake_keys::VENDOR_CONFIG_KEY_0,
owner_config: Some(caliptra_image_fake_keys::OWNER_CONFIG),
pqc_key_type: FwVerificationPqcKeyType::MLDSA,
}
}
}
pub fn build_and_sign_image(
fmc: &FwId<'static>,
app: &FwId<'static>,
opts: ImageOptions,
) -> anyhow::Result<ImageBundle> {
let fmc_elf = build_firmware_elf(fmc)?;
let app_elf = build_firmware_elf(app)?;
let gen = ImageGenerator::new(Crypto::default());
let image = gen.generate(&ImageGeneratorConfig {
fmc: ElfExecutable::new(&fmc_elf, opts.fmc_version as u32, image_revision()?)?,
runtime: ElfExecutable::new(&app_elf, opts.app_version, image_revision()?)?,
fw_svn: opts.fw_svn,
vendor_config: opts.vendor_config,
owner_config: opts.owner_config,
pqc_key_type: opts.pqc_key_type,
})?;
Ok(image)
}
fn image_revision() -> io::Result<ImageRevision> {
if std::env::var_os("CALIPTRA_IMAGE_NO_GIT_REVISION").is_some() {
// Sometimes needed to build a consistent ROM image from different
// commits.
Ok(*b"~~~~~NO_GIT_REVISION")
} else {
image_revision_from_git_repo()
}
}
fn image_revision_from_git_repo() -> io::Result<ImageRevision> {
let commit_id = run_cmd_stdout(Command::new("git").arg("rev-parse").arg("HEAD"), None)?;
let rtl_git_status =
run_cmd_stdout(Command::new("git").arg("status").arg("--porcelain"), None)?;
image_revision_from_str(&commit_id, rtl_git_status.is_empty())
}
fn image_revision_from_str(commit_id_str: &str, is_clean: bool) -> io::Result<ImageRevision> {
// (dirtdirtdirtdirtdirt)
const DIRTY_SUFFIX: [u8; 10] = [0xd1, 0x47, 0xd1, 0x47, 0xd1, 0x47, 0xd1, 0x47, 0xd1, 0x47];
let mut commit_id = ImageRevision::default();
hex::decode_to_slice(commit_id_str.trim(), &mut commit_id).map_err(|e| {
other_err(format!(
"Unable to decode git commit {commit_id_str:?}: {e}"
))
})?;
if !is_clean {
// spoil the revision because the git client is dirty
commit_id[10..].copy_from_slice(&DIRTY_SUFFIX);
}
Ok(commit_id)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_build_firmware() {
// Ensure that we can build the ELF and elf2rom can parse it
build_firmware_rom(&firmware::caliptra_builder_tests::FWID).unwrap();
}
#[test]
fn test_build_firmware_not_registered() {
static FWID: FwId = FwId {
crate_name: "caliptra-drivers-test-bin",
bin_name: "test_success2",
features: &[],
};
// Ensure that we can build the ELF and elf2rom can parse it
let err = build_firmware_rom(&FWID).unwrap_err();
assert!(err.to_string().contains(
"FwId has not been registered. Make sure it has been added to the REGISTERED_FW array"
));
}
#[test]
fn test_elf2rom_golden() {
let rom_bytes = elf2rom(include_bytes!("testdata/example.elf")).unwrap();
assert_eq!(&rom_bytes, include_bytes!("testdata/example.rom.golden"));
}
#[test]
fn test_elf_size() {
assert_eq!(
elf_size(include_bytes!("testdata/example.elf")).unwrap(),
4096
);
}
#[test]
fn test_image_revision_from_str() {
assert_eq!(
image_revision_from_str("d6a462a63a9cf2dafa5bbc6cf78b1fccc308009a", true).unwrap(),
[
0xd6, 0xa4, 0x62, 0xa6, 0x3a, 0x9c, 0xf2, 0xda, 0xfa, 0x5b, 0xbc, 0x6c, 0xf7, 0x8b,
0x1f, 0xcc, 0xc3, 0x08, 0x00, 0x9a
]
);
assert_eq!(
image_revision_from_str("d6a462a63a9cf2dafa5bbc6cf78b1fccc308009a\n", true).unwrap(),
[
0xd6, 0xa4, 0x62, 0xa6, 0x3a, 0x9c, 0xf2, 0xda, 0xfa, 0x5b, 0xbc, 0x6c, 0xf7, 0x8b,
0x1f, 0xcc, 0xc3, 0x08, 0x00, 0x9a
]
);
assert_eq!(
image_revision_from_str("d6a462a63a9cf2dafa5bbc6cf78b1fccc308009a", false).unwrap(),
[
0xd6, 0xa4, 0x62, 0xa6, 0x3a, 0x9c, 0xf2, 0xda, 0xfa, 0x5b, 0xd1, 0x47, 0xd1, 0x47,
0xd1, 0x47, 0xd1, 0x47, 0xd1, 0x47
]
);
assert_eq!(
image_revision_from_str("d6a462a63a9cf2dafa5bbc6cf78b1fccc30800", false).unwrap_err().to_string(),
"Unable to decode git commit \"d6a462a63a9cf2dafa5bbc6cf78b1fccc30800\": Invalid string length");
assert!(image_revision_from_str("d6a462a63a9cf2dafa5bbc6cf78b1fccc308009g", true).is_err());
}
mod cargo_invocations_from_fwid {
use super::*;
#[test]
fn test_success() {
let fwids = [
&FwId {
crate_name: "initech-firmware",
bin_name: "initech-firmware",
features: &["pc-load-letter"],
},
&FwId {
crate_name: "initech-firmware",
bin_name: "initech-firmware",
features: &["pc-load-letter", "uart"],
},
&FwId {
crate_name: "test-fw",
bin_name: "test1",
features: &["pc-load-letter"],
},
&FwId {
crate_name: "test-fw",
bin_name: "test2",
features: &["pc-load-letter"],
},
&FwId {
crate_name: "test-fw",
bin_name: "test2",
features: &["pc-load-letter", "uart"],
},
&FwId {
crate_name: "test-fw",
bin_name: "test3",
features: &["pc-load-letter"],
},
&FwId {
crate_name: "test-fw2",
bin_name: "test1",
features: &["pc-load-letter"],
},
&FwId {
crate_name: "test-fw2",
bin_name: "test4",
features: &["pc-load-letter"],
},
];
assert_eq!(
vec![
CargoInvocation {
features: &["pc-load-letter",],
crate_name: "test-fw",
fwids: vec![
&FwId {
crate_name: "test-fw",
bin_name: "test1",
features: &["pc-load-letter",],
},
&FwId {
crate_name: "test-fw",
bin_name: "test2",
features: &["pc-load-letter",],
},
&FwId {
crate_name: "test-fw",
bin_name: "test3",
features: &["pc-load-letter",],
},
]
},
CargoInvocation {
features: &["pc-load-letter",],
crate_name: "test-fw2",
fwids: vec![
&FwId {
crate_name: "test-fw2",
bin_name: "test1",
features: &["pc-load-letter",],
},
&FwId {
crate_name: "test-fw2",
bin_name: "test4",
features: &["pc-load-letter",],
},
],
},
CargoInvocation {
features: &["pc-load-letter",],
crate_name: "initech-firmware",
fwids: vec![&FwId {
crate_name: "initech-firmware",
bin_name: "initech-firmware",
features: &["pc-load-letter"],
},],
},
CargoInvocation {
features: &["pc-load-letter", "uart",],
crate_name: "initech-firmware",
fwids: vec![&FwId {
crate_name: "initech-firmware",
bin_name: "initech-firmware",
features: &["pc-load-letter", "uart",],
},]
},
CargoInvocation {
features: &["pc-load-letter", "uart",],
crate_name: "test-fw",
fwids: vec![&FwId {
crate_name: "test-fw",
bin_name: "test2",
features: &["pc-load-letter", "uart",],
},],
},
],
cargo_invocations_from_fwids(&fwids).unwrap()
)
}
#[test]
fn test_duplicate() {
let fwids = [
&FwId {
crate_name: "initech-firmware",
bin_name: "initech-firmware",
features: &["pc-load-letter"],
},
&FwId {
crate_name: "initech-firmware",
bin_name: "initech-firmware",
features: &["pc-load-letter"],
},
];
assert!(cargo_invocations_from_fwids(&fwids)
.unwrap_err()
.to_string()
.contains("Duplicate FwId"));
}
}
#[test]
fn test_fwid_elf_filename() {
assert_eq!(
FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &[]
}
.elf_filename(),
"caliptra-rom.elf"
);
assert_eq!(
FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["uart", "debug"]
}
.elf_filename(),
"caliptra-rom--uart-debug.elf"
);
assert_eq!(
&FwId {
crate_name: "caliptra-test",
bin_name: "smoke_test",
features: &[]
}
.elf_filename(),
"caliptra-test--smoke_test.elf"
);
assert_eq!(
&FwId {
crate_name: "caliptra-test",
bin_name: "smoke_test",
features: &["uart", "debug"]
}
.elf_filename(),
"caliptra-test--smoke_test--uart-debug.elf"
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/builder/src/version.rs | builder/src/version.rs | // Licensed under the Apache-2.0 license
pub const ROM_VERSION_MAJOR: u16 = 2;
pub const ROM_VERSION_MINOR: u16 = 0;
pub const ROM_VERSION_PATCH: u16 = 0;
pub const FMC_VERSION_MAJOR: u16 = 2;
pub const FMC_VERSION_MINOR: u16 = 0;
pub const FMC_VERSION_PATCH: u16 = 0;
pub const RUNTIME_VERSION_MAJOR: u32 = 2;
pub const RUNTIME_VERSION_MINOR: u32 = 0;
pub const RUNTIME_VERSION_PATCH: u32 = 0;
// ROM Version - 16 bits
// Major - 5 bits [15:11]
// Minor - 5 bits [10:6]
// Patch - 6 bits [5:0]
pub fn get_rom_version() -> u16 {
((ROM_VERSION_MAJOR & 0x1F) << 11)
| ((ROM_VERSION_MINOR & 0x1F) << 6)
| (ROM_VERSION_PATCH & 0x3F)
}
// FMC Version - 16 bits
// Major - 5 bits [15:11]
// Minor - 5 bits [10:6]
// Patch - 6 bits [5:0]
pub fn get_fmc_version() -> u16 {
((FMC_VERSION_MAJOR & 0x1F) << 11)
| ((FMC_VERSION_MINOR & 0x1F) << 6)
| (FMC_VERSION_PATCH & 0x3F)
}
// Runtime Version - 32 bits
// Major - 8 bits [31:24]
// Minor - 8 bits [23:16]
// Patch - 16 bits [15:0]
pub fn get_runtime_version() -> u32 {
((RUNTIME_VERSION_MAJOR & 0xFF) << 24)
| ((RUNTIME_VERSION_MINOR & 0xFF) << 16)
| (RUNTIME_VERSION_PATCH & 0xFFFF)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/builder/src/sha256.rs | builder/src/sha256.rs | // Licensed under the Apache-2.0 license
#[cfg(feature = "openssl")]
use caliptra_image_crypto::OsslCrypto as Crypto;
#[cfg(feature = "rustcrypto")]
use caliptra_image_crypto::RustCrypto as Crypto;
use caliptra_image_gen::{ImageGeneratorCrypto, ImageGeneratorHasher};
pub fn sha256_word_reversed(bytes: &[u8]) -> [u32; 8] {
let mut sha = Crypto::default().sha256_start();
for i in 0..bytes.len() / 4 {
let word = u32::from_le_bytes(bytes[i * 4..][..4].try_into().unwrap());
sha.update(&word.swap_bytes().to_le_bytes());
}
sha.finish()
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/builder/src/elf_symbols.rs | builder/src/elf_symbols.rs | // Licensed under the Apache-2.0 license
use std::io;
use elf::endian::LittleEndian;
use super::other_err;
pub fn elf_symbols(elf_bytes: &[u8]) -> io::Result<Vec<Symbol>> {
let elf = elf::ElfBytes::<LittleEndian>::minimal_parse(elf_bytes).map_err(other_err)?;
let Some((symbols, strings)) = elf.symbol_table().map_err(other_err)? else {
return Ok(vec![]);
};
let mut result = vec![];
for sym in symbols.iter() {
let sym_name = strings.get(sym.st_name as usize).map_err(|e| {
other_err(format!(
"Could not parse symbol string at index {}: {e}",
sym.st_name
))
})?;
result.push(Symbol {
name: sym_name,
size: sym.st_size,
value: sym.st_value,
// Unwrap cannot panic because st_vis is only 2 bits
visibility: SymbolVisibility::try_from(sym.st_vis()).unwrap(),
// Unwrap cannot panic because st_symtype is only 4 bits
ty: SymbolType::try_from(sym.st_symtype()).unwrap(),
// Unwrap cannot panic because st_bind is only 4 bits
bind: SymbolBind::try_from(sym.st_bind()).unwrap(),
});
}
Ok(result)
}
#[derive(Debug, Eq, PartialEq)]
pub struct Symbol<'a> {
pub name: &'a str,
pub size: u64,
pub value: u64,
pub ty: SymbolType,
pub visibility: SymbolVisibility,
pub bind: SymbolBind,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SymbolType {
None = 0,
Object = 1,
Func = 2,
Section = 3,
File = 4,
Common = 5,
Tls = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Os10 = 10,
Os11 = 11,
Os12 = 12,
Proc13 = 13,
Proc14 = 14,
Proc15 = 15,
}
impl TryFrom<u8> for SymbolType {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::None),
1 => Ok(Self::Object),
2 => Ok(Self::Func),
3 => Ok(Self::Section),
4 => Ok(Self::File),
5 => Ok(Self::Common),
6 => Ok(Self::Tls),
7 => Ok(Self::Reserved7),
8 => Ok(Self::Reserved8),
9 => Ok(Self::Reserved9),
10 => Ok(Self::Os10),
11 => Ok(Self::Os11),
12 => Ok(Self::Os12),
13 => Ok(Self::Proc13),
14 => Ok(Self::Proc14),
15 => Ok(Self::Proc15),
_ => Err(()),
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SymbolVisibility {
Default = 0,
Internal = 1,
Hidden = 2,
Protected = 3,
}
impl TryFrom<u8> for SymbolVisibility {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::Default),
1 => Ok(Self::Internal),
2 => Ok(Self::Hidden),
3 => Ok(Self::Protected),
_ => Err(()),
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SymbolBind {
Local = 0,
Global = 1,
Weak = 2,
Reserved3 = 3,
Reserved4 = 4,
Reserved5 = 5,
Reserved6 = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Os10 = 10,
Os11 = 11,
Os12 = 12,
Proc13 = 13,
Proc14 = 14,
Proc15 = 15,
}
impl TryFrom<u8> for SymbolBind {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::Local),
1 => Ok(Self::Global),
2 => Ok(Self::Weak),
3 => Ok(Self::Reserved3),
4 => Ok(Self::Reserved4),
5 => Ok(Self::Reserved5),
6 => Ok(Self::Reserved6),
7 => Ok(Self::Reserved7),
8 => Ok(Self::Reserved8),
9 => Ok(Self::Reserved9),
10 => Ok(Self::Os10),
11 => Ok(Self::Os11),
12 => Ok(Self::Os12),
13 => Ok(Self::Proc13),
14 => Ok(Self::Proc14),
15 => Ok(Self::Proc15),
_ => Err(()),
}
}
}
#[cfg(test)]
mod test {
use crate::{self as caliptra_builder, SymbolBind, SymbolType, SymbolVisibility};
#[test]
fn test_elf_symbols() {
let symbols =
caliptra_builder::elf_symbols(include_bytes!("testdata/example.elf")).unwrap();
let bss_start = symbols.iter().find(|s| s.name == "BSS_START");
assert_eq!(
bss_start,
Some(&caliptra_builder::elf_symbols::Symbol {
name: "BSS_START",
size: 0,
value: 0x50000000,
ty: SymbolType::None,
visibility: SymbolVisibility::Default,
bind: SymbolBind::Global,
})
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/builder/src/firmware.rs | builder/src/firmware.rs | // Licensed under the Apache-2.0 license
// Centralized list of all firmware targets. This allows us to compile them all
// ahead of time for executing tests on hosts that can't compile rust code.
use crate::FwId;
pub fn rom_from_env() -> &'static FwId<'static> {
match std::env::var("CPTRA_ROM_TYPE").as_ref().map(|s| s.as_str()) {
Ok("ROM") => &ROM,
Ok("ROM_WITHOUT_UART") => &ROM,
Ok("ROM_WITH_UART") => &ROM_WITH_UART,
Ok(s) => panic!("unexpected CPRTA_TEST_ROM env-var value: {s:?}"),
Err(_) => &ROM_WITH_UART,
}
}
pub fn rom_from_env_fpga(fpga: bool) -> &'static FwId<'static> {
match (
std::env::var("CPTRA_ROM_TYPE").as_ref().map(|s| s.as_str()),
fpga,
) {
(Ok("ROM"), _) => &ROM,
(Ok("ROM_WITHOUT_UART"), true) => &ROM_FPGA,
(Ok("ROM_WITHOUT_UART"), false) => &ROM,
(Ok("ROM_WITH_UART"), true) => &ROM_FPGA_WITH_UART,
(Ok("ROM_WITH_UART"), false) => &ROM_WITH_UART,
(Ok(s), _) => panic!("unexpected CPRTA_TEST_ROM env-var value: {s:?}"),
(Err(_), true) => &ROM_FPGA_WITH_UART,
(Err(_), false) => &ROM_WITH_UART,
}
}
pub fn fake_rom(fpga: bool) -> &'static FwId<'static> {
if fpga {
&ROM_FAKE_WITH_UART_FPGA
} else {
&ROM_FAKE_WITH_UART
}
}
pub const ROM: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &[],
};
pub const ROM_FPGA: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["fpga_realtime"],
};
pub const ROM_WITH_UART: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["emu"],
};
pub const ROM_FAKE_WITH_UART: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["emu", "fake-rom"],
};
pub const ROM_FAKE_WITH_UART_FPGA: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["emu", "fake-rom", "fpga_realtime"],
};
pub const ROM_WITH_FIPS_TEST_HOOKS: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["fips-test-hooks"],
};
pub const ROM_WITH_FIPS_TEST_HOOKS_FPGA: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["fips-test-hooks", "fpga_realtime"],
};
// TODO: delete this when AXI DMA is fixed in the FPGA
pub const ROM_FPGA_WITH_UART: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "caliptra-rom",
features: &["emu", "fpga_realtime"],
};
pub const FMC_WITH_UART: FwId = FwId {
crate_name: "caliptra-fmc",
bin_name: "caliptra-fmc",
features: &["emu"],
};
pub const FMC_FAKE_WITH_UART: FwId = FwId {
crate_name: "caliptra-fmc",
bin_name: "caliptra-fmc",
features: &["emu", "fake-fmc"],
};
// TODO: delete this when AXI DMA is fixed in the FPGA
pub const FMC_FPGA_WITH_UART: FwId = FwId {
crate_name: "caliptra-fmc",
bin_name: "caliptra-fmc",
features: &["emu", "fpga_realtime"],
};
pub const APP: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["fips_self_test"],
};
pub const APP_WITH_UART: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["emu", "fips_self_test"],
};
pub const APP_WITH_UART_OCP_LOCK: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["emu", "fips_self_test", "ocp-lock"],
};
pub const APP_WITH_UART_FIPS_TEST_HOOKS: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["emu", "fips_self_test", "fips-test-hooks"],
};
pub const APP_WITH_UART_FIPS_TEST_HOOKS_FPGA: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["emu", "fips_self_test", "fips-test-hooks", "fpga_subsystem"],
};
pub const APP_WITH_UART_FPGA: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["emu", "fips_self_test", "fpga_realtime"],
};
pub const APP_WITH_UART_OCP_LOCK_FPGA: FwId = FwId {
crate_name: "caliptra-runtime",
bin_name: "caliptra-runtime",
features: &["emu", "fips_self_test", "fpga_realtime", "ocp-lock"],
};
pub const APP_ZEROS: FwId = FwId {
crate_name: "caliptra-zeros",
bin_name: "caliptra-zeros",
features: &[],
};
pub const FMC_ZEROS: FwId = FwId {
crate_name: "caliptra-zeros",
bin_name: "caliptra-zeros",
features: &["fmc"],
};
pub mod caliptra_builder_tests {
use super::*;
pub const FWID: FwId = FwId {
crate_name: "caliptra-drivers-test-bin",
bin_name: "test_success",
features: &[],
};
}
pub mod hw_model_tests {
use super::*;
const BASE_FWID: FwId = FwId {
crate_name: "caliptra-hw-model-test-fw",
bin_name: "",
features: &["emu"],
};
pub const MAILBOX_RESPONDER: FwId = FwId {
bin_name: "mailbox_responder",
..BASE_FWID
};
pub const MAILBOX_SENDER: FwId = FwId {
bin_name: "mailbox_sender",
..BASE_FWID
};
pub const MCU_HITLESS_UPDATE_FLOW: FwId = FwId {
bin_name: "mcu_hitless_update_flow",
..BASE_FWID
};
pub const TEST_ICCM_BYTE_WRITE: FwId = FwId {
bin_name: "test_iccm_byte_write",
..BASE_FWID
};
pub const TEST_ICCM_UNALIGNED_WRITE: FwId = FwId {
bin_name: "test_iccm_unaligned_write",
..BASE_FWID
};
pub const TEST_ICCM_WRITE_LOCKED: FwId = FwId {
bin_name: "test_iccm_write_locked",
..BASE_FWID
};
pub const TEST_INVALID_INSTRUCTION: FwId = FwId {
bin_name: "test_invalid_instruction",
..BASE_FWID
};
pub const TEST_WRITE_TO_ROM: FwId = FwId {
bin_name: "test_write_to_rom",
..BASE_FWID
};
pub const TEST_ICCM_DOUBLE_BIT_ECC: FwId = FwId {
bin_name: "test_iccm_double_bit_ecc",
..BASE_FWID
};
pub const TEST_DCCM_DOUBLE_BIT_ECC: FwId = FwId {
bin_name: "test_dccm_double_bit_ecc",
..BASE_FWID
};
pub const TEST_UNITIALIZED_READ: FwId = FwId {
bin_name: "test_uninitialized_read",
..BASE_FWID
};
pub const TEST_PCR_EXTEND: FwId = FwId {
bin_name: "test_pcr_extend",
..BASE_FWID
};
}
pub mod driver_tests {
use super::*;
const BASE_FWID: FwId = FwId {
crate_name: "caliptra-drivers-test-bin",
bin_name: "",
features: &["emu"],
};
pub const DOE: FwId = FwId {
bin_name: "doe",
..BASE_FWID
};
pub const AES: FwId = FwId {
bin_name: "aes",
..BASE_FWID
};
pub const ECC384: FwId = FwId {
bin_name: "ecc384",
..BASE_FWID
};
pub const ECC384_SIGN_VALIDATION_FAILURE: FwId = FwId {
bin_name: "ecc384_sign_validation_failure",
..BASE_FWID
};
pub const ERROR_REPORTER: FwId = FwId {
bin_name: "error_reporter",
..BASE_FWID
};
pub const HMAC: FwId = FwId {
bin_name: "hmac",
..BASE_FWID
};
pub const KEYVAULT: FwId = FwId {
bin_name: "keyvault",
..BASE_FWID
};
pub const KEYVAULT_FPGA: FwId = FwId {
bin_name: "keyvault",
features: &["emu", "fpga_realtime"],
..BASE_FWID
};
pub const MAILBOX_DRIVER_RESPONDER: FwId = FwId {
bin_name: "mailbox_driver_responder",
..BASE_FWID
};
pub const MAILBOX_DRIVER_SENDER: FwId = FwId {
bin_name: "mailbox_driver_sender",
..BASE_FWID
};
pub const MAILBOX_DRIVER_NEGATIVE_TESTS: FwId = FwId {
bin_name: "mailbox_driver_negative_tests",
..BASE_FWID
};
pub const MBOX_SEND_TXN_DROP: FwId = FwId {
bin_name: "mbox_send_txn_drop",
..BASE_FWID
};
pub const ML_DSA87: FwId = FwId {
bin_name: "ml_dsa87",
..BASE_FWID
};
pub const ML_DSA87_EXTERNAL_MU: FwId = FwId {
bin_name: "ml_dsa87_external_mu",
..BASE_FWID
};
pub const ML_KEM: FwId = FwId {
bin_name: "ml_kem",
..BASE_FWID
};
pub const PCRBANK: FwId = FwId {
bin_name: "pcrbank",
..BASE_FWID
};
pub const PRECONDITIONED_KEYS: FwId = FwId {
bin_name: "preconditioned_keys",
..BASE_FWID
};
pub const SHA1: FwId = FwId {
bin_name: "sha1",
..BASE_FWID
};
pub const SHA256: FwId = FwId {
bin_name: "sha256",
..BASE_FWID
};
pub const SHA384: FwId = FwId {
bin_name: "sha384",
..BASE_FWID
};
pub const SHA3: FwId = FwId {
bin_name: "sha3",
..BASE_FWID
};
pub const SHA512: FwId = FwId {
bin_name: "sha512",
..BASE_FWID
};
pub const SHA2_512_384ACC: FwId = FwId {
bin_name: "sha2_512_384acc",
..BASE_FWID
};
pub const STATUS_REPORTER: FwId = FwId {
bin_name: "status_reporter",
..BASE_FWID
};
pub const TEST_LMS_24: FwId = FwId {
bin_name: "test_lms_24",
..BASE_FWID
};
pub const TEST_LMS_32: FwId = FwId {
bin_name: "test_lms_32",
..BASE_FWID
};
pub const TEST_NEGATIVE_LMS: FwId = FwId {
bin_name: "test_negative_lms",
..BASE_FWID
};
pub const TEST_UART: FwId = FwId {
bin_name: "test_uart",
..BASE_FWID
};
pub const CSRNG: FwId = FwId {
bin_name: "csrng",
..BASE_FWID
};
pub const CSRNG2: FwId = FwId {
bin_name: "csrng2",
..BASE_FWID
};
pub const CSRNG_PASS_HEALTH_TESTS: FwId = FwId {
bin_name: "csrng_pass_health_tests",
..BASE_FWID
};
pub const CSRNG_FAIL_REPCNT_TESTS: FwId = FwId {
bin_name: "csrng_fail_repcnt_tests",
..BASE_FWID
};
pub const CSRNG_FAIL_ADAPTP_TESTS: FwId = FwId {
bin_name: "csrng_fail_adaptp_tests",
..BASE_FWID
};
pub const TRNG_DRIVER_RESPONDER: FwId = FwId {
bin_name: "trng_driver_responder",
..BASE_FWID
};
pub const PERSISTENT: FwId = FwId {
bin_name: "persistent",
..BASE_FWID
};
pub const DMA_SHA384: FwId = FwId {
bin_name: "dma_sha384",
..BASE_FWID
};
// TODO: delete this when AXI DMA is fixed in the FPGA
pub const DMA_SHA384_FPGA: FwId = FwId {
bin_name: "dma_sha384",
features: &["emu", "fpga_subsystem"],
..BASE_FWID
};
pub const OCP_LOCK: FwId = FwId {
bin_name: "ocp_lock",
features: &["fpga_realtime"],
..BASE_FWID
};
pub const OCP_LOCK_WARM_RESET: FwId = FwId {
bin_name: "ocp_lock_warm_reset",
features: &["fpga_realtime"],
..BASE_FWID
};
pub const DMA_AES: FwId = FwId {
bin_name: "dma_aes",
features: &["emu", "fpga_subsystem"],
..BASE_FWID
};
pub const AXI_BYPASS: FwId = FwId {
bin_name: "axi_bypass",
features: &["emu", "fpga_subsystem"],
..BASE_FWID
};
}
pub mod rom_tests {
use super::*;
const BASE_FWID: FwId = FwId {
crate_name: "caliptra-rom",
bin_name: "",
features: &["emu"],
};
pub const ASM_TESTS: FwId = FwId {
bin_name: "asm_tests",
..BASE_FWID
};
pub const TEST_FMC_WITH_UART: FwId = FwId {
crate_name: "caliptra-rom-test-fmc",
bin_name: "caliptra-rom-test-fmc",
features: &["emu"],
};
pub const TEST_RT_WITH_UART: FwId = FwId {
crate_name: "caliptra-rom-test-rt",
bin_name: "caliptra-rom-test-rt",
features: &["emu"],
};
pub const FAKE_TEST_FMC_WITH_UART: FwId = FwId {
crate_name: "caliptra-rom-test-fmc",
bin_name: "caliptra-rom-test-fmc",
features: &["emu", "fake-fmc"],
};
pub const TEST_FMC_INTERACTIVE: FwId = FwId {
crate_name: "caliptra-rom-test-fmc",
bin_name: "caliptra-rom-test-fmc",
features: &["emu", "interactive_test_fmc"],
};
pub const FAKE_TEST_FMC_INTERACTIVE: FwId = FwId {
crate_name: "caliptra-rom-test-fmc",
bin_name: "caliptra-rom-test-fmc",
features: &["emu", "interactive_test_fmc", "fake-fmc"],
};
pub const TEST_PMP_TESTS: FwId = FwId {
bin_name: "pmp_tests",
..BASE_FWID
};
}
pub mod runtime_tests {
use super::*;
const RUNTIME_TEST_FWID_BASE: FwId = FwId {
crate_name: "caliptra-runtime-test-bin",
bin_name: "",
features: &["emu", "riscv", "runtime"],
};
pub const BOOT: FwId = FwId {
bin_name: "boot",
..RUNTIME_TEST_FWID_BASE
};
pub const MBOX: FwId = FwId {
bin_name: "mbox",
..RUNTIME_TEST_FWID_BASE
};
pub const MBOX_FPGA: FwId = FwId {
bin_name: "mbox",
features: &["emu", "riscv", "runtime", "fpga_realtime"],
..RUNTIME_TEST_FWID_BASE
};
// Used to test updates between RT FW images.
pub const MBOX_WITHOUT_UART: FwId = FwId {
bin_name: "mbox",
features: &["riscv", "runtime"],
..RUNTIME_TEST_FWID_BASE
};
pub const MBOX_WITHOUT_UART_FPGA: FwId = FwId {
bin_name: "mbox",
features: &["riscv", "runtime", "fpga_realtime"],
..RUNTIME_TEST_FWID_BASE
};
pub const PERSISTENT_RT: FwId = FwId {
bin_name: "persistent_rt",
..RUNTIME_TEST_FWID_BASE
};
pub const MOCK_RT_INTERACTIVE: FwId = FwId {
bin_name: "mock_rt_interact",
..RUNTIME_TEST_FWID_BASE
};
pub const MOCK_RT_INTERACTIVE_FPGA: FwId = FwId {
bin_name: "mock_rt_interact",
features: &["emu", "riscv", "runtime", "fpga_realtime"],
..RUNTIME_TEST_FWID_BASE
};
}
pub const REGISTERED_FW: &[&FwId] = &[
&ROM,
&ROM_FPGA,
&ROM_WITH_UART,
&ROM_FAKE_WITH_UART,
&ROM_FAKE_WITH_UART_FPGA,
&ROM_WITH_FIPS_TEST_HOOKS,
&ROM_WITH_FIPS_TEST_HOOKS_FPGA,
&ROM_FPGA_WITH_UART,
&FMC_WITH_UART,
&FMC_FAKE_WITH_UART,
&FMC_FPGA_WITH_UART,
&APP,
&APP_WITH_UART,
&APP_WITH_UART_OCP_LOCK,
&APP_WITH_UART_FIPS_TEST_HOOKS,
&APP_WITH_UART_FIPS_TEST_HOOKS_FPGA,
&APP_WITH_UART_OCP_LOCK_FPGA,
&APP_WITH_UART_FPGA,
&APP_ZEROS,
&FMC_ZEROS,
&caliptra_builder_tests::FWID,
&hw_model_tests::MAILBOX_RESPONDER,
&hw_model_tests::MAILBOX_SENDER,
&hw_model_tests::MCU_HITLESS_UPDATE_FLOW,
&hw_model_tests::TEST_ICCM_BYTE_WRITE,
&hw_model_tests::TEST_ICCM_UNALIGNED_WRITE,
&hw_model_tests::TEST_ICCM_WRITE_LOCKED,
&hw_model_tests::TEST_INVALID_INSTRUCTION,
&hw_model_tests::TEST_WRITE_TO_ROM,
&hw_model_tests::TEST_ICCM_DOUBLE_BIT_ECC,
&hw_model_tests::TEST_DCCM_DOUBLE_BIT_ECC,
&hw_model_tests::TEST_UNITIALIZED_READ,
&hw_model_tests::TEST_PCR_EXTEND,
&driver_tests::DOE,
&driver_tests::AES,
&driver_tests::ECC384,
&driver_tests::ECC384_SIGN_VALIDATION_FAILURE,
&driver_tests::ERROR_REPORTER,
&driver_tests::HMAC,
&driver_tests::KEYVAULT,
&driver_tests::KEYVAULT_FPGA,
&driver_tests::MAILBOX_DRIVER_RESPONDER,
&driver_tests::MAILBOX_DRIVER_SENDER,
&driver_tests::MAILBOX_DRIVER_NEGATIVE_TESTS,
&driver_tests::MBOX_SEND_TXN_DROP,
&driver_tests::ML_DSA87,
&driver_tests::ML_DSA87_EXTERNAL_MU,
&driver_tests::ML_KEM,
&driver_tests::PCRBANK,
&driver_tests::PRECONDITIONED_KEYS,
&driver_tests::SHA1,
&driver_tests::SHA256,
&driver_tests::SHA384,
&driver_tests::SHA3,
&driver_tests::SHA512,
&driver_tests::SHA2_512_384ACC,
&driver_tests::STATUS_REPORTER,
&driver_tests::TEST_LMS_24,
&driver_tests::TEST_LMS_32,
&driver_tests::TEST_NEGATIVE_LMS,
&driver_tests::TEST_UART,
&driver_tests::CSRNG,
&driver_tests::CSRNG2,
&driver_tests::CSRNG_PASS_HEALTH_TESTS,
&driver_tests::CSRNG_FAIL_REPCNT_TESTS,
&driver_tests::CSRNG_FAIL_ADAPTP_TESTS,
&driver_tests::TRNG_DRIVER_RESPONDER,
&driver_tests::PERSISTENT,
&driver_tests::DMA_SHA384,
&driver_tests::DMA_SHA384_FPGA,
&driver_tests::OCP_LOCK,
&driver_tests::OCP_LOCK_WARM_RESET,
&driver_tests::DMA_AES,
&driver_tests::AXI_BYPASS,
&rom_tests::ASM_TESTS,
&rom_tests::TEST_FMC_WITH_UART,
&rom_tests::FAKE_TEST_FMC_WITH_UART,
&rom_tests::TEST_FMC_INTERACTIVE,
&rom_tests::FAKE_TEST_FMC_INTERACTIVE,
&rom_tests::TEST_RT_WITH_UART,
&rom_tests::TEST_PMP_TESTS,
&runtime_tests::BOOT,
&runtime_tests::MBOX,
&runtime_tests::MBOX_FPGA,
&runtime_tests::MBOX_WITHOUT_UART,
&runtime_tests::MBOX_WITHOUT_UART_FPGA,
&runtime_tests::PERSISTENT_RT,
&runtime_tests::MOCK_RT_INTERACTIVE,
&runtime_tests::MOCK_RT_INTERACTIVE_FPGA,
];
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/builder/bin/image_gen.rs | builder/bin/image_gen.rs | // Licensed under the Apache-2.0 license
use caliptra_builder::firmware;
use caliptra_builder::version;
use caliptra_builder::ImageOptions;
use caliptra_image_types::FwVerificationPqcKeyType;
use caliptra_image_types::ImageHeader;
use caliptra_image_types::ImageManifest;
use caliptra_image_types::ImageSignatures;
use clap::{arg, value_parser, Command};
use memoffset::{offset_of, span_of};
use serde_json::{json, to_string_pretty};
use sha2::{Digest, Sha384};
use std::collections::HashSet;
use std::path::PathBuf;
use zerocopy::FromBytes;
fn main() {
let mut cmd = Command::new("image-gen")
.about("Caliptra firmware image builder")
.arg(
arg!(--"rom-no-log" [FILE] "ROM binary image (prod)")
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"rom-with-log" [FILE] "ROM binary image (with logging)")
.value_parser(value_parser!(PathBuf)),
)
.arg(arg!(--"fw" [FILE] "FW bundle image").value_parser(value_parser!(PathBuf)))
.arg(
arg!(--"fw-svn" [VALUE] "Security Version Number of firmware image")
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"all_elfs" [DIR] "Build all firmware elf files")
.value_parser(value_parser!(PathBuf)),
)
.arg(arg!(--"fake-rom" [FILE] "Fake ROM").value_parser(value_parser!(PathBuf)))
.arg(arg!(--"fake-fw" [FILE] "Fake FW bundle image").value_parser(value_parser!(PathBuf)))
.arg(
arg!(--"hashes" [FILE] "File path for output JSON file containing image bundle header hashes for external signing tools")
.value_parser(value_parser!(PathBuf))
)
.arg(arg!(--"zeros" "Build an image bundle with zero'd FMC and RT. This will NMI immediately."))
.arg(arg!(--"owner-sig-override" [FILE] "Manually overwrite the owner_sigs of the FW bundle image with the contents of binary [FILE]. The signature should be an ECC signature concatenated with an LMS signature").value_parser(value_parser!(PathBuf)))
.arg(arg!(--"vendor-sig-override" [FILE] "Manually overwrite the vendor_sigs of the FW bundle image with the contents of binary [FILE]. The signature should be an ECC signature concatenated with an LMS signature").value_parser(value_parser!(PathBuf)))
.arg(
arg!(--"pqc-key-type" [integer] "PQC key type to use (MLDSA: 1, LMS: 3)")
.value_parser(value_parser!(i32)),
)
.arg(arg!(--"image-options" [FILE] "Override the `ImageOptions` struct for the image bundle with the given TOML file").value_parser(value_parser!(PathBuf)));
let args = cmd.get_matches_mut();
// Print help if the provided args did not create anything.
let mut valid_cmd = false;
if let Some(path) = args.get_one::<PathBuf>("rom-no-log") {
let rom = caliptra_builder::build_firmware_rom(&firmware::ROM).unwrap();
valid_cmd = true;
std::fs::write(path, rom).unwrap();
}
if let Some(path) = args.get_one::<PathBuf>("rom-with-log") {
let rom = caliptra_builder::build_firmware_rom(&firmware::ROM_WITH_UART).unwrap();
valid_cmd = true;
std::fs::write(path, rom).unwrap();
}
if let Some(path) = args.get_one::<PathBuf>("fake-rom") {
let rom = caliptra_builder::build_firmware_rom(&firmware::ROM_FAKE_WITH_UART).unwrap();
valid_cmd = true;
std::fs::write(path, rom).unwrap();
}
let fw_svn = if let Some(fw_svn) = args.get_one::<u32>("fw-svn") {
*fw_svn
} else {
0
};
let pqc_key_type = match args.get_one("pqc-key-type") {
Some(1) | None => FwVerificationPqcKeyType::MLDSA,
Some(3) => FwVerificationPqcKeyType::LMS,
_ => panic!("--pqc-key-type must be 1 or 3"),
};
if let Some(path) = args.get_one::<PathBuf>("fw") {
// Get image options
let image_options = if let Some(path) = args.get_one::<PathBuf>("image-options") {
toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
} else if args.contains_id("zeros") {
ImageOptions::default()
} else {
ImageOptions {
fmc_version: version::get_fmc_version(),
app_version: version::get_runtime_version(),
fw_svn,
pqc_key_type,
..Default::default()
}
};
// Get image types (zeros or actual firmware)
let (fmc_type, app_type) = if args.contains_id("zeros") {
(firmware::FMC_ZEROS, firmware::APP_ZEROS)
} else {
(firmware::FMC_WITH_UART, firmware::APP_WITH_UART)
};
// Generate Image Bundle
let mut image =
caliptra_builder::build_and_sign_image(&fmc_type, &app_type, image_options).unwrap();
// Override signatures if provided
if let Some(path) = args.get_one::<PathBuf>("owner-sig-override") {
let sig_override = std::fs::read(path).unwrap();
image.manifest.preamble.owner_sigs =
ImageSignatures::read_from_bytes(&sig_override).unwrap();
}
if let Some(path) = args.get_one::<PathBuf>("vendor-sig-override") {
let sig_override = std::fs::read(path).unwrap();
image.manifest.preamble.vendor_sigs =
ImageSignatures::read_from_bytes(&sig_override).unwrap();
}
let contents = image.to_bytes().unwrap();
valid_cmd = true;
std::fs::write(path, contents.clone()).unwrap();
if let Some(path) = args.get_one::<PathBuf>("hashes") {
let header_range = span_of!(ImageManifest, header);
// Get the vendor digest which is taken from a subset of the header
let vendor_header_len = offset_of!(ImageHeader, owner_data);
let vendor_range = header_range.start..header_range.start + vendor_header_len;
let vendor_digest = Sha384::digest(&contents[vendor_range]);
// Get the owner digest which is the full header
let owner_digest = Sha384::digest(&contents[header_range]);
let json = json!({
"vendor": format!("{vendor_digest:02x}"),
"owner": format!("{owner_digest:02x}"),
});
valid_cmd = true;
std::fs::write(path, to_string_pretty(&json).unwrap()).unwrap();
}
}
if let Some(path) = args.get_one::<PathBuf>("fake-fw") {
// Generate Image Bundle
let image = caliptra_builder::build_and_sign_image(
&firmware::FMC_FAKE_WITH_UART,
&firmware::APP_WITH_UART,
ImageOptions {
fmc_version: version::get_fmc_version(),
app_version: version::get_runtime_version(),
pqc_key_type,
..Default::default()
},
)
.unwrap();
valid_cmd = true;
std::fs::write(path, image.to_bytes().unwrap()).unwrap();
}
let mut used_filenames = HashSet::new();
if let Some(all_dir) = args.get_one::<PathBuf>("all_elfs") {
for (fwid, elf_bytes) in
caliptra_builder::build_firmware_elfs_uncached(None, firmware::REGISTERED_FW).unwrap()
{
let elf_filename = fwid.elf_filename();
if !used_filenames.insert(elf_filename.clone()) {
panic!("Multiple fwids with filename {elf_filename}")
}
valid_cmd = true;
std::fs::write(all_dir.join(elf_filename), elf_bytes).unwrap();
}
}
if !valid_cmd {
let _ = cmd.print_long_help();
}
}
#[test]
#[cfg_attr(not(feature = "slow_tests"), ignore)]
fn test_binaries_are_identical() {
for (fwid, elf_bytes1) in
caliptra_builder::build_firmware_elfs_uncached(None, firmware::REGISTERED_FW).unwrap()
{
let elf_bytes2 = caliptra_builder::build_firmware_elf_uncached(None, fwid).unwrap();
assert!(
elf_bytes1 == elf_bytes2,
"binaries are not consistent in {fwid:?}"
);
}
}
#[test]
fn test_image_options_imports_correctly() {
// Use a thread with a larger stack to avoid stack overflow
const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB stack
let thread_result = std::thread::Builder::new()
.stack_size(STACK_SIZE)
.spawn(|| {
// Toml options
let t: ImageOptions = toml::from_str(
&std::fs::read_to_string("test_data/default_image_options.toml").unwrap(),
)
.unwrap();
// Default options
let d = ImageOptions {
fmc_version: version::get_fmc_version(),
app_version: version::get_runtime_version(),
..Default::default()
};
// Check top level fields
assert_eq!(t.fmc_version, d.fmc_version);
assert_eq!(t.fw_svn, d.fw_svn);
assert_eq!(t.app_version, d.app_version);
assert_eq!(t.pqc_key_type, d.pqc_key_type);
// Check vendor config fields. Only the first key is populated in the toml file.
let t_v = &t.vendor_config;
let d_v = &d.vendor_config;
assert_eq!(t_v.ecc_key_idx, d_v.ecc_key_idx);
assert_eq!(t_v.pqc_key_idx, d_v.pqc_key_idx);
assert_eq!(t_v.ecc_key_count, d_v.ecc_key_count);
assert_eq!(t_v.lms_key_count, d_v.lms_key_count);
assert_eq!(t_v.mldsa_key_count, d_v.mldsa_key_count);
assert_eq!(t_v.not_before, d_v.not_before);
assert_eq!(t_v.not_after, d_v.not_after);
assert_eq!(t_v.pl0_pauser, d_v.pl0_pauser);
// Check vendor public keys
assert_eq!(t_v.pub_keys.ecc_pub_keys[0], d_v.pub_keys.ecc_pub_keys[0]);
assert_eq!(t_v.pub_keys.lms_pub_keys[0], d_v.pub_keys.lms_pub_keys[0]);
assert_eq!(
t_v.pub_keys.mldsa_pub_keys[0],
d_v.pub_keys.mldsa_pub_keys[0]
);
// Check vendor private keys
assert_eq!(
t_v.priv_keys.unwrap().ecc_priv_keys[0],
d_v.priv_keys.unwrap().ecc_priv_keys[0]
);
assert_eq!(
t_v.priv_keys.unwrap().lms_priv_keys[0],
d_v.priv_keys.unwrap().lms_priv_keys[0]
);
assert_eq!(
t_v.priv_keys.unwrap().mldsa_priv_keys[0],
d_v.priv_keys.unwrap().mldsa_priv_keys[0]
);
// Check owner config fields
let t_o = &t.owner_config.unwrap();
let d_o = &d.owner_config.unwrap();
assert_eq!(t_o.not_before, d_o.not_before);
assert_eq!(t_o.not_after, d_o.not_after);
// Check owner public keys
assert_eq!(t_o.pub_keys.ecc_pub_key, d_o.pub_keys.ecc_pub_key);
assert_eq!(t_o.pub_keys.lms_pub_key, d_o.pub_keys.lms_pub_key);
assert_eq!(t_o.pub_keys.mldsa_pub_key, d_o.pub_keys.mldsa_pub_key);
// Check owner private keys
assert_eq!(
t_o.priv_keys.unwrap().ecc_priv_key,
d_o.priv_keys.unwrap().ecc_priv_key
);
assert_eq!(
t_o.priv_keys.unwrap().lms_priv_key,
d_o.priv_keys.unwrap().lms_priv_key
);
assert_eq!(
t_o.priv_keys.unwrap().mldsa_priv_key,
d_o.priv_keys.unwrap().mldsa_priv_key
);
})
.unwrap();
// Wait for the thread to complete and propagate any panics
thread_result.join().unwrap();
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/error/src/lib.rs | error/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
error.rs
Abstract:
File contains API and macros used by the library for error handling
--*/
#![cfg_attr(not(feature = "std"), no_std)]
use core::convert::From;
use core::num::{NonZeroU32, TryFromIntError};
/// Caliptra Error Type
/// Derives debug, copy, clone, eq, and partial eq
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct CaliptraError(pub NonZeroU32);
/// Macro to define error constants ensuring uniqueness
///
/// This macro takes a list of (name, value, doc) tuples and generates
/// constant definitions for each error code.
#[macro_export]
macro_rules! define_error_constants {
($(($name:ident, $value:expr, $doc:expr)),* $(,)?) => {
$(
#[doc = $doc]
pub const $name: CaliptraError = CaliptraError::new_const($value);
)*
#[cfg(test)]
/// Returns a vector of all defined error constants for testing uniqueness
pub fn all_constants() -> Vec<(& 'static str, u32)> {
vec![
$(
(stringify!($name), $value),
)*
]
}
};
}
impl CaliptraError {
/// Create a caliptra error; intended to only be used from const contexts, as we don't want
/// runtime panics if val is zero. The preferred way to get a CaliptraError from a u32 is to
/// use `CaliptraError::try_from()` from the `TryFrom` trait impl.
const fn new_const(val: u32) -> Self {
match NonZeroU32::new(val) {
Some(val) => Self(val),
None => panic!("CaliptraError cannot be 0"),
}
}
// Use the macro to define all error constants
define_error_constants![
(
DRIVER_BAD_DATASTORE_VAULT_TYPE,
0x00010001,
"Bad datastore vault type"
),
(
DRIVER_BAD_DATASTORE_REG_TYPE,
0x00010002,
"Bad datastore register type"
),
(CALIPTRA_INTERNAL, 0x00010003, "Internal error"),
(
DRIVER_SHA256_INVALID_STATE,
0x00020001,
"SHA256 invalid state"
),
(
DRIVER_SHA256_MAX_DATA,
0x00020002,
"SHA256 max data exceeded"
),
(
DRIVER_SHA256_INVALID_SLICE,
0x00020003,
"SHA256 invalid slice"
),
(
DRIVER_SHA256_INDEX_OUT_OF_BOUNDS,
0x00020004,
"SHA256 index out of bounds"
),
(
DRIVER_SHA2_512_384_READ_DATA_KV_READ,
0x00030001,
"Driver Error: SHA2_512_384 read data KV read"
),
(
DRIVER_SHA2_512_384_READ_DATA_KV_WRITE,
0x00030002,
"Driver Error: SHA2_512_384 read data KV write"
),
(
DRIVER_SHA2_512_384_READ_DATA_KV_UNKNOWN,
0x00030003,
"Driver Error: SHA2_512_384 read data KV unknown"
),
(
DRIVER_SHA2_512_384_INVALID_STATE_ERR,
0x00030007,
"Driver Error: SHA2_512_384 invalid state"
),
(
DRIVER_SHA2_512_384_MAX_DATA_ERR,
0x00030008,
"Driver Error: SHA2_512_384 max data exceeded"
),
(
DRIVER_SHA2_512_384_INVALID_KEY_SIZE,
0x00030009,
"Driver Error: SHA2_512_384 invalid key size"
),
(
DRIVER_SHA2_512_384_INVALID_SLICE,
0x0003000A,
"Driver Error: SHA2_512_384 invalid slice"
),
(
DRIVER_SHA2_512_384_INDEX_OUT_OF_BOUNDS,
0x0003000B,
"Driver Error: SHA2_512_384 index out of bounds"
),
(
DRIVER_SHA2_512_384_ACC_DIGEST_START_OP_FAILURE,
0x0003000C,
"Driver Error: SHA2_512_384 SHA2_512_384_ACC digest start op failure"
),
(
DRIVER_SHA2_512_384ACC_UNEXPECTED_ACQUIRED_LOCK_STATE,
0x00038000,
"Driver Error: SHA2_512_384ACC unexpected acquired lock state"
),
(
DRIVER_HMAC_READ_KEY_KV_READ,
0x00040001,
"Driver Error: HMAC read key KV read"
),
(
DRIVER_HMAC_READ_KEY_KV_WRITE,
0x00040002,
"Driver Error: HMAC read key KV write"
),
(
DRIVER_HMAC_READ_KEY_KV_UNKNOWN,
0x00040003,
"Driver Error: HMAC read key KV unknown"
),
(
DRIVER_HMAC_READ_DATA_KV_READ,
0x00040004,
"Driver Error: HMAC read data KV read"
),
(
DRIVER_HMAC_READ_DATA_KV_WRITE,
0x00040005,
"Driver Error: HMAC read data KV write"
),
(
DRIVER_HMAC_READ_DATA_KV_UNKNOWN,
0x00040006,
"Driver Error: HMAC read data KV unknown"
),
(
DRIVER_HMAC_WRITE_TAG_KV_READ,
0x00040007,
"Driver Error: HMAC write tag KV read"
),
(
DRIVER_HMAC_WRITE_TAG_KV_WRITE,
0x00040008,
"Driver Error: HMAC write tag KV write"
),
(
DRIVER_HMAC_WRITE_TAG_KV_UNKNOWN,
0x00040009,
"Driver Error: HMAC write tag KV unknown"
),
(
DRIVER_HMAC_INVALID_STATE,
0x0004000b,
"Driver Error: HMAC invalid state"
),
(
DRIVER_HMAC_MAX_DATA,
0x0004000c,
"Driver Error: HMAC max data exceeded"
),
(
DRIVER_HMAC_INVALID_SLICE,
0x0004000d,
"Driver Error: HMAC invalid slice"
),
(
DRIVER_HMAC_INDEX_OUT_OF_BOUNDS,
0x0004000e,
"Driver Error: HMAC index out of bounds"
),
(
DRIVER_HKDF_SALT_TOO_LONG,
0x0004000f,
"Driver Error: HKDF salt is too large"
),
(
DRIVER_AES_READ_KEY_KV_READ,
0x00040010,
"Driver Error: AES read key KV read"
),
(
DRIVER_CMAC_KDF_INVALID_SLICE,
0x00040011,
"Driver Error: CMAC KDF invalid slice"
),
(
DRIVER_CMAC_KDF_INVALID_ROUNDS,
0x00040012,
"Driver Error: CMAC KDF invalid number of rounds"
),
(
DRIVER_ECC384_READ_SEED_KV_READ,
0x00050001,
"Driver Error: ECC384 read seed KV read"
),
(
DRIVER_ECC384_READ_SEED_KV_WRITE,
0x00050002,
"Driver Error: ECC384 read seed KV write"
),
(
DRIVER_ECC384_READ_SEED_KV_UNKNOWN,
0x00050003,
"Driver Error: ECC384 read seed KV unknown"
),
(
DRIVER_ECC384_WRITE_PRIV_KEY_KV_READ,
0x00050004,
"Driver Error: ECC384 write private key KV read"
),
(
DRIVER_ECC384_WRITE_PRIV_KEY_KV_WRITE,
0x00050005,
"Driver Error: ECC384 write private key KV write"
),
(
DRIVER_ECC384_WRITE_PRIV_KEY_KV_UNKNOWN,
0x00050006,
"Driver Error: ECC384 write private key KV unknown"
),
(
DRIVER_ECC384_READ_PRIV_KEY_KV_READ,
0x00050007,
"Driver Error: ECC384 read private key KV read"
),
(
DRIVER_ECC384_READ_PRIV_KEY_KV_WRITE,
0x00050008,
"Driver Error: ECC384 read private key KV write"
),
(
DRIVER_ECC384_READ_PRIV_KEY_KV_UNKNOWN,
0x00050009,
"Driver Error: ECC384 read private key KV unknown"
),
(
DRIVER_ECC384_READ_DATA_KV_READ,
0x0005000a,
"Driver Error: ECC384 read data KV read"
),
(
DRIVER_ECC384_READ_DATA_KV_WRITE,
0x0005000b,
"Driver Error: ECC384 read data KV write"
),
(
DRIVER_ECC384_READ_DATA_KV_UNKNOWN,
0x0005000c,
"Driver Error: ECC384 read data KV unknown"
),
(
DRIVER_ECC384_KEYGEN_PAIRWISE_CONSISTENCY_FAILURE,
0x0005000d,
"Driver Error: ECC384 key generation pairwise consistency failure"
),
(
DRIVER_ECC384_SIGN_VALIDATION_FAILED,
0x0005000e,
"Driver Error: ECC384 sign validation failed"
),
(
DRIVER_ECC384_SCALAR_RANGE_CHECK_FAILED,
0x0005000f,
"Driver Error: ECC384 scalar range check failed"
),
(
DRIVER_ECC384_KEYGEN_BAD_USAGE,
0x00050010,
"Driver Error: ECC384 key generation bad usage"
),
(
DRIVER_ECC384_HW_ERROR,
0x00050011,
"Driver Error: ECC384 hardware error"
),
(
DRIVER_MLDSA87_READ_SEED_KV_READ,
0x00058000,
"Driver Error: MLDSA87 read seed KV read"
),
(
DRIVER_MLDSA87_READ_SEED_KV_WRITE,
0x00058001,
"Driver Error: MLDSA87 read seed KV write"
),
(
DRIVER_MLDSA87_READ_SEED_KV_UNKNOWN,
0x00058002,
"Driver Error: MLDSA87 read seed KV unknown"
),
(
DRIVER_MLDSA87_HW_ERROR,
0x00058003,
"Driver Error: MLDSA87 hardware error"
),
(
DRIVER_MLDSA87_SIGN_VALIDATION_FAILED,
0x00058004,
"Driver Error: MLDSA87 sign validation failed"
),
(
DRIVER_MLDSA87_KEY_GEN_SEED_BAD_USAGE,
0x00058005,
"Driver Error: MLDSA87 key generation seed bad usage"
),
(
DRIVER_MLDSA87_UNSUPPORTED_SIGNATURE,
0x00058006,
"Driver Error: MLDSA87 signature is not supported"
),
(
DRIVER_MLKEM_READ_SEED_KV_READ,
0x00059000,
"Driver Error: ML-KEM read seed KV read"
),
(
DRIVER_MLKEM_READ_SEED_KV_WRITE,
0x00059001,
"Driver Error: ML-KEM read seed KV write"
),
(
DRIVER_MLKEM_READ_SEED_KV_UNKNOWN,
0x00059002,
"Driver Error: ML-KEM read seed KV unknown"
),
(
DRIVER_MLKEM_HW_ERROR,
0x00059003,
"Driver Error: ML-KEM hardware error"
),
(
DRIVER_MLKEM_READ_MSG_KV_READ,
0x00059004,
"Driver Error: ML-KEM read message KV read"
),
(
DRIVER_MLKEM_READ_MSG_KV_WRITE,
0x00059005,
"Driver Error: ML-KEM read message KV write"
),
(
DRIVER_MLKEM_READ_MSG_KV_UNKNOWN,
0x00059006,
"Driver Error: ML-KEM read message KV unknown"
),
(
DRIVER_KV_ERASE_USE_LOCK_SET_FAILURE,
0x00060001,
"Driver Error: KV erase use lock set failure"
),
(
DRIVER_KV_ERASE_WRITE_LOCK_SET_FAILURE,
0x00060002,
"Driver Error: KV erase write lock set failure"
),
(
DRIVER_PCR_BANK_ERASE_WRITE_LOCK_SET_FAILURE,
0x00070001,
"Driver Error: PCR bank erase write lock set failure"
),
(
DRIVER_RECOVERY_INVALID_CMS_TYPE,
0x00052000,
"Recovery register interface driver: Invalid CMS type"
),
(
DRIVER_RECOVERY_INVALID_CMS,
0x00052001,
"Recovery register interface driver: Invalid CMS"
),
(
DRIVER_MAILBOX_INVALID_STATE,
0x00080001,
"Mailbox Error: Invalid state"
),
(
DRIVER_MAILBOX_INVALID_DATA_LEN,
0x00080002,
"Mailbox Error: Invalid data length"
),
(
DRIVER_MAILBOX_ENQUEUE_ERR,
0x00080004,
"Mailbox Error: Enqueue error"
),
(
DRIVER_MAILBOX_UNCORRECTABLE_ECC,
0x00080005,
"Mailbox Error: Uncorrectable ECC"
),
(
DRIVER_SHA2_512_384ACC_INDEX_OUT_OF_BOUNDS,
0x00090003,
"SHA2_512_384ACC Error: Index out of bounds"
),
(
DRIVER_SHA1_INVALID_STATE,
0x000a0001,
"SHA1 Error: Invalid state"
),
(
DRIVER_SHA1_MAX_DATA,
0x000a0002,
"SHA1 Error: Max data exceeded"
),
(
DRIVER_SHA1_INVALID_SLICE,
0x000a0003,
"SHA1 Error: Invalid slice"
),
(
DRIVER_SHA1_INDEX_OUT_OF_BOUNDS,
0x000a0004,
"SHA1 Error: Index out of bounds"
),
(
DRIVER_OCP_LOCK_COLD_RESET_INVALID_HEK_SEED,
0x000b0000,
"OCP LOCK: Invalid HEK Seed state"
),
(
IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH,
0x000b0001,
"Image Verifier Error: Manifest marker mismatch"
),
(
IMAGE_VERIFIER_ERR_MANIFEST_SIZE_MISMATCH,
0x000b0002,
"Image Verifier Error: Manifest size mismatch"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_INVALID,
0x000b0003,
"Image Verifier Error: Vendor public key digest invalid"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_FAILURE,
0x000b0004,
"Image Verifier Error: Vendor public key digest failure"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_MISMATCH,
0x000b0005,
"Image Verifier Error: Vendor public key digest mismatch"
),
(
IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_FAILURE,
0x000b0006,
"Image Verifier Error: Owner public key digest failure"
),
(
IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_MISMATCH,
0x000b0007,
"Image Verifier Error: Owner public key digest mismatch"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
0x000b0008,
"Image Verifier Error: Vendor ECC public key index out of bounds"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_REVOKED,
0x000b0009,
"Image Verifier Error: Vendor ECC public key revoked"
),
(
IMAGE_VERIFIER_ERR_HEADER_DIGEST_FAILURE,
0x000b000a,
"Image Verifier Error: Header digest failure"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_VERIFY_FAILURE,
0x000b000b,
"Image Verifier Error: Vendor ECC verify failure"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID,
0x000b000c,
"Image Verifier Error: Vendor ECC signature invalid"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_MISMATCH,
0x000b000d,
"Image Verifier Error: Vendor ECC public key index mismatch"
),
(
IMAGE_VERIFIER_ERR_OWNER_ECC_VERIFY_FAILURE,
0x000b000e,
"Image Verifier Error: Owner ECC verify failure"
),
(
IMAGE_VERIFIER_ERR_OWNER_ECC_SIGNATURE_INVALID,
0x000b000f,
"Image Verifier Error: Owner ECC signature invalid"
),
(
IMAGE_VERIFIER_ERR_TOC_ENTRY_COUNT_INVALID,
0x000b0010,
"Image Verifier Error: TOC entry count invalid"
),
(
IMAGE_VERIFIER_ERR_TOC_DIGEST_FAILURE,
0x000b0011,
"Image Verifier Error: TOC digest failure"
),
(
IMAGE_VERIFIER_ERR_TOC_DIGEST_MISMATCH,
0x000b0012,
"Image Verifier Error: TOC digest mismatch"
),
(
IMAGE_VERIFIER_ERR_FMC_DIGEST_FAILURE,
0x000b0013,
"Image Verifier Error: FMC digest failure"
),
(
IMAGE_VERIFIER_ERR_FMC_DIGEST_MISMATCH,
0x000b0014,
"Image Verifier Error: FMC digest mismatch"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_DIGEST_FAILURE,
0x000b0015,
"Image Verifier Error: Runtime digest failure"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_DIGEST_MISMATCH,
0x000b0016,
"Image Verifier Error: Runtime digest mismatch"
),
(
IMAGE_VERIFIER_ERR_FMC_RUNTIME_OVERLAP,
0x000b0017,
"Image Verifier Error: FMC runtime overlap"
),
(
IMAGE_VERIFIER_ERR_FMC_RUNTIME_INCORRECT_ORDER,
0x000b0018,
"Image Verifier Error: FMC runtime incorrect order"
),
(
IMAGE_VERIFIER_ERR_OWNER_ECC_PUB_KEY_INVALID_ARG,
0x000b0019,
"Image Verifier Error: Owner ECC public key invalid arg"
),
(
IMAGE_VERIFIER_ERR_OWNER_ECC_SIGNATURE_INVALID_ARG,
0x000b001a,
"Image Verifier Error: Owner ECC signature invalid arg"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INVALID_ARG,
0x000b001b,
"Image Verifier Error: Vendor ECC public key invalid arg"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID_ARG,
0x000b001c,
"Image Verifier Error: Vendor ECC signature invalid arg"
),
(
IMAGE_VERIFIER_ERR_UPDATE_RESET_OWNER_DIGEST_FAILURE,
0x000b001d,
"Image Verifier Error: Update reset owner digest failure"
),
(
IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_ECC_PUB_KEY_IDX_MISMATCH,
0x000b001e,
"Image Verifier Error: Update reset vendor ECC public key index mismatch"
),
(
IMAGE_VERIFIER_ERR_UPDATE_RESET_FMC_DIGEST_MISMATCH,
0x000b001f,
"Image Verifier Error: Update reset FMC digest mismatch"
),
(
IMAGE_VERIFIER_ERR_FMC_LOAD_ADDR_INVALID,
0x000b0021,
"Image Verifier Error: FMC load address invalid"
),
(
IMAGE_VERIFIER_ERR_FMC_LOAD_ADDR_UNALIGNED,
0x000b0022,
"Image Verifier Error: FMC load address unaligned"
),
(
IMAGE_VERIFIER_ERR_FMC_ENTRY_POINT_INVALID,
0x000b0023,
"Image Verifier Error: FMC entry point invalid"
),
(
IMAGE_VERIFIER_ERR_FMC_ENTRY_POINT_UNALIGNED,
0x000b0024,
"Image Verifier Error: FMC entry point unaligned"
),
// 0x000b0025 (deprecated) was IMAGE_VERIFIER_ERR_FMC_SVN_GREATER_THAN_MAX_SUPPORTED
// 0x000b0026 (deprecated) was IMAGE_VERIFIER_ERR_FMC_SVN_LESS_THAN_MIN_SUPPORTED
// 0x000b0027 (deprecated) was IMAGE_VERIFIER_ERR_FMC_SVN_LESS_THAN_FUSE
(
IMAGE_VERIFIER_ERR_RUNTIME_LOAD_ADDR_INVALID,
0x000b0028,
"Image Verifier Error: Runtime load address invalid"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_LOAD_ADDR_UNALIGNED,
0x000b0029,
"Image Verifier Error: Runtime load address unaligned"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_ENTRY_POINT_INVALID,
0x000b002a,
"Image Verifier Error: Runtime entry point invalid"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_ENTRY_POINT_UNALIGNED,
0x000b002b,
"Image Verifier Error: Runtime entry point unaligned"
),
(
IMAGE_VERIFIER_ERR_FIRMWARE_SVN_GREATER_THAN_MAX_SUPPORTED,
0x000b002c,
"Image Verifier Error: Firmware SVN greater than max supported"
),
// 0x000b002d (deprecated) was IMAGE_VERIFIER_ERR_FIRMWARE_SVN_LESS_THAN_MIN_SUPPORTED
(
IMAGE_VERIFIER_ERR_FIRMWARE_SVN_LESS_THAN_FUSE,
0x000b002e,
"Image Verifier Error: Firmware SVN less than fuse"
),
(
IMAGE_VERIFIER_ERR_IMAGE_LEN_MORE_THAN_BUNDLE_SIZE,
0x000b002f,
"Image Verifier Error: Image length more than bundle size"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_MISMATCH,
0x000b0030,
"Image Verifier Error: Vendor PQC public key index mismatch"
),
(
IMAGE_VERIFIER_ERR_VENDOR_LMS_VERIFY_FAILURE,
0x000b0031,
"Image Verifier Error: Vendor LMS verify failure"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_OUT_OF_BOUNDS,
0x000b0032,
"Image Verifier Error: Vendor PQC public key index out of bounds"
),
(
IMAGE_VERIFIER_ERR_VENDOR_LMS_SIGNATURE_INVALID,
0x000b0033,
"Image Verifier Error: Vendor LMS signature invalid"
),
(
IMAGE_VERIFIER_ERR_FMC_RUNTIME_LOAD_ADDR_OVERLAP,
0x000b0034,
"Image Verifier Error: FMC runtime load address overlap"
),
(
IMAGE_VERIFIER_ERR_OWNER_LMS_VERIFY_FAILURE,
0x000b0036,
"Image Verifier Error: Owner LMS verify failure"
),
(
IMAGE_VERIFIER_ERR_OWNER_LMS_SIGNATURE_INVALID,
0x000b0038,
"Image Verifier Error: Owner LMS signature invalid"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_REVOKED,
0x000b003a,
"Image Verifier Error: Vendor PQC public key revoked"
),
(
IMAGE_VERIFIER_ERR_FMC_SIZE_ZERO,
0x000b003b,
"Image Verifier Error: FMC size zero"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_SIZE_ZERO,
0x000b003c,
"Image Verifier Error: Runtime size zero"
),
(
IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_PQC_PUB_KEY_IDX_MISMATCH,
0x000b003d,
"Image Verifier Error: Update reset vendor PQC public key index mismatch"
),
(
IMAGE_VERIFIER_ERR_FMC_LOAD_ADDRESS_IMAGE_SIZE_ARITHMETIC_OVERFLOW,
0x000b003e,
"Image Verifier Error: FMC load address image size arithmetic overflow"
),
(
IMAGE_VERIFIER_ERR_RUNTIME_LOAD_ADDRESS_IMAGE_SIZE_ARITHMETIC_OVERFLOW,
0x000b003f,
"Image Verifier Error: Runtime load address image size arithmetic overflow"
),
(
IMAGE_VERIFIER_ERR_TOC_ENTRY_RANGE_ARITHMETIC_OVERFLOW,
0x000b0040,
"Image Verifier Error: TOC entry range arithmetic overflow"
),
(
IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS,
0x000b0041,
"Image Verifier Error: Digest out of bounds"
),
(
IMAGE_VERIFIER_ERR_ECC_KEY_DESCRIPTOR_VERSION_MISMATCH,
0x000b0042,
"Image Verifier Error: ECC key descriptor version mismatch"
),
(
IMAGE_VERIFIER_ERR_ECC_KEY_DESCRIPTOR_HASH_COUNT_GT_MAX,
0x000b0043,
"Image Verifier Error: ECC key descriptor hash count greater than max"
),
(
IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_VERSION_MISMATCH,
0x000b0044,
"Image Verifier Error: PQC key descriptor version mismatch"
),
(
IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_TYPE_MISMATCH,
0x000b0045,
"Image Verifier Error: PQC key descriptor type mismatch"
),
(
IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_HASH_COUNT_GT_MAX,
0x000b0046,
"Image Verifier Error: PQC key descriptor hash count greater than max"
),
(
IMAGE_VERIFIER_ERR_ECC_KEY_DESCRIPTOR_INVALID_HASH_COUNT,
0x000b0047,
"Image Verifier Error: ECC key descriptor invalid hash count"
),
(
IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_INVALID_HASH_COUNT,
0x000b0048,
"Image Verifier Error: PQC key descriptor invalid hash count"
),
(
IMAGE_VERIFIER_ERR_PQC_KEY_TYPE_INVALID,
0x000b0049,
"Image Verifier Error: PQC key type invalid"
),
(
IMAGE_VERIFIER_ERR_LMS_VENDOR_PUB_KEY_INVALID,
0x000b004a,
"Image Verifier Error: LMS vendor public key invalid"
),
(
IMAGE_VERIFIER_ERR_LMS_VENDOR_SIG_INVALID,
0x000b004b,
"Image Verifier Error: LMS vendor signature invalid"
),
(
IMAGE_VERIFIER_ERR_LMS_OWNER_PUB_KEY_INVALID,
0x000b004c,
"Image Verifier Error: LMS owner public key invalid"
),
(
IMAGE_VERIFIER_ERR_LMS_OWNER_SIG_INVALID,
0x000b004d,
"Image Verifier Error: LMS owner signature invalid"
),
(
IMAGE_VERIFIER_ERR_MLDSA_VENDOR_PUB_KEY_READ_FAILED,
0x000b004e,
"Image Verifier Error: MLDSA vendor public key read failed"
),
(
IMAGE_VERIFIER_ERR_MLDSA_VENDOR_SIG_READ_FAILED,
0x000b004f,
"Image Verifier Error: MLDSA vendor signature read failed"
),
(
IMAGE_VERIFIER_ERR_MLDSA_OWNER_PUB_KEY_READ_FAILED,
0x000b0050,
"Image Verifier Error: MLDSA owner public key read failed"
),
(
IMAGE_VERIFIER_ERR_MLDSA_OWNER_SIG_READ_FAILED,
0x000b0051,
"Image Verifier Error: MLDSA owner signature read failed"
),
(
IMAGE_VERIFIER_ERR_VENDOR_MLDSA_MSG_MISSING,
0x000b0052,
"Image Verifier Error: Vendor MLDSA message missing"
),
(
IMAGE_VERIFIER_ERR_OWNER_MLDSA_MSG_MISSING,
0x000b0053,
"Image Verifier Error: Owner MLDSA message missing"
),
(
IMAGE_VERIFIER_ERR_VENDOR_MLDSA_VERIFY_FAILURE,
0x000b0054,
"Image Verifier Error: Vendor MLDSA verify failure"
),
(
IMAGE_VERIFIER_ERR_VENDOR_MLDSA_SIGNATURE_INVALID,
0x000b0055,
"Image Verifier Error: Vendor MLDSA signature invalid"
),
(
IMAGE_VERIFIER_ERR_OWNER_MLDSA_VERIFY_FAILURE,
0x000b0056,
"Image Verifier Error: Owner MLDSA verify failure"
),
(
IMAGE_VERIFIER_ERR_OWNER_MLDSA_SIGNATURE_INVALID,
0x000b0057,
"Image Verifier Error: Owner MLDSA signature invalid"
),
(
IMAGE_VERIFIER_ERR_MLDSA_TYPE_CONVERSION_FAILED,
0x000b0058,
"Image Verifier Error: MLDSA type conversion failed"
),
(
IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_DIGEST_MISMATCH,
0x000b0059,
"Image Verifier Error: Vendor ECC public key digest mismatch"
),
(
IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_DIGEST_MISMATCH,
0x000b005a,
"Image Verifier Error: Vendor PQC public key digest mismatch"
),
(
IMAGE_VERIFIER_ERR_INVALID_PQC_KEY_TYPE_IN_FUSE,
0x000b005b,
"Image Verifier Error: Invalid PQC key type in fuse"
),
(
IMAGE_VERIFIER_ERR_PQC_KEY_TYPE_MISMATCH,
0x000b005c,
"Image Verifier Error: PQC key type mismatch"
),
(
IMAGE_VERIFIER_ACTIVATION_FAILED,
0x000b005d,
"Image Verifier Error: Activation failed"
),
(
IMAGE_VERIFIER_ERR_DOT_OWNER_PUB_KEY_DIGEST_MISMATCH,
0x000b005e,
"Image Verifier Error: DOT owner public key digest mismatch"
),
(
DRIVER_LMS_INVALID_LMS_ALGO_TYPE,
0x000c0001,
"Driver Error: LMS invalid LMS algorithm type"
),
(
DRIVER_LMS_INVALID_LMOTS_ALGO_TYPE,
0x000c0002,
"Driver Error: LMS invalid LMOTS algorithm type"
),
(
DRIVER_LMS_INVALID_WINTERNITS_PARAM,
0x000c0003,
"Driver Error: LMS invalid Winternitz parameter"
),
(
DRIVER_LMS_INVALID_PVALUE,
0x000c0004,
"Driver Error: LMS invalid p-value"
),
(
DRIVER_LMS_INVALID_HASH_WIDTH,
0x000c0005,
"Driver Error: LMS invalid hash width"
),
(
DRIVER_LMS_INVALID_TREE_HEIGHT,
0x000c0006,
"Driver Error: LMS invalid tree height"
),
(
DRIVER_LMS_INVALID_Q_VALUE,
0x000c0007,
"Driver Error: LMS invalid q-value"
),
(
DRIVER_LMS_INVALID_INDEX,
0x000c0008,
"Driver Error: LMS invalid index"
),
(
DRIVER_LMS_PATH_OUT_OF_BOUNDS,
0x000c0009,
"Driver Error: LMS path out of bounds"
),
(
DRIVER_LMS_INVALID_SIGNATURE_LENGTH,
0x000c000a,
"Driver Error: LMS invalid signature length"
),
(
DRIVER_LMS_INVALID_PUBLIC_KEY_LENGTH,
0x000c000b,
"Driver Error: LMS invalid public key length"
),
(
DRIVER_LMS_INVALID_SIGNATURE_DEPTH,
0x000c000c,
"Driver Error: LMS invalid signature depth"
),
(
DRIVER_LMS_SIGNATURE_LMOTS_DOESNT_MATCH_PUBKEY_LMOTS,
0x000c000d,
"Driver Error: LMS signature LMOTS doesn't match pubkey LMOTS"
),
(
DRIVER_CSRNG_INSTANTIATE,
0x000d0001,
"CSRNG Error: Instantiate"
),
(
DRIVER_CSRNG_UNINSTANTIATE,
0x000d0002,
"CSRNG Error: Uninstantiate"
),
(DRIVER_CSRNG_RESEED, 0x000d0003, "CSRNG Error: Reseed"),
(DRIVER_CSRNG_GENERATE, 0x000d0004, "CSRNG Error: Generate"),
(DRIVER_CSRNG_UPDATE, 0x000d0005, "CSRNG Error: Update"),
(
DRIVER_CSRNG_OTHER_HEALTH_CHECK_FAILED,
0x000d0006,
"CSRNG Error: Other health check failed"
),
(
DRIVER_CSRNG_REPCNT_HEALTH_CHECK_FAILED,
0x000d0007,
"CSRNG Error: RepCnt health check failed"
),
(
DRIVER_CSRNG_ADAPTP_HEALTH_CHECK_FAILED,
0x000d0008,
"CSRNG Error: AdaptP health check failed"
),
(
DRIVER_HANDOFF_INVALID_VAULT,
0x000D100,
"Driver Handoff Error: Invalid vault"
),
(
DRIVER_HANDOFF_INVALID_KEY_ID,
0x000D101,
"Driver Handoff Error: Invalid key ID"
),
(
DRIVER_HANDOFF_INVALID_COLD_RESET_ENTRY4,
0x000D102,
"Driver Handoff Error: Invalid cold reset entry4"
),
(
DRIVER_HANDOFF_INVALID_COLD_RESET_ENTRY48,
0x000D103,
"Driver Handoff Error: Invalid cold reset entry48"
),
(
DRIVER_HANDOFF_INVALID_WARM_RESET_ENTRY4,
0x000D104,
"Driver Handoff Error: Invalid warm reset entry4"
),
(
DRIVER_HANDOFF_INVALID_WARM_RESET_ENTRY48,
0x000D105,
"Driver Handoff Error: Invalid warm reset entry48"
),
(
DRIVER_DMA_TRANSACTION_ALREADY_BUSY,
0x0000f000,
"DMA driver Error: Transaction already busy"
),
(
DRIVER_DMA_TRANSACTION_ERROR,
0x0000f001,
"DMA driver Error: Transaction error"
),
(
DRIVER_DMA_FIFO_UNDERRUN,
0x0000f002,
"DMA driver Error: FIFO underrun"
),
(
DRIVER_DMA_FIFO_OVERRUN,
0x0000f003,
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/hmac.rs | hw/latest/registers/src/hmac.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct HmacReg {
_priv: (),
}
impl HmacReg {
pub const PTR: *mut u32 = 0x10010000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing of the name
/// of HMAC component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hmac512_name(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::hmac::meta::Hmac512Name, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of HMAC512 component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hmac512_version(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::hmac::meta::Hmac512Version, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HMAC512 component control register type definition.
///
/// Read value: [`hmac::regs::Hmac512CtrlReadVal`]; Write value: [`hmac::regs::Hmac512CtrlWriteVal`]
#[inline(always)]
pub fn hmac512_ctrl(&self) -> ureg::RegRef<crate::hmac::meta::Hmac512Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HMAC512 component status register type definition
///
/// Read value: [`hmac::regs::Hmac512StatusReadVal`]; Write value: [`hmac::regs::Hmac512StatusWriteVal`]
#[inline(always)]
pub fn hmac512_status(&self) -> ureg::RegRef<crate::hmac::meta::Hmac512Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HMAC512 component key register type definition
/// 16 32-bit registers storing the 512-bit key in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hmac512_key(
&self,
) -> ureg::Array<16, ureg::RegRef<crate::hmac::meta::Hmac512Key, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HMAC512 component block register type definition
/// 32 32-bit registers storing the 1024-bit padded input in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hmac512_block(
&self,
) -> ureg::Array<32, ureg::RegRef<crate::hmac::meta::Hmac512Block, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HMAC512 component tag register type definition
/// 16 32-bit registers storing the 512-bit digest output in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hmac512_tag(
&self,
) -> ureg::Array<16, ureg::RegRef<crate::hmac::meta::Hmac512Tag, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HMAC512 component lfsr seed register type definition
/// 12 32-bit registers storing the 384-bit lfsr seed input.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hmac512_lfsr_seed(
&self,
) -> ureg::Array<12, ureg::RegRef<crate::hmac::meta::Hmac512LfsrSeed, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x140 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn hmac512_kv_rd_key_ctrl(
&self,
) -> ureg::RegRef<crate::hmac::meta::Hmac512KvRdKeyCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x600 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn hmac512_kv_rd_key_status(
&self,
) -> ureg::RegRef<crate::hmac::meta::Hmac512KvRdKeyStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x604 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn hmac512_kv_rd_block_ctrl(
&self,
) -> ureg::RegRef<crate::hmac::meta::Hmac512KvRdBlockCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x608 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn hmac512_kv_rd_block_status(
&self,
) -> ureg::RegRef<crate::hmac::meta::Hmac512KvRdBlockStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault write access for this engine
///
/// Read value: [`regs::KvWriteCtrlRegReadVal`]; Write value: [`regs::KvWriteCtrlRegWriteVal`]
#[inline(always)]
pub fn hmac512_kv_wr_ctrl(&self) -> ureg::RegRef<crate::hmac::meta::Hmac512KvWrCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x610 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn hmac512_kv_wr_status(
&self,
) -> ureg::RegRef<crate::hmac::meta::Hmac512KvWrStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x614 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`hmac::regs::ErrorIntrEnTReadVal`]; Write value: [`hmac::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::NotifIntrEnTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`hmac::regs::ErrorIntrTReadVal`]; Write value: [`hmac::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::NotifIntrTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`hmac::regs::ErrorIntrTrigTReadVal`]; Write value: [`hmac::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::NotifIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn key_mode_error_intr_count_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfKeyModeErrorIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn key_zero_error_intr_count_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfKeyZeroErrorIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn key_mode_error_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfKeyModeErrorIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn key_zero_error_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfKeyZeroErrorIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::hmac::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct Hmac512CtrlWriteVal(u32);
impl Hmac512CtrlWriteVal {
/// Control init command bit: Trigs the HMAC512 core to start the
/// processing for the key and the first padded
/// message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn init(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Control next command bit: Trigs the HMAC512 core to start the
/// processing for the remining padded message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn next(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Zeroize all internal registers: Zeroize all internal registers after HMAC process, to avoid SCA leakage.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn zeroize(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Control mode command bits: Indicates the HMAC512 core to set dynamically
/// the type of hashing algorithm. This can be:
/// 0 for HMAC384
/// 1 for HMAC512
#[inline(always)]
pub fn mode(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// CSR Mode: Indicates to the HMAC512 core to use the CSR HMAC key
#[inline(always)]
pub fn csr_mode(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Reserved
#[inline(always)]
pub fn reserved(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
}
impl From<u32> for Hmac512CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<Hmac512CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: Hmac512CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct Hmac512StatusReadVal(u32);
impl Hmac512StatusReadVal {
/// Status ready bit: Indicates if the core is ready to take
/// a control command and process the block.
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Status valid bit: Indicates if the process is done and the
/// results stored in TAG registers are valid.
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for Hmac512StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<Hmac512StatusReadVal> for u32 {
#[inline(always)]
fn from(val: Hmac512StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn key_mode_error_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable bit for Event 1
#[inline(always)]
pub fn key_zero_error_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrEnTWriteVal {
ErrorIntrEnTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTWriteVal(u32);
impl ErrorIntrEnTWriteVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn key_mode_error_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Enable bit for Event 1
#[inline(always)]
pub fn key_zero_error_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrEnTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTReadVal(u32);
impl ErrorIntrTReadVal {
/// Interrupt Event 0 status bit when 384-bit key is selected in HMAC512 mode
#[inline(always)]
pub fn key_mode_error_sts(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Event 1 status bit when all-zero key is derived from KeyVault
#[inline(always)]
pub fn key_zero_error_sts(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(&self) -> bool {
((self.0 >> 3) & 1) != 0
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mbox_sram.rs | hw/latest/registers/src/mbox_sram.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct MboxSram {
_priv: (),
}
impl MboxSram {
pub const PTR: *mut u32 = 0x30040000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
}
pub mod regs {
//! Types that represent the values held by registers.
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/i3ccsr.rs | hw/latest/registers/src/i3ccsr.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct I3ccsr {
_priv: (),
}
impl I3ccsr {
pub const PTR: *mut u32 = 0x10040000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dat(&self) -> ureg::Array<256, ureg::RegRef<crate::i3ccsr::meta::Dat, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x400 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dct(&self) -> ureg::Array<512, ureg::RegRef<crate::i3ccsr::meta::Dct, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x800 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn i3c_base(&self) -> I3cbaseBlock<&TMmio> {
I3cbaseBlock {
ptr: unsafe { self.ptr.add(0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn piocontrol(&self) -> PiocontrolBlock<&TMmio> {
PiocontrolBlock {
ptr: unsafe { self.ptr.add(0x80 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn i3c_ec(&self) -> I3cEcBlock<&TMmio> {
I3cEcBlock {
ptr: unsafe { self.ptr.add(0x100 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn sec_fw_recovery_if(&self) -> SecfwrecoveryifBlock<&TMmio> {
SecfwrecoveryifBlock {
ptr: unsafe { self.ptr.add(0x100 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn stdby_ctrl_mode(&self) -> StdbyctrlmodeBlock<&TMmio> {
StdbyctrlmodeBlock {
ptr: unsafe { self.ptr.add(0x180 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn tti(&self) -> TtiBlock<&TMmio> {
TtiBlock {
ptr: unsafe { self.ptr.add(0x1c0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn so_cmgmt_if(&self) -> SocmgmtifBlock<&TMmio> {
SocmgmtifBlock {
ptr: unsafe { self.ptr.add(0x200 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn ctrl_cfg(&self) -> CtrlcfgBlock<&TMmio> {
CtrlcfgBlock {
ptr: unsafe { self.ptr.add(0x260 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct I3cbaseBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> I3cbaseBlock<TMmio> {
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hci_version(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseHciVersion, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::HcControlReadVal`]; Write value: [`i3ccsr::regs::HcControlWriteVal`]
#[inline(always)]
pub fn hc_control(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseHcControl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::ControllerDeviceAddrReadVal`]; Write value: [`i3ccsr::regs::ControllerDeviceAddrWriteVal`]
#[inline(always)]
pub fn controller_device_addr(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseControllerDeviceAddr, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::HcCapabilitiesReadVal`]; Write value: [`i3ccsr::regs::HcCapabilitiesWriteVal`]
#[inline(always)]
pub fn hc_capabilities(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseHcCapabilities, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::ResetControlReadVal`]; Write value: [`i3ccsr::regs::ResetControlWriteVal`]
#[inline(always)]
pub fn reset_control(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseResetControl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PresentStateReadVal`]; Write value: [`i3ccsr::regs::PresentStateWriteVal`]
#[inline(always)]
pub fn present_state(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbasePresentState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IntrStatusReadVal`]; Write value: [`i3ccsr::regs::IntrStatusWriteVal`]
#[inline(always)]
pub fn intr_status(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIntrStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IntrStatusEnableReadVal`]; Write value: [`i3ccsr::regs::IntrStatusEnableWriteVal`]
#[inline(always)]
pub fn intr_status_enable(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIntrStatusEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IntrSignalEnableReadVal`]; Write value: [`i3ccsr::regs::IntrSignalEnableWriteVal`]
#[inline(always)]
pub fn intr_signal_enable(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIntrSignalEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IntrForceReadVal`]; Write value: [`i3ccsr::regs::IntrForceWriteVal`]
#[inline(always)]
pub fn intr_force(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIntrForce, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DatSectionOffsetReadVal`]; Write value: [`i3ccsr::regs::DatSectionOffsetWriteVal`]
#[inline(always)]
pub fn dat_section_offset(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseDatSectionOffset, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DctSectionOffsetReadVal`]; Write value: [`i3ccsr::regs::DctSectionOffsetWriteVal`]
#[inline(always)]
pub fn dct_section_offset(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseDctSectionOffset, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::RingHeadersSectionOffsetReadVal`]; Write value: [`i3ccsr::regs::RingHeadersSectionOffsetWriteVal`]
#[inline(always)]
pub fn ring_headers_section_offset(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseRingHeadersSectionOffset, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PioSectionOffsetReadVal`]; Write value: [`i3ccsr::regs::PioSectionOffsetWriteVal`]
#[inline(always)]
pub fn pio_section_offset(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbasePioSectionOffset, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::ExtCapsSectionOffsetReadVal`]; Write value: [`i3ccsr::regs::ExtCapsSectionOffsetWriteVal`]
#[inline(always)]
pub fn ext_caps_section_offset(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseExtCapsSectionOffset, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IntCtrlCmdsEnReadVal`]; Write value: [`i3ccsr::regs::IntCtrlCmdsEnWriteVal`]
#[inline(always)]
pub fn int_ctrl_cmds_en(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIntCtrlCmdsEn, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x4c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IbiNotifyCtrlReadVal`]; Write value: [`i3ccsr::regs::IbiNotifyCtrlWriteVal`]
#[inline(always)]
pub fn ibi_notify_ctrl(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIbiNotifyCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x58 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IbiDataAbortCtrlReadVal`]; Write value: [`i3ccsr::regs::IbiDataAbortCtrlWriteVal`]
#[inline(always)]
pub fn ibi_data_abort_ctrl(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseIbiDataAbortCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DevCtxBaseLoReadVal`]; Write value: [`i3ccsr::regs::DevCtxBaseLoWriteVal`]
#[inline(always)]
pub fn dev_ctx_base_lo(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseDevCtxBaseLo, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DevCtxBaseHiReadVal`]; Write value: [`i3ccsr::regs::DevCtxBaseHiWriteVal`]
#[inline(always)]
pub fn dev_ctx_base_hi(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseDevCtxBaseHi, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x64 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DevCtxSgReadVal`]; Write value: [`i3ccsr::regs::DevCtxSgWriteVal`]
#[inline(always)]
pub fn dev_ctx_sg(&self) -> ureg::RegRef<crate::i3ccsr::meta::I3cbaseDevCtxSg, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x68 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
#[derive(Clone, Copy)]
pub struct PiocontrolBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> PiocontrolBlock<TMmio> {
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn command_port(&self) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolCommandPort, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn response_port(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolResponsePort, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn tx_data_port(&self) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolTxDataPort, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn rx_data_port(&self) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolRxDataPort, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn ibi_port(&self) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolIbiPort, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::QueueThldCtrlReadVal`]; Write value: [`i3ccsr::regs::QueueThldCtrlWriteVal`]
#[inline(always)]
pub fn queue_thld_ctrl(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolQueueThldCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DataBufferThldCtrlReadVal`]; Write value: [`i3ccsr::regs::DataBufferThldCtrlWriteVal`]
#[inline(always)]
pub fn data_buffer_thld_ctrl(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolDataBufferThldCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::QueueSizeReadVal`]; Write value: [`i3ccsr::regs::QueueSizeWriteVal`]
#[inline(always)]
pub fn queue_size(&self) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolQueueSize, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::AltQueueSizeReadVal`]; Write value: [`i3ccsr::regs::AltQueueSizeWriteVal`]
#[inline(always)]
pub fn alt_queue_size(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolAltQueueSize, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PioIntrStatusReadVal`]; Write value: [`i3ccsr::regs::PioIntrStatusWriteVal`]
#[inline(always)]
pub fn pio_intr_status(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolPioIntrStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PioIntrStatusEnableReadVal`]; Write value: [`i3ccsr::regs::PioIntrStatusEnableWriteVal`]
#[inline(always)]
pub fn pio_intr_status_enable(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolPioIntrStatusEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PioIntrSignalEnableReadVal`]; Write value: [`i3ccsr::regs::PioIntrSignalEnableWriteVal`]
#[inline(always)]
pub fn pio_intr_signal_enable(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolPioIntrSignalEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PioIntrForceReadVal`]; Write value: [`i3ccsr::regs::PioIntrForceWriteVal`]
#[inline(always)]
pub fn pio_intr_force(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolPioIntrForce, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::PioControlReadVal`]; Write value: [`i3ccsr::regs::PioControlWriteVal`]
#[inline(always)]
pub fn pio_control(&self) -> ureg::RegRef<crate::i3ccsr::meta::PiocontrolPioControl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
#[derive(Clone, Copy)]
pub struct I3cEcBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> I3cEcBlock<TMmio> {
/// Register after the last EC must advertise ID == 0.
/// Termination register is added to guarantee that the discovery mechanism
/// reaches termination value.
///
/// Read value: [`i3ccsr::regs::ExtcapHeaderReadVal`]; Write value: [`i3ccsr::regs::ExtcapHeaderWriteVal`]
#[inline(always)]
pub fn termination_extcap_header(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::I3cEcTerminationExtcapHeader, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
#[derive(Clone, Copy)]
pub struct SecfwrecoveryifBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> SecfwrecoveryifBlock<TMmio> {
/// Read value: [`i3ccsr::regs::ExtcapHeaderReadVal`]; Write value: [`i3ccsr::regs::ExtcapHeaderWriteVal`]
#[inline(always)]
pub fn extcap_header(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifExtcapHeader, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prot_cap_0(&self) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifProtCap0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prot_cap_1(&self) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifProtCap1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::ProtCap2ReadVal`]; Write value: [`i3ccsr::regs::ProtCap2WriteVal`]
#[inline(always)]
pub fn prot_cap_2(&self) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifProtCap2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::ProtCap3ReadVal`]; Write value: [`i3ccsr::regs::ProtCap3WriteVal`]
#[inline(always)]
pub fn prot_cap_3(&self) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifProtCap3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DeviceId0ReadVal`]; Write value: [`i3ccsr::regs::DeviceId0WriteVal`]
#[inline(always)]
pub fn device_id_0(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceId0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_1(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceId1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_2(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceId2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_3(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceId3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_4(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceId4, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_5(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceId5, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_reserved(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceIdReserved, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DeviceStatus0ReadVal`]; Write value: [`i3ccsr::regs::DeviceStatus0WriteVal`]
#[inline(always)]
pub fn device_status_0(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceStatus0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::DeviceStatus1ReadVal`]; Write value: [`i3ccsr::regs::DeviceStatus1WriteVal`]
#[inline(always)]
pub fn device_status_1(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceStatus1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// For devices which support reset, this register will reset the device or management entity
///
/// Read value: [`i3ccsr::regs::DeviceResetReadVal`]; Write value: [`i3ccsr::regs::DeviceResetWriteVal`]
#[inline(always)]
pub fn device_reset(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifDeviceReset, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::RecoveryCtrlReadVal`]; Write value: [`i3ccsr::regs::RecoveryCtrlWriteVal`]
#[inline(always)]
pub fn recovery_ctrl(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifRecoveryCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::RecoveryStatusReadVal`]; Write value: [`i3ccsr::regs::RecoveryStatusWriteVal`]
#[inline(always)]
pub fn recovery_status(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifRecoveryStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::HwStatusReadVal`]; Write value: [`i3ccsr::regs::HwStatusWriteVal`]
#[inline(always)]
pub fn hw_status(&self) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifHwStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IndirectFifoCtrl0ReadVal`]; Write value: [`i3ccsr::regs::IndirectFifoCtrl0WriteVal`]
#[inline(always)]
pub fn indirect_fifo_ctrl_0(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifIndirectFifoCtrl0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x48 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn indirect_fifo_ctrl_1(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifIndirectFifoCtrl1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x4c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`i3ccsr::regs::IndirectFifoStatus0ReadVal`]; Write value: [`i3ccsr::regs::IndirectFifoStatus0WriteVal`]
#[inline(always)]
pub fn indirect_fifo_status_0(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifIndirectFifoStatus0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x50 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn indirect_fifo_status_1(
&self,
) -> ureg::RegRef<crate::i3ccsr::meta::SecfwrecoveryifIndirectFifoStatus1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x54 / core::mem::size_of::<u32>()),
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/lib.rs | hw/latest/registers/src/lib.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![no_std]
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct KvReadCtrlRegReadVal(u32);
impl KvReadCtrlRegReadVal {
/// Indicates that the read data is to come from the key vault.
/// Setting this bit to 1 initiates copying of data from the key vault.
#[inline(always)]
pub fn read_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Key Vault entry to retrieve the read data from for the engine
#[inline(always)]
pub fn read_entry(&self) -> u32 {
(self.0 >> 1) & 0x1f
}
/// Requested entry is a PCR. This is used only for SHA to hash extend, it's NOP in all other engines
#[inline(always)]
pub fn pcr_hash_extend(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// Reserved field
#[inline(always)]
pub fn rsvd(&self) -> u32 {
(self.0 >> 7) & 0x1ffffff
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> KvReadCtrlRegWriteVal {
KvReadCtrlRegWriteVal(self.0)
}
}
impl From<u32> for KvReadCtrlRegReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvReadCtrlRegReadVal> for u32 {
#[inline(always)]
fn from(val: KvReadCtrlRegReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct KvReadCtrlRegWriteVal(u32);
impl KvReadCtrlRegWriteVal {
/// Indicates that the read data is to come from the key vault.
/// Setting this bit to 1 initiates copying of data from the key vault.
#[inline(always)]
pub fn read_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Key Vault entry to retrieve the read data from for the engine
#[inline(always)]
pub fn read_entry(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 1)) | ((val & 0x1f) << 1))
}
/// Requested entry is a PCR. This is used only for SHA to hash extend, it's NOP in all other engines
#[inline(always)]
pub fn pcr_hash_extend(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
/// Reserved field
#[inline(always)]
pub fn rsvd(self, val: u32) -> Self {
Self((self.0 & !(0x1ffffff << 7)) | ((val & 0x1ffffff) << 7))
}
}
impl From<u32> for KvReadCtrlRegWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvReadCtrlRegWriteVal> for u32 {
#[inline(always)]
fn from(val: KvReadCtrlRegWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct KvStatusRegReadVal(u32);
impl KvStatusRegReadVal {
/// Key Vault control is ready for use
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Key Vault flow is done
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Indicates the error status of a key vault flow
#[inline(always)]
pub fn error(&self) -> super::enums::KvErrorE {
super::enums::KvErrorE::try_from((self.0 >> 2) & 0xff).unwrap()
}
}
impl From<u32> for KvStatusRegReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvStatusRegReadVal> for u32 {
#[inline(always)]
fn from(val: KvStatusRegReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct KvWriteCtrlRegReadVal(u32);
impl KvWriteCtrlRegReadVal {
/// Indicates that the result is to be stored in the key vault.
/// Setting this bit to 1 will copy the result to the keyvault when it is ready.
#[inline(always)]
pub fn write_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Key Vault entry to store the result
#[inline(always)]
pub fn write_entry(&self) -> u32 {
(self.0 >> 1) & 0x1f
}
/// HMAC KEY is a valid destination
#[inline(always)]
pub fn hmac_key_dest_valid(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// HMAC BLOCK is a valid destination
#[inline(always)]
pub fn hmac_block_dest_valid(&self) -> bool {
((self.0 >> 7) & 1) != 0
}
/// MLDSA_SEED is a valid destination
#[inline(always)]
pub fn mldsa_seed_dest_valid(&self) -> bool {
((self.0 >> 8) & 1) != 0
}
/// ECC PKEY is a valid destination
#[inline(always)]
pub fn ecc_pkey_dest_valid(&self) -> bool {
((self.0 >> 9) & 1) != 0
}
/// ECC SEED is a valid destination
#[inline(always)]
pub fn ecc_seed_dest_valid(&self) -> bool {
((self.0 >> 10) & 1) != 0
}
/// AES KEY is a valid destination
#[inline(always)]
pub fn aes_key_dest_valid(&self) -> bool {
((self.0 >> 11) & 1) != 0
}
/// MLKEM SEED is a valid destination
#[inline(always)]
pub fn mlkem_seed_dest_valid(&self) -> bool {
((self.0 >> 12) & 1) != 0
}
/// MLKEM MSG is a valid destination
#[inline(always)]
pub fn mlkem_msg_dest_valid(&self) -> bool {
((self.0 >> 13) & 1) != 0
}
/// AXI DMA data is a valid destination
#[inline(always)]
pub fn dma_data_dest_valid(&self) -> bool {
((self.0 >> 14) & 1) != 0
}
/// Reserved field
#[inline(always)]
pub fn rsvd(&self) -> u32 {
(self.0 >> 15) & 0x1ffff
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> KvWriteCtrlRegWriteVal {
KvWriteCtrlRegWriteVal(self.0)
}
}
impl From<u32> for KvWriteCtrlRegReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvWriteCtrlRegReadVal> for u32 {
#[inline(always)]
fn from(val: KvWriteCtrlRegReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct KvWriteCtrlRegWriteVal(u32);
impl KvWriteCtrlRegWriteVal {
/// Indicates that the result is to be stored in the key vault.
/// Setting this bit to 1 will copy the result to the keyvault when it is ready.
#[inline(always)]
pub fn write_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Key Vault entry to store the result
#[inline(always)]
pub fn write_entry(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 1)) | ((val & 0x1f) << 1))
}
/// HMAC KEY is a valid destination
#[inline(always)]
pub fn hmac_key_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
/// HMAC BLOCK is a valid destination
#[inline(always)]
pub fn hmac_block_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 7)) | (u32::from(val) << 7))
}
/// MLDSA_SEED is a valid destination
#[inline(always)]
pub fn mldsa_seed_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 8)) | (u32::from(val) << 8))
}
/// ECC PKEY is a valid destination
#[inline(always)]
pub fn ecc_pkey_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 9)) | (u32::from(val) << 9))
}
/// ECC SEED is a valid destination
#[inline(always)]
pub fn ecc_seed_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 10)) | (u32::from(val) << 10))
}
/// AES KEY is a valid destination
#[inline(always)]
pub fn aes_key_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 11)) | (u32::from(val) << 11))
}
/// MLKEM SEED is a valid destination
#[inline(always)]
pub fn mlkem_seed_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 12)) | (u32::from(val) << 12))
}
/// MLKEM MSG is a valid destination
#[inline(always)]
pub fn mlkem_msg_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 13)) | (u32::from(val) << 13))
}
/// AXI DMA data is a valid destination
#[inline(always)]
pub fn dma_data_dest_valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 14)) | (u32::from(val) << 14))
}
/// Reserved field
#[inline(always)]
pub fn rsvd(self, val: u32) -> Self {
Self((self.0 & !(0x1ffff << 15)) | ((val & 0x1ffff) << 15))
}
}
impl From<u32> for KvWriteCtrlRegWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvWriteCtrlRegWriteVal> for u32 {
#[inline(always)]
fn from(val: KvWriteCtrlRegWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u32)]
pub enum KvErrorE {
Success = 0,
KvReadFail = 1,
KvWriteFail = 2,
Reserved3 = 3,
Reserved4 = 4,
Reserved5 = 5,
Reserved6 = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Reserved10 = 10,
Reserved11 = 11,
Reserved12 = 12,
Reserved13 = 13,
Reserved14 = 14,
Reserved15 = 15,
Reserved16 = 16,
Reserved17 = 17,
Reserved18 = 18,
Reserved19 = 19,
Reserved20 = 20,
Reserved21 = 21,
Reserved22 = 22,
Reserved23 = 23,
Reserved24 = 24,
Reserved25 = 25,
Reserved26 = 26,
Reserved27 = 27,
Reserved28 = 28,
Reserved29 = 29,
Reserved30 = 30,
Reserved31 = 31,
Reserved32 = 32,
Reserved33 = 33,
Reserved34 = 34,
Reserved35 = 35,
Reserved36 = 36,
Reserved37 = 37,
Reserved38 = 38,
Reserved39 = 39,
Reserved40 = 40,
Reserved41 = 41,
Reserved42 = 42,
Reserved43 = 43,
Reserved44 = 44,
Reserved45 = 45,
Reserved46 = 46,
Reserved47 = 47,
Reserved48 = 48,
Reserved49 = 49,
Reserved50 = 50,
Reserved51 = 51,
Reserved52 = 52,
Reserved53 = 53,
Reserved54 = 54,
Reserved55 = 55,
Reserved56 = 56,
Reserved57 = 57,
Reserved58 = 58,
Reserved59 = 59,
Reserved60 = 60,
Reserved61 = 61,
Reserved62 = 62,
Reserved63 = 63,
Reserved64 = 64,
Reserved65 = 65,
Reserved66 = 66,
Reserved67 = 67,
Reserved68 = 68,
Reserved69 = 69,
Reserved70 = 70,
Reserved71 = 71,
Reserved72 = 72,
Reserved73 = 73,
Reserved74 = 74,
Reserved75 = 75,
Reserved76 = 76,
Reserved77 = 77,
Reserved78 = 78,
Reserved79 = 79,
Reserved80 = 80,
Reserved81 = 81,
Reserved82 = 82,
Reserved83 = 83,
Reserved84 = 84,
Reserved85 = 85,
Reserved86 = 86,
Reserved87 = 87,
Reserved88 = 88,
Reserved89 = 89,
Reserved90 = 90,
Reserved91 = 91,
Reserved92 = 92,
Reserved93 = 93,
Reserved94 = 94,
Reserved95 = 95,
Reserved96 = 96,
Reserved97 = 97,
Reserved98 = 98,
Reserved99 = 99,
Reserved100 = 100,
Reserved101 = 101,
Reserved102 = 102,
Reserved103 = 103,
Reserved104 = 104,
Reserved105 = 105,
Reserved106 = 106,
Reserved107 = 107,
Reserved108 = 108,
Reserved109 = 109,
Reserved110 = 110,
Reserved111 = 111,
Reserved112 = 112,
Reserved113 = 113,
Reserved114 = 114,
Reserved115 = 115,
Reserved116 = 116,
Reserved117 = 117,
Reserved118 = 118,
Reserved119 = 119,
Reserved120 = 120,
Reserved121 = 121,
Reserved122 = 122,
Reserved123 = 123,
Reserved124 = 124,
Reserved125 = 125,
Reserved126 = 126,
Reserved127 = 127,
Reserved128 = 128,
Reserved129 = 129,
Reserved130 = 130,
Reserved131 = 131,
Reserved132 = 132,
Reserved133 = 133,
Reserved134 = 134,
Reserved135 = 135,
Reserved136 = 136,
Reserved137 = 137,
Reserved138 = 138,
Reserved139 = 139,
Reserved140 = 140,
Reserved141 = 141,
Reserved142 = 142,
Reserved143 = 143,
Reserved144 = 144,
Reserved145 = 145,
Reserved146 = 146,
Reserved147 = 147,
Reserved148 = 148,
Reserved149 = 149,
Reserved150 = 150,
Reserved151 = 151,
Reserved152 = 152,
Reserved153 = 153,
Reserved154 = 154,
Reserved155 = 155,
Reserved156 = 156,
Reserved157 = 157,
Reserved158 = 158,
Reserved159 = 159,
Reserved160 = 160,
Reserved161 = 161,
Reserved162 = 162,
Reserved163 = 163,
Reserved164 = 164,
Reserved165 = 165,
Reserved166 = 166,
Reserved167 = 167,
Reserved168 = 168,
Reserved169 = 169,
Reserved170 = 170,
Reserved171 = 171,
Reserved172 = 172,
Reserved173 = 173,
Reserved174 = 174,
Reserved175 = 175,
Reserved176 = 176,
Reserved177 = 177,
Reserved178 = 178,
Reserved179 = 179,
Reserved180 = 180,
Reserved181 = 181,
Reserved182 = 182,
Reserved183 = 183,
Reserved184 = 184,
Reserved185 = 185,
Reserved186 = 186,
Reserved187 = 187,
Reserved188 = 188,
Reserved189 = 189,
Reserved190 = 190,
Reserved191 = 191,
Reserved192 = 192,
Reserved193 = 193,
Reserved194 = 194,
Reserved195 = 195,
Reserved196 = 196,
Reserved197 = 197,
Reserved198 = 198,
Reserved199 = 199,
Reserved200 = 200,
Reserved201 = 201,
Reserved202 = 202,
Reserved203 = 203,
Reserved204 = 204,
Reserved205 = 205,
Reserved206 = 206,
Reserved207 = 207,
Reserved208 = 208,
Reserved209 = 209,
Reserved210 = 210,
Reserved211 = 211,
Reserved212 = 212,
Reserved213 = 213,
Reserved214 = 214,
Reserved215 = 215,
Reserved216 = 216,
Reserved217 = 217,
Reserved218 = 218,
Reserved219 = 219,
Reserved220 = 220,
Reserved221 = 221,
Reserved222 = 222,
Reserved223 = 223,
Reserved224 = 224,
Reserved225 = 225,
Reserved226 = 226,
Reserved227 = 227,
Reserved228 = 228,
Reserved229 = 229,
Reserved230 = 230,
Reserved231 = 231,
Reserved232 = 232,
Reserved233 = 233,
Reserved234 = 234,
Reserved235 = 235,
Reserved236 = 236,
Reserved237 = 237,
Reserved238 = 238,
Reserved239 = 239,
Reserved240 = 240,
Reserved241 = 241,
Reserved242 = 242,
Reserved243 = 243,
Reserved244 = 244,
Reserved245 = 245,
Reserved246 = 246,
Reserved247 = 247,
Reserved248 = 248,
Reserved249 = 249,
Reserved250 = 250,
Reserved251 = 251,
Reserved252 = 252,
Reserved253 = 253,
Reserved254 = 254,
Reserved255 = 255,
}
impl KvErrorE {
#[inline(always)]
pub fn success(&self) -> bool {
*self == Self::Success
}
#[inline(always)]
pub fn kv_read_fail(&self) -> bool {
*self == Self::KvReadFail
}
#[inline(always)]
pub fn kv_write_fail(&self) -> bool {
*self == Self::KvWriteFail
}
}
impl TryFrom<u32> for KvErrorE {
type Error = ();
#[inline(always)]
fn try_from(val: u32) -> Result<KvErrorE, ()> {
if val < 0x100 {
Ok(unsafe { core::mem::transmute::<u32, KvErrorE>(val) })
} else {
Err(())
}
}
}
impl From<KvErrorE> for u32 {
fn from(val: KvErrorE) -> Self {
val as u32
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u32)]
pub enum PvErrorE {
Success = 0,
PvReadFail = 1,
PvWriteFail = 2,
Reserved3 = 3,
Reserved4 = 4,
Reserved5 = 5,
Reserved6 = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Reserved10 = 10,
Reserved11 = 11,
Reserved12 = 12,
Reserved13 = 13,
Reserved14 = 14,
Reserved15 = 15,
Reserved16 = 16,
Reserved17 = 17,
Reserved18 = 18,
Reserved19 = 19,
Reserved20 = 20,
Reserved21 = 21,
Reserved22 = 22,
Reserved23 = 23,
Reserved24 = 24,
Reserved25 = 25,
Reserved26 = 26,
Reserved27 = 27,
Reserved28 = 28,
Reserved29 = 29,
Reserved30 = 30,
Reserved31 = 31,
Reserved32 = 32,
Reserved33 = 33,
Reserved34 = 34,
Reserved35 = 35,
Reserved36 = 36,
Reserved37 = 37,
Reserved38 = 38,
Reserved39 = 39,
Reserved40 = 40,
Reserved41 = 41,
Reserved42 = 42,
Reserved43 = 43,
Reserved44 = 44,
Reserved45 = 45,
Reserved46 = 46,
Reserved47 = 47,
Reserved48 = 48,
Reserved49 = 49,
Reserved50 = 50,
Reserved51 = 51,
Reserved52 = 52,
Reserved53 = 53,
Reserved54 = 54,
Reserved55 = 55,
Reserved56 = 56,
Reserved57 = 57,
Reserved58 = 58,
Reserved59 = 59,
Reserved60 = 60,
Reserved61 = 61,
Reserved62 = 62,
Reserved63 = 63,
Reserved64 = 64,
Reserved65 = 65,
Reserved66 = 66,
Reserved67 = 67,
Reserved68 = 68,
Reserved69 = 69,
Reserved70 = 70,
Reserved71 = 71,
Reserved72 = 72,
Reserved73 = 73,
Reserved74 = 74,
Reserved75 = 75,
Reserved76 = 76,
Reserved77 = 77,
Reserved78 = 78,
Reserved79 = 79,
Reserved80 = 80,
Reserved81 = 81,
Reserved82 = 82,
Reserved83 = 83,
Reserved84 = 84,
Reserved85 = 85,
Reserved86 = 86,
Reserved87 = 87,
Reserved88 = 88,
Reserved89 = 89,
Reserved90 = 90,
Reserved91 = 91,
Reserved92 = 92,
Reserved93 = 93,
Reserved94 = 94,
Reserved95 = 95,
Reserved96 = 96,
Reserved97 = 97,
Reserved98 = 98,
Reserved99 = 99,
Reserved100 = 100,
Reserved101 = 101,
Reserved102 = 102,
Reserved103 = 103,
Reserved104 = 104,
Reserved105 = 105,
Reserved106 = 106,
Reserved107 = 107,
Reserved108 = 108,
Reserved109 = 109,
Reserved110 = 110,
Reserved111 = 111,
Reserved112 = 112,
Reserved113 = 113,
Reserved114 = 114,
Reserved115 = 115,
Reserved116 = 116,
Reserved117 = 117,
Reserved118 = 118,
Reserved119 = 119,
Reserved120 = 120,
Reserved121 = 121,
Reserved122 = 122,
Reserved123 = 123,
Reserved124 = 124,
Reserved125 = 125,
Reserved126 = 126,
Reserved127 = 127,
Reserved128 = 128,
Reserved129 = 129,
Reserved130 = 130,
Reserved131 = 131,
Reserved132 = 132,
Reserved133 = 133,
Reserved134 = 134,
Reserved135 = 135,
Reserved136 = 136,
Reserved137 = 137,
Reserved138 = 138,
Reserved139 = 139,
Reserved140 = 140,
Reserved141 = 141,
Reserved142 = 142,
Reserved143 = 143,
Reserved144 = 144,
Reserved145 = 145,
Reserved146 = 146,
Reserved147 = 147,
Reserved148 = 148,
Reserved149 = 149,
Reserved150 = 150,
Reserved151 = 151,
Reserved152 = 152,
Reserved153 = 153,
Reserved154 = 154,
Reserved155 = 155,
Reserved156 = 156,
Reserved157 = 157,
Reserved158 = 158,
Reserved159 = 159,
Reserved160 = 160,
Reserved161 = 161,
Reserved162 = 162,
Reserved163 = 163,
Reserved164 = 164,
Reserved165 = 165,
Reserved166 = 166,
Reserved167 = 167,
Reserved168 = 168,
Reserved169 = 169,
Reserved170 = 170,
Reserved171 = 171,
Reserved172 = 172,
Reserved173 = 173,
Reserved174 = 174,
Reserved175 = 175,
Reserved176 = 176,
Reserved177 = 177,
Reserved178 = 178,
Reserved179 = 179,
Reserved180 = 180,
Reserved181 = 181,
Reserved182 = 182,
Reserved183 = 183,
Reserved184 = 184,
Reserved185 = 185,
Reserved186 = 186,
Reserved187 = 187,
Reserved188 = 188,
Reserved189 = 189,
Reserved190 = 190,
Reserved191 = 191,
Reserved192 = 192,
Reserved193 = 193,
Reserved194 = 194,
Reserved195 = 195,
Reserved196 = 196,
Reserved197 = 197,
Reserved198 = 198,
Reserved199 = 199,
Reserved200 = 200,
Reserved201 = 201,
Reserved202 = 202,
Reserved203 = 203,
Reserved204 = 204,
Reserved205 = 205,
Reserved206 = 206,
Reserved207 = 207,
Reserved208 = 208,
Reserved209 = 209,
Reserved210 = 210,
Reserved211 = 211,
Reserved212 = 212,
Reserved213 = 213,
Reserved214 = 214,
Reserved215 = 215,
Reserved216 = 216,
Reserved217 = 217,
Reserved218 = 218,
Reserved219 = 219,
Reserved220 = 220,
Reserved221 = 221,
Reserved222 = 222,
Reserved223 = 223,
Reserved224 = 224,
Reserved225 = 225,
Reserved226 = 226,
Reserved227 = 227,
Reserved228 = 228,
Reserved229 = 229,
Reserved230 = 230,
Reserved231 = 231,
Reserved232 = 232,
Reserved233 = 233,
Reserved234 = 234,
Reserved235 = 235,
Reserved236 = 236,
Reserved237 = 237,
Reserved238 = 238,
Reserved239 = 239,
Reserved240 = 240,
Reserved241 = 241,
Reserved242 = 242,
Reserved243 = 243,
Reserved244 = 244,
Reserved245 = 245,
Reserved246 = 246,
Reserved247 = 247,
Reserved248 = 248,
Reserved249 = 249,
Reserved250 = 250,
Reserved251 = 251,
Reserved252 = 252,
Reserved253 = 253,
Reserved254 = 254,
Reserved255 = 255,
}
impl PvErrorE {
#[inline(always)]
pub fn success(&self) -> bool {
*self == Self::Success
}
#[inline(always)]
pub fn pv_read_fail(&self) -> bool {
*self == Self::PvReadFail
}
#[inline(always)]
pub fn pv_write_fail(&self) -> bool {
*self == Self::PvWriteFail
}
}
impl TryFrom<u32> for PvErrorE {
type Error = ();
#[inline(always)]
fn try_from(val: u32) -> Result<PvErrorE, ()> {
if val < 0x100 {
Ok(unsafe { core::mem::transmute::<u32, PvErrorE>(val) })
} else {
Err(())
}
}
}
impl From<PvErrorE> for u32 {
fn from(val: PvErrorE) -> Self {
val as u32
}
}
pub mod selector {
pub struct KvErrorESelector();
impl KvErrorESelector {
#[inline(always)]
pub fn success(&self) -> super::KvErrorE {
super::KvErrorE::Success
}
#[inline(always)]
pub fn kv_read_fail(&self) -> super::KvErrorE {
super::KvErrorE::KvReadFail
}
#[inline(always)]
pub fn kv_write_fail(&self) -> super::KvErrorE {
super::KvErrorE::KvWriteFail
}
}
pub struct PvErrorESelector();
impl PvErrorESelector {
#[inline(always)]
pub fn success(&self) -> super::PvErrorE {
super::PvErrorE::Success
}
#[inline(always)]
pub fn pv_read_fail(&self) -> super::PvErrorE {
super::PvErrorE::PvReadFail
}
#[inline(always)]
pub fn pv_write_fail(&self) -> super::PvErrorE {
super::PvErrorE::PvWriteFail
}
}
}
}
pub mod meta {
//! Additional metadata needed by ureg.
}
pub mod abr;
pub mod aes;
pub mod aes_clp;
pub mod axi_dma;
pub mod csrng;
pub mod doe;
pub mod dv;
pub mod ecc;
pub mod el2_pic_ctrl;
pub mod entropy_src;
pub mod hmac;
pub mod i3ccsr;
pub mod kmac;
pub mod kv;
pub mod lc_ctrl;
pub mod mbox;
pub mod mbox_sram;
pub mod mci;
pub mod mcu_mbox0;
pub mod mcu_mbox1;
pub mod mcu_sram;
pub mod mcu_trace_buffer;
pub mod otp_ctrl;
pub mod pv;
pub mod sha256;
pub mod sha3;
pub mod sha512;
pub mod sha512_acc;
pub mod soc_ifc;
pub mod soc_ifc_trng;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/soc_ifc_trng.rs | hw/latest/registers/src/soc_ifc_trng.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct SocIfcTrngReg {
_priv: (),
}
impl SocIfcTrngReg {
pub const PTR: *mut u32 = 0x30030000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Storage for the requested TRNG Data.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_trng_data(
&self,
) -> ureg::Array<12, ureg::RegRef<crate::soc_ifc_trng::meta::CptraTrngData, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x78 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// TRNG Status register to indicate request and done
///
/// Read value: [`soc_ifc_trng::regs::CptraTrngStatusReadVal`]; Write value: [`soc_ifc_trng::regs::CptraTrngStatusWriteVal`]
#[inline(always)]
pub fn cptra_trng_status(
&self,
) -> ureg::RegRef<crate::soc_ifc_trng::meta::CptraTrngStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xac / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct CptraTrngStatusReadVal(u32);
impl CptraTrngStatusReadVal {
/// Indicates that there is a request for TRNG Data.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
#[inline(always)]
pub fn data_req(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Indicates that the requests TRNG Data is done and stored in the TRNG Data register.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RW
/// [br]When DATA_REQ is 0 DATA_WR_DONE will also be 0
#[inline(always)]
pub fn data_wr_done(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CptraTrngStatusWriteVal {
CptraTrngStatusWriteVal(self.0)
}
}
impl From<u32> for CptraTrngStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CptraTrngStatusReadVal> for u32 {
#[inline(always)]
fn from(val: CptraTrngStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CptraTrngStatusWriteVal(u32);
impl CptraTrngStatusWriteVal {
/// Indicates that there is a request for TRNG Data.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
#[inline(always)]
pub fn data_req(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Indicates that the requests TRNG Data is done and stored in the TRNG Data register.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RW
/// [br]When DATA_REQ is 0 DATA_WR_DONE will also be 0
#[inline(always)]
pub fn data_wr_done(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for CptraTrngStatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CptraTrngStatusWriteVal> for u32 {
#[inline(always)]
fn from(val: CptraTrngStatusWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type CptraTrngData = ureg::ReadWriteReg32<0, u32, u32>;
pub type CptraTrngStatus = ureg::ReadWriteReg32<
0,
crate::soc_ifc_trng::regs::CptraTrngStatusReadVal,
crate::soc_ifc_trng::regs::CptraTrngStatusWriteVal,
>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/otp_ctrl.rs | hw/latest/registers/src/otp_ctrl.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct OtpCtrl {
_priv: (),
}
impl OtpCtrl {
pub const PTR: *mut u32 = 0x10060000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`otp_ctrl::regs::InterruptStateReadVal`]; Write value: [`otp_ctrl::regs::InterruptStateWriteVal`]
#[inline(always)]
pub fn interrupt_state(&self) -> ureg::RegRef<crate::otp_ctrl::meta::InterruptState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::InterruptEnableReadVal`]; Write value: [`otp_ctrl::regs::InterruptEnableWriteVal`]
#[inline(always)]
pub fn interrupt_enable(&self) -> ureg::RegRef<crate::otp_ctrl::meta::InterruptEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::InterruptTestReadVal`]; Write value: [`otp_ctrl::regs::InterruptTestWriteVal`]
#[inline(always)]
pub fn interrupt_test(&self) -> ureg::RegRef<crate::otp_ctrl::meta::InterruptTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::AlertTestReadVal`]; Write value: [`otp_ctrl::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::otp_ctrl::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::StatusReadVal`]; Write value: [`otp_ctrl::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Register write enable for all direct access interface registers.
///
/// Read value: [`otp_ctrl::regs::DirectAccessRegwenReadVal`]; Write value: [`otp_ctrl::regs::DirectAccessRegwenWriteVal`]
#[inline(always)]
pub fn direct_access_regwen(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::DirectAccessRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Command register for direct accesses.
///
/// Read value: [`otp_ctrl::regs::DirectAccessCmdReadVal`]; Write value: [`otp_ctrl::regs::DirectAccessCmdWriteVal`]
#[inline(always)]
pub fn direct_access_cmd(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::DirectAccessCmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Address register for direct accesses.
///
/// Read value: [`otp_ctrl::regs::DirectAccessAddressReadVal`]; Write value: [`otp_ctrl::regs::DirectAccessAddressWriteVal`]
#[inline(always)]
pub fn direct_access_address(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::DirectAccessAddress, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x64 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Register write enable for !!CHECK_TRIGGER.
///
/// Read value: [`otp_ctrl::regs::CheckTriggerRegwenReadVal`]; Write value: [`otp_ctrl::regs::CheckTriggerRegwenWriteVal`]
#[inline(always)]
pub fn check_trigger_regwen(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::CheckTriggerRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x78 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Command register for direct accesses.
///
/// Read value: [`otp_ctrl::regs::CheckTriggerReadVal`]; Write value: [`otp_ctrl::regs::CheckTriggerWriteVal`]
#[inline(always)]
pub fn check_trigger(&self) -> ureg::RegRef<crate::otp_ctrl::meta::CheckTrigger, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x7c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Register write enable for !!INTEGRITY_CHECK_PERIOD and !!CONSISTENCY_CHECK_PERIOD.
///
/// Read value: [`otp_ctrl::regs::CheckRegwenReadVal`]; Write value: [`otp_ctrl::regs::CheckRegwenWriteVal`]
#[inline(always)]
pub fn check_regwen(&self) -> ureg::RegRef<crate::otp_ctrl::meta::CheckRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Timeout value for the integrity and consistency checks.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn check_timeout(&self) -> ureg::RegRef<crate::otp_ctrl::meta::CheckTimeout, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x84 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This value specifies the maximum period that can be generated pseudo-randomly.Only applies to the HW_CFG* and SECRET* partitions once they are locked.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn integrity_check_period(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::IntegrityCheckPeriod, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x88 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This value specifies the maximum period that can be generated pseudo-randomly.This applies to the LIFE_CYCLE partition and the HW_CFG* and SECRET* partitions once they are locked.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn consistency_check_period(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::ConsistencyCheckPeriod, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x8c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the SW_MANUF_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::SwManufPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::SwManufPartitionReadLockWriteVal`]
#[inline(always)]
pub fn sw_manuf_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::SwManufPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x90 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the SVN_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::SvnPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::SvnPartitionReadLockWriteVal`]
#[inline(always)]
pub fn svn_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::SvnPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x94 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the VENDOR_TEST_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::VendorTestPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::VendorTestPartitionReadLockWriteVal`]
#[inline(always)]
pub fn vendor_test_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::VendorTestPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x98 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the VENDOR_HASHES_MANUF_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::VendorHashesManufPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::VendorHashesManufPartitionReadLockWriteVal`]
#[inline(always)]
pub fn vendor_hashes_manuf_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::VendorHashesManufPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x9c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the VENDOR_HASHES_PROD_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::VendorHashesProdPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::VendorHashesProdPartitionReadLockWriteVal`]
#[inline(always)]
pub fn vendor_hashes_prod_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::VendorHashesProdPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the VENDOR_REVOCATIONS_PROD_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::VendorRevocationsProdPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::VendorRevocationsProdPartitionReadLockWriteVal`]
#[inline(always)]
pub fn vendor_revocations_prod_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::VendorRevocationsProdPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Runtime read lock for the VENDOR_NON_SECRET_PROD_PARTITION partition.
///
/// Read value: [`otp_ctrl::regs::VendorNonSecretProdPartitionReadLockReadVal`]; Write value: [`otp_ctrl::regs::VendorNonSecretProdPartitionReadLockWriteVal`]
#[inline(always)]
pub fn vendor_non_secret_prod_partition_read_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::VendorNonSecretProdPartitionReadLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Volatile write lock for vendor public key hashes.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn vendor_pk_hash_volatile_lock(
&self,
) -> ureg::RegRef<crate::otp_ctrl::meta::VendorPkHashVolatileLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xac / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr0ReadVal`]; Write value: [`otp_ctrl::regs::Csr0WriteVal`]
#[inline(always)]
pub fn csr0(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x120 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr1ReadVal`]; Write value: [`otp_ctrl::regs::Csr1WriteVal`]
#[inline(always)]
pub fn csr1(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x124 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr2ReadVal`]; Write value: [`otp_ctrl::regs::Csr2WriteVal`]
#[inline(always)]
pub fn csr2(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x128 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr3ReadVal`]; Write value: [`otp_ctrl::regs::Csr3WriteVal`]
#[inline(always)]
pub fn csr3(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x12c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr4ReadVal`]; Write value: [`otp_ctrl::regs::Csr4WriteVal`]
#[inline(always)]
pub fn csr4(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr4, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x130 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr5ReadVal`]; Write value: [`otp_ctrl::regs::Csr5WriteVal`]
#[inline(always)]
pub fn csr5(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr5, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x134 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr6ReadVal`]; Write value: [`otp_ctrl::regs::Csr6WriteVal`]
#[inline(always)]
pub fn csr6(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr6, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x138 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`otp_ctrl::regs::Csr7ReadVal`]; Write value: [`otp_ctrl::regs::Csr7WriteVal`]
#[inline(always)]
pub fn csr7(&self) -> ureg::RegRef<crate::otp_ctrl::meta::Csr7, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x13c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn err_code_rf(&self) -> ErrCodeRfBlock<&TMmio> {
ErrCodeRfBlock {
ptr: unsafe { self.ptr.add(0x14 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn dai_wdata_rf(&self) -> DaiWdataRfBlock<&TMmio> {
DaiWdataRfBlock {
ptr: unsafe { self.ptr.add(0x68 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn dai_rdata_rf(&self) -> DaiRdataRfBlock<&TMmio> {
DaiRdataRfBlock {
ptr: unsafe { self.ptr.add(0x70 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_test_unlock_partition_digest(
&self,
) -> SecretTestUnlockPartitionDigestBlock<&TMmio> {
SecretTestUnlockPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0xb0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_manuf_partition_digest(&self) -> SecretManufPartitionDigestBlock<&TMmio> {
SecretManufPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0xb8 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_prod_partition_0_digest(&self) -> SecretProdPartition0DigestBlock<&TMmio> {
SecretProdPartition0DigestBlock {
ptr: unsafe { self.ptr.add(0xc0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_prod_partition_1_digest(&self) -> SecretProdPartition1DigestBlock<&TMmio> {
SecretProdPartition1DigestBlock {
ptr: unsafe { self.ptr.add(0xc8 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_prod_partition_2_digest(&self) -> SecretProdPartition2DigestBlock<&TMmio> {
SecretProdPartition2DigestBlock {
ptr: unsafe { self.ptr.add(0xd0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_prod_partition_3_digest(&self) -> SecretProdPartition3DigestBlock<&TMmio> {
SecretProdPartition3DigestBlock {
ptr: unsafe { self.ptr.add(0xd8 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn sw_manuf_partition_digest(&self) -> SwManufPartitionDigestBlock<&TMmio> {
SwManufPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0xe0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn secret_lc_transition_partition_digest(
&self,
) -> SecretLcTransitionPartitionDigestBlock<&TMmio> {
SecretLcTransitionPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0xe8 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn vendor_test_partition_digest(&self) -> VendorTestPartitionDigestBlock<&TMmio> {
VendorTestPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0xf0 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn vendor_hashes_manuf_partition_digest(
&self,
) -> VendorHashesManufPartitionDigestBlock<&TMmio> {
VendorHashesManufPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0xf8 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn vendor_hashes_prod_partition_digest(
&self,
) -> VendorHashesProdPartitionDigestBlock<&TMmio> {
VendorHashesProdPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0x100 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn vendor_revocations_prod_partition_digest(
&self,
) -> VendorRevocationsProdPartitionDigestBlock<&TMmio> {
VendorRevocationsProdPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0x108 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn vendor_secret_prod_partition_digest(
&self,
) -> VendorSecretProdPartitionDigestBlock<&TMmio> {
VendorSecretProdPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0x110 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
#[inline(always)]
pub fn vendor_non_secret_prod_partition_digest(
&self,
) -> VendorNonSecretProdPartitionDigestBlock<&TMmio> {
VendorNonSecretProdPartitionDigestBlock {
ptr: unsafe { self.ptr.add(0x118 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct ErrCodeRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> ErrCodeRfBlock<TMmio> {
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_0(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_1(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_2(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_3(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_4(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode4, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_5(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode5, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_6(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode6, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_7(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode7, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
pub fn err_code_8(&self) -> ureg::RegRef<crate::otp_ctrl::meta::ErrCodeRfErrCode8, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds information about error conditions that occurred in the agents
/// interacting with the OTP macr via the internal bus. The error codes should be checked
/// if the partitions, DAI or LCI flag an error in the !!STATUS register, or when an
/// !!INTR_STATE.otp_error has been triggered. Note that all errors trigger an otp_error
/// interrupt, and in addition some errors may trigger either an fatal_macr_error or an
/// fatal_check_error alert.
///
/// Read value: [`otp_ctrl::regs::ErrCodeRegTReadVal`]; Write value: [`otp_ctrl::regs::ErrCodeRegTWriteVal`]
#[inline(always)]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mci.rs | hw/latest/registers/src/mci.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct MciReg {
_priv: (),
}
impl MciReg {
pub const PTR: *mut u32 = 0 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// MCU HW Capabilities. Initialized with reset values, rewritable by MCU FW.
/// [br]Read-only once locked.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hw_capabilities(&self) -> ureg::RegRef<crate::mci::meta::HwCapabilities, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// MCU FW Capabilities. Initialized with reset values. rewrtitable by MCU FW.
/// [br]Read-only once locked.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_capabilities(&self) -> ureg::RegRef<crate::mci::meta::FwCapabilities, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Lock register to disable further firmware modifications to capabilities registers.
/// [br]Once set, this register may not be cleared until a warm reset. If set, the values in HW_CAPABILITIES and FW_CAPABILITIES may not be modified.
/// [br]Read-only once locked.
///
/// Read value: [`mci::regs::CapLockReadVal`]; Write value: [`mci::regs::CapLockWriteVal`]
#[inline(always)]
pub fn cap_lock(&self) -> ureg::RegRef<crate::mci::meta::CapLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HW revision ID for Manufacturer Control components (MCU & MCI) that matches the official
/// final release milestone of Caliptra Subsystem.
///
/// Read value: [`mci::regs::HwRevIdReadVal`]; Write value: [`mci::regs::HwRevIdWriteVal`]
#[inline(always)]
pub fn hw_rev_id(&self) -> ureg::RegRef<crate::mci::meta::HwRevId, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// MCU FW revision ID
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_rev_id(&self) -> ureg::Array<2, ureg::RegRef<crate::mci::meta::FwRevId, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// MCU HW Configuration
///
/// Read value: [`mci::regs::HwConfig0ReadVal`]; Write value: [`mci::regs::HwConfig0WriteVal`]
#[inline(always)]
pub fn hw_config0(&self) -> ureg::RegRef<crate::mci::meta::HwConfig0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// MCU HW Configuration
///
/// Read value: [`mci::regs::HwConfig1ReadVal`]; Write value: [`mci::regs::HwConfig1WriteVal`]
#[inline(always)]
pub fn hw_config1(&self) -> ureg::RegRef<crate::mci::meta::HwConfig1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// MCU IFU AXI USER Strap
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mcu_ifu_axi_user(&self) -> ureg::RegRef<crate::mci::meta::McuIfuAxiUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// MCU LSU AXI USER Strap
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mcu_lsu_axi_user(&self) -> ureg::RegRef<crate::mci::meta::McuLsuAxiUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Agent with access to MCU SRAM Execution region. Typically Caliptra Core
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mcu_sram_config_axi_user(
&self,
) -> ureg::RegRef<crate::mci::meta::McuSramConfigAxiUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SOC agent with special access to MCI register bank
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn soc_config_axi_user(&self) -> ureg::RegRef<crate::mci::meta::SocConfigAxiUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the status of the firmware flows.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_flow_status(&self) -> ureg::RegRef<crate::mci::meta::FwFlowStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the status of HW FSMs and other flows.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::HwFlowStatusReadVal`]; Write value: [`mci::regs::HwFlowStatusWriteVal`]
#[inline(always)]
pub fn hw_flow_status(&self) -> ureg::RegRef<crate::mci::meta::HwFlowStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates to ROM the originating cause for the PC to be reset to 0.
/// Firmware Update Reset indicator is reset by the warm reset and updated by SW applying MCU FW updated.
/// Warm Reset indicator is reset by the cold reset.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::ResetReasonReadVal`]; Write value: [`mci::regs::ResetReasonWriteVal`]
#[inline(always)]
pub fn reset_reason(&self) -> ureg::RegRef<crate::mci::meta::ResetReason, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the status of the rests controlled by MCI.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::ResetStatusReadVal`]; Write value: [`mci::regs::ResetStatusWriteVal`]
#[inline(always)]
pub fn reset_status(&self) -> ureg::RegRef<crate::mci::meta::ResetStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates current hardware security state.
///
/// Read value: [`mci::regs::SecurityStateReadVal`]; Write value: [`mci::regs::SecurityStateWriteVal`]
#[inline(always)]
pub fn security_state(&self) -> ureg::RegRef<crate::mci::meta::SecurityState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates fatal hardware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// mci_error_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, clearing
/// the bit in this register will not cause the interrupt to deassert.
/// Only an MCI reset will clear the fatal error interrupt.
/// [br]AXI Access: RW1C
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::HwErrorFatalReadVal`]; Write value: [`mci::regs::HwErrorFatalWriteVal`]
#[inline(always)]
pub fn hw_error_fatal(&self) -> ureg::RegRef<crate::mci::meta::HwErrorFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x50 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates fatal error from another IP within Caliptra SS. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// mci_error_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, clearing
/// the bit in this register will not cause the interrupt to deassert.
/// Only an MCI reset will clear the fatal error interrupt.
/// [br]AXI Access: RW1C
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::AggErrorFatalReadVal`]; Write value: [`mci::regs::AggErrorFatalWriteVal`]
#[inline(always)]
pub fn agg_error_fatal(&self) -> ureg::RegRef<crate::mci::meta::AggErrorFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x54 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates non-fatal hardware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// mci_error_non_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, any
/// change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the mci_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] HW_ERROR_NON_FATAL
/// [br] [*] AGG_ERROR_NON_FATAL
/// [br] [*] FW_ERROR_NON_FATAL
/// [br] [*] hw_error_non_fatal_mask
/// [br] [*] agg_error_non_fatal_mask
/// [br] [*] fw_error_non_fatal_mask
/// [/list]
/// [br]AXI Access: RW1C
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::HwErrorNonFatalReadVal`]; Write value: [`mci::regs::HwErrorNonFatalWriteVal`]
#[inline(always)]
pub fn hw_error_non_fatal(&self) -> ureg::RegRef<crate::mci::meta::HwErrorNonFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x58 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates non-fatal error from another IP within the Caliptra SS. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// mci_error_non_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, any
/// change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the mci_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] HW_ERROR_NON_FATAL
/// [br] [*] AGG_ERROR_NON_FATAL
/// [br] [*] FW_ERROR_NON_FATAL
/// [br] [*] hw_error_non_fatal_mask
/// [br] [*] agg_error_non_fatal_mask
/// [br] [*] fw_error_non_fatal_mask
/// [/list]
/// [br]AXI Access: RW1C
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`mci::regs::AggErrorNonFatalReadVal`]; Write value: [`mci::regs::AggErrorNonFatalWriteVal`]
#[inline(always)]
pub fn agg_error_non_fatal(&self) -> ureg::RegRef<crate::mci::meta::AggErrorNonFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates fatal firmware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// mci_error_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, clearing
/// the bit in this register will not cause the interrupt to deassert.
/// Only an MCI reset will clear the fatal error interrupt.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_error_fatal(&self) -> ureg::RegRef<crate::mci::meta::FwErrorFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates non-fatal firmware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// mci_error_non_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, any
/// change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the mci_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] HW_ERROR_NON_FATAL
/// [br] [*] AGG_ERROR_NON_FATAL
/// [br] [*] FW_ERROR_NON_FATAL
/// [br] [*] hw_error_non_fatal_mask
/// [br] [*] agg_error_non_fatal_mask
/// [br] [*] fw_error_non_fatal_mask
/// [/list]
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_error_non_fatal(&self) -> ureg::RegRef<crate::mci::meta::FwErrorNonFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x64 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Encoded error value for hardware errors.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn hw_error_enc(&self) -> ureg::RegRef<crate::mci::meta::HwErrorEnc, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x68 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Encoded error value for firmware errors.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_error_enc(&self) -> ureg::RegRef<crate::mci::meta::FwErrorEnc, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x6c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Firmware Extended Error information for firmware errors.
/// [br]TAP Access [with debug intent set]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_extended_error_info(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::mci::meta::FwExtendedErrorInfo, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x70 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Bit mask for the register HW_ERROR_FATAL to determine
/// which bits are disabled for interrupt generation on the
/// mci_error_fatal output signal.
/// [br]A value of 1 in a field of this register means the corresponding bit
/// position in HW_ERROR_FATAL will not produce an interrupt
/// output assertion. If a hardware error bit is set and was previously
/// masked, and firmware performs a write to clear the corresponding mask
/// bit in this register, the interrupt output will not be asserted. Only
/// the same error condition reoccurring while it is unmasked will cause
/// a new assertion of the interrupt output.
/// [br]Firmware can not cause the interrupt output to deassert by setting
/// mask bits for fatal error conditions that have already triggered the
/// interrupt.
///
/// Read value: [`mci::regs::InternalHwErrorFatalMaskReadVal`]; Write value: [`mci::regs::InternalHwErrorFatalMaskWriteVal`]
#[inline(always)]
pub fn internal_hw_error_fatal_mask(
&self,
) -> ureg::RegRef<crate::mci::meta::InternalHwErrorFatalMask, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x90 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Bit mask for the register HW_ERROR_NON_FATAL to determine
/// which bits are disabled for interrupt generation on the
/// mci_error_non_fatal output signal.
/// [br]A value of 1 in a field of this register means the corresponding bit
/// position in HW_ERROR_NON_FATAL will not produce an interrupt
/// output assertion. If a hardware error bit is set that was previously
/// masked, and firmware performs a write to clear the corresponding mask
/// bit in this register, the interrupt output will not be asserted. Only
/// the same error condition reoccurring while it is unmasked will cause
/// a new assertion of the interrupt output.
/// [br]Any change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the mci_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] HW_ERROR_NON_FATAL
/// [br] [*] AGG_ERROR_NON_FATAL
/// [br] [*] FW_ERROR_NON_FATAL
/// [br] [*] hw_error_non_fatal_mask
/// [br] [*] agg_error_non_fatal_mask
/// [br] [*] fw_error_non_fatal_mask
/// [/list]
///
/// Read value: [`mci::regs::InternalHwErrorNonFatalMaskReadVal`]; Write value: [`mci::regs::InternalHwErrorNonFatalMaskWriteVal`]
#[inline(always)]
pub fn internal_hw_error_non_fatal_mask(
&self,
) -> ureg::RegRef<crate::mci::meta::InternalHwErrorNonFatalMask, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x94 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Bit mask for the register AGG_ERROR_FATAL to determine
/// which bits are disabled for interrupt generation on the
/// mci_error_fatal output signal.
/// [br]A value of 1 in a field of this register means the corresponding bit
/// position in AGG_ERROR_FATAL will not produce an interrupt
/// output assertion. If a hardware error bit is set and was previously
/// masked, and firmware performs a write to clear the corresponding mask
/// bit in this register, the interrupt output will not be asserted. Only
/// the same error condition reoccurring while it is unmasked will cause
/// a new assertion of the interrupt output.
/// [br]Firmware can not cause the interrupt output to deassert by setting
/// mask bits for fatal error conditions that have already triggered the
/// interrupt.
///
/// Read value: [`mci::regs::InternalAggErrorFatalMaskReadVal`]; Write value: [`mci::regs::InternalAggErrorFatalMaskWriteVal`]
#[inline(always)]
pub fn internal_agg_error_fatal_mask(
&self,
) -> ureg::RegRef<crate::mci::meta::InternalAggErrorFatalMask, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x98 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Bit mask for the register AGG_ERROR_NON_FATAL to determine
/// which bits are disabled for interrupt generation on the
/// mci_error_non_fatal output signal.
/// [br]A value of 1 in a field of this register means the corresponding bit
/// position in AGG_ERROR_NON_FATAL will not produce an interrupt
/// output assertion. If a hardware error bit is set that was previously
/// masked, and firmware performs a write to clear the corresponding mask
/// bit in this register, the interrupt output will not be asserted. Only
/// the same error condition reoccurring while it is unmasked will cause
/// a new assertion of the interrupt output.
/// [br]Any change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the mci_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] HW_ERROR_NON_FATAL
/// [br] [*] AGG_ERROR_NON_FATAL
/// [br] [*] FW_ERROR_NON_FATAL
/// [br] [*] hw_error_non_fatal_mask
/// [br] [*] agg_error_non_fatal_mask
/// [br] [*] fw_error_non_fatal_mask
/// [/list]
///
/// Read value: [`mci::regs::InternalAggErrorNonFatalMaskReadVal`]; Write value: [`mci::regs::InternalAggErrorNonFatalMaskWriteVal`]
#[inline(always)]
pub fn internal_agg_error_non_fatal_mask(
&self,
) -> ureg::RegRef<crate::mci::meta::InternalAggErrorNonFatalMask, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x9c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Bit mask for the register FW_ERROR_FATAL to determine
/// which bits are disabled for interrupt generation on the
/// mci_error_fatal output signal.
/// [br]A value of 1 in a field of this register means the corresponding bit
/// position in FW_ERROR_FATAL will not produce an interrupt
/// output assertion. If a firmware error bit is set and was previously
/// masked, and firmware performs a write to clear the corresponding mask
/// bit in this register, the interrupt output will not be asserted. Only
/// the same error bit being cleared then set again while it is unmasked will cause
/// a new assertion of the interrupt output.
/// [br]Firmware can not cause the interrupt output to deassert by setting
/// mask bits for fatal error conditions that have already triggered the
/// interrupt.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn internal_fw_error_fatal_mask(
&self,
) -> ureg::RegRef<crate::mci::meta::InternalFwErrorFatalMask, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Bit mask for the register FW_ERROR_NON_FATAL to determine
/// which bits are disabled for interrupt generation on the
/// mci_error_non_fatal output signal.
/// [br]A value of 1 in a field of this register means the corresponding bit
/// position in FW_ERROR_NON_FATAL will not produce an interrupt
/// output assertion. If a firmware error bit is set that was previously
/// masked, and firmware performs a write to clear the corresponding mask
/// bit in this register, the interrupt output will not be asserted. Only
/// the same error bit being cleared then set again while it is unmasked will cause
/// a new assertion of the interrupt output.
/// [br]Any change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the mci_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] HW_ERROR_NON_FATAL
/// [br] [*] AGG_ERROR_NON_FATAL
/// [br] [*] FW_ERROR_NON_FATAL
/// [br] [*] hw_error_non_fatal_mask
/// [br] [*] agg_error_non_fatal_mask
/// [br] [*] fw_error_non_fatal_mask
/// [/list]
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn internal_fw_error_non_fatal_mask(
&self,
) -> ureg::RegRef<crate::mci::meta::InternalFwErrorNonFatalMask, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer1 enable register
///
/// Read value: [`mci::regs::WdtTimer1EnReadVal`]; Write value: [`mci::regs::WdtTimer1EnWriteVal`]
#[inline(always)]
pub fn wdt_timer1_en(&self) -> ureg::RegRef<crate::mci::meta::WdtTimer1En, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer1 control register
///
/// Read value: [`mci::regs::WdtTimer1CtrlReadVal`]; Write value: [`mci::regs::WdtTimer1CtrlWriteVal`]
#[inline(always)]
pub fn wdt_timer1_ctrl(&self) -> ureg::RegRef<crate::mci::meta::WdtTimer1Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer1 timeout register
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn wdt_timer1_timeout_period(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::mci::meta::WdtTimer1TimeoutPeriod, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xb8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer2 enable register. Note: Setting this to 1 will disable the default cascaded mode and will have both timers count independently.
///
/// Read value: [`mci::regs::WdtTimer2EnReadVal`]; Write value: [`mci::regs::WdtTimer2EnWriteVal`]
#[inline(always)]
pub fn wdt_timer2_en(&self) -> ureg::RegRef<crate::mci::meta::WdtTimer2En, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer2 control register
///
/// Read value: [`mci::regs::WdtTimer2CtrlReadVal`]; Write value: [`mci::regs::WdtTimer2CtrlWriteVal`]
#[inline(always)]
pub fn wdt_timer2_ctrl(&self) -> ureg::RegRef<crate::mci::meta::WdtTimer2Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer2 timeout register
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn wdt_timer2_timeout_period(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::mci::meta::WdtTimer2TimeoutPeriod, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xc8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Watchdog timer status register
///
/// Read value: [`mci::regs::WdtStatusReadVal`]; Write value: [`mci::regs::WdtStatusWriteVal`]
#[inline(always)]
pub fn wdt_status(&self) -> ureg::RegRef<crate::mci::meta::WdtStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xd0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SOC provided count in cycles for WDT1 timeout.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn wdt_cfg(&self) -> ureg::Array<2, ureg::RegRef<crate::mci::meta::WdtCfg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xd4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mcu_mbox0.rs | hw/latest/registers/src/mcu_mbox0.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct McuMbox0Csr {
_priv: (),
}
impl McuMbox0Csr {
pub const PTR: *mut u32 = 0x400000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Mailbox SRAM storage. The maximum size is 2MB, but is configurable by the integration team. Only writable once a lock is obtained. Cleared from 0x0 to max DLEN after lock is released.
/// [br] Root user, user with lock on mailbox, and target user have RW access.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_sram(
&self,
) -> ureg::Array<524288, ureg::RegRef<crate::mcu_mbox0::meta::MboxSram, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Mailbox lock register for mailbox access, reading 0 will set the lock. On reset release lock is set to root_user (MCU) to allow SRAM clearing
///
/// Read value: [`mcu_mbox0::regs::MboxLockReadVal`]; Write value: [`mcu_mbox0::regs::MboxLockWriteVal`]
#[inline(always)]
pub fn mbox_lock(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the AXI USER that locked the mailbox. Cleared when lock is cleared.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_user(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200004 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the AXI USER for target user access. Only valid when mbox_target_user_valid is set. Only controllable by the root user. Only accessible when mailbox is locked. Cleared when lock is cleared.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_target_user(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxTargetUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200008 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Enables access for the mbox_target_user. Only controllable by the root user. Only accessible when mailbox is locked. Cleared when lock is cleared.
///
/// Read value: [`mcu_mbox0::regs::MboxTargetUserValidReadVal`]; Write value: [`mcu_mbox0::regs::MboxTargetUserValidWriteVal`]
#[inline(always)]
pub fn mbox_target_user_valid(
&self,
) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxTargetUserValid, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x20000c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Command requested for data in mailbox. Cleared when lock is cleared.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_cmd(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxCmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200010 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Data length for mailbox access in bytes. Cleared when lock is cleared
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_dlen(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxDlen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200014 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Mailbox execute register indicates to receiver that the sender is done.
///
/// Read value: [`mcu_mbox0::regs::MboxExecuteReadVal`]; Write value: [`mcu_mbox0::regs::MboxExecuteWriteVal`]
#[inline(always)]
pub fn mbox_execute(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxExecute, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200018 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status of the mailbox command
///
/// Read value: [`mcu_mbox0::regs::MboxTargetStatusReadVal`]; Write value: [`mcu_mbox0::regs::MboxTargetStatusWriteVal`]
#[inline(always)]
pub fn mbox_target_status(
&self,
) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxTargetStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x20001c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status of the mailbox command
///
/// Read value: [`mcu_mbox0::regs::MboxCmdStatusReadVal`]; Write value: [`mcu_mbox0::regs::MboxCmdStatusWriteVal`]
#[inline(always)]
pub fn mbox_cmd_status(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxCmdStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200020 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HW status of the mailbox
///
/// Read value: [`mcu_mbox0::regs::MboxHwStatusReadVal`]; Write value: [`mcu_mbox0::regs::MboxHwStatusWriteVal`]
#[inline(always)]
pub fn mbox_hw_status(&self) -> ureg::RegRef<crate::mcu_mbox0::meta::MboxHwStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200024 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct MboxCmdStatusReadVal(u32);
impl MboxCmdStatusReadVal {
/// Indicates the status of mailbox command.
#[inline(always)]
pub fn status(&self) -> super::enums::MboxStatusE {
super::enums::MboxStatusE::try_from((self.0 >> 0) & 0xf).unwrap()
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxCmdStatusWriteVal {
MboxCmdStatusWriteVal(self.0)
}
}
impl From<u32> for MboxCmdStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxCmdStatusReadVal> for u32 {
#[inline(always)]
fn from(val: MboxCmdStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxCmdStatusWriteVal(u32);
impl MboxCmdStatusWriteVal {
/// Indicates the status of mailbox command.
#[inline(always)]
pub fn status(
self,
f: impl FnOnce(super::enums::selector::MboxStatusESelector) -> super::enums::MboxStatusE,
) -> Self {
Self(
(self.0 & !(0xf << 0))
| (u32::from(f(super::enums::selector::MboxStatusESelector())) << 0),
)
}
}
impl From<u32> for MboxCmdStatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxCmdStatusWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxCmdStatusWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxExecuteReadVal(u32);
impl MboxExecuteReadVal {
#[inline(always)]
pub fn execute(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxExecuteWriteVal {
MboxExecuteWriteVal(self.0)
}
}
impl From<u32> for MboxExecuteReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxExecuteReadVal> for u32 {
#[inline(always)]
fn from(val: MboxExecuteReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxExecuteWriteVal(u32);
impl MboxExecuteWriteVal {
#[inline(always)]
pub fn execute(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for MboxExecuteWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxExecuteWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxExecuteWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxHwStatusReadVal(u32);
impl MboxHwStatusReadVal {
/// Indicates a correctable ECC single-bit error was
/// detected and corrected while reading dataout.
/// Auto-clears when mbox_execute field is cleared.
#[inline(always)]
pub fn ecc_single_error(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Indicates an uncorrectable ECC double-bit error
/// was detected while reading dataout.
/// Firmware developers are advised to set the command
/// status to CMD_FAILURE in response.
/// Auto-clears when mbox_execute field is cleared.
#[inline(always)]
pub fn ecc_double_error(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for MboxHwStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxHwStatusReadVal> for u32 {
#[inline(always)]
fn from(val: MboxHwStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxLockReadVal(u32);
impl MboxLockReadVal {
#[inline(always)]
pub fn lock(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
}
impl From<u32> for MboxLockReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxLockReadVal> for u32 {
#[inline(always)]
fn from(val: MboxLockReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetStatusReadVal(u32);
impl MboxTargetStatusReadVal {
/// Indicates the status of mailbox for the target user. Valid when done is set.
#[inline(always)]
pub fn status(&self) -> super::enums::MboxStatusE {
super::enums::MboxStatusE::try_from((self.0 >> 0) & 0xf).unwrap()
}
/// Indicates target user is done and target status is valid.
#[inline(always)]
pub fn done(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxTargetStatusWriteVal {
MboxTargetStatusWriteVal(self.0)
}
}
impl From<u32> for MboxTargetStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetStatusReadVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetStatusWriteVal(u32);
impl MboxTargetStatusWriteVal {
/// Indicates the status of mailbox for the target user. Valid when done is set.
#[inline(always)]
pub fn status(
self,
f: impl FnOnce(super::enums::selector::MboxStatusESelector) -> super::enums::MboxStatusE,
) -> Self {
Self(
(self.0 & !(0xf << 0))
| (u32::from(f(super::enums::selector::MboxStatusESelector())) << 0),
)
}
/// Indicates target user is done and target status is valid.
#[inline(always)]
pub fn done(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
}
impl From<u32> for MboxTargetStatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetStatusWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetStatusWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetUserValidReadVal(u32);
impl MboxTargetUserValidReadVal {
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxTargetUserValidWriteVal {
MboxTargetUserValidWriteVal(self.0)
}
}
impl From<u32> for MboxTargetUserValidReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetUserValidReadVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetUserValidReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetUserValidWriteVal(u32);
impl MboxTargetUserValidWriteVal {
#[inline(always)]
pub fn valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for MboxTargetUserValidWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetUserValidWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetUserValidWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u32)]
pub enum MboxStatusE {
CmdBusy = 0,
DataReady = 1,
CmdComplete = 2,
CmdFailure = 3,
Reserved4 = 4,
Reserved5 = 5,
Reserved6 = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Reserved10 = 10,
Reserved11 = 11,
Reserved12 = 12,
Reserved13 = 13,
Reserved14 = 14,
Reserved15 = 15,
}
impl MboxStatusE {
#[inline(always)]
pub fn cmd_busy(&self) -> bool {
*self == Self::CmdBusy
}
#[inline(always)]
pub fn data_ready(&self) -> bool {
*self == Self::DataReady
}
#[inline(always)]
pub fn cmd_complete(&self) -> bool {
*self == Self::CmdComplete
}
#[inline(always)]
pub fn cmd_failure(&self) -> bool {
*self == Self::CmdFailure
}
}
impl TryFrom<u32> for MboxStatusE {
type Error = ();
#[inline(always)]
fn try_from(val: u32) -> Result<MboxStatusE, ()> {
if val < 0x10 {
Ok(unsafe { core::mem::transmute::<u32, MboxStatusE>(val) })
} else {
Err(())
}
}
}
impl From<MboxStatusE> for u32 {
fn from(val: MboxStatusE) -> Self {
val as u32
}
}
pub mod selector {
pub struct MboxStatusESelector();
impl MboxStatusESelector {
#[inline(always)]
pub fn cmd_busy(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdBusy
}
#[inline(always)]
pub fn data_ready(&self) -> super::MboxStatusE {
super::MboxStatusE::DataReady
}
#[inline(always)]
pub fn cmd_complete(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdComplete
}
#[inline(always)]
pub fn cmd_failure(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdFailure
}
}
}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type MboxSram = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxLock = ureg::ReadOnlyReg32<crate::mcu_mbox0::regs::MboxLockReadVal>;
pub type MboxUser = ureg::ReadOnlyReg32<u32>;
pub type MboxTargetUser = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxTargetUserValid = ureg::ReadWriteReg32<
0,
crate::mcu_mbox0::regs::MboxTargetUserValidReadVal,
crate::mcu_mbox0::regs::MboxTargetUserValidWriteVal,
>;
pub type MboxCmd = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxDlen = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxExecute = ureg::ReadWriteReg32<
0,
crate::mcu_mbox0::regs::MboxExecuteReadVal,
crate::mcu_mbox0::regs::MboxExecuteWriteVal,
>;
pub type MboxTargetStatus = ureg::ReadWriteReg32<
0,
crate::mcu_mbox0::regs::MboxTargetStatusReadVal,
crate::mcu_mbox0::regs::MboxTargetStatusWriteVal,
>;
pub type MboxCmdStatus = ureg::ReadWriteReg32<
0,
crate::mcu_mbox0::regs::MboxCmdStatusReadVal,
crate::mcu_mbox0::regs::MboxCmdStatusWriteVal,
>;
pub type MboxHwStatus = ureg::ReadOnlyReg32<crate::mcu_mbox0::regs::MboxHwStatusReadVal>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/soc_ifc.rs | hw/latest/registers/src/soc_ifc.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct SocIfcReg {
_priv: (),
}
impl SocIfcReg {
pub const PTR: *mut u32 = 0x30030000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Indicates fatal hardware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// cptra_error_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, clearing
/// the bit in this register will not cause the interrupt to deassert.
/// Only a Caliptra reset will clear the fatal error interrupt.
/// [br]Caliptra Access: RW1C
/// [br]SOC Access: RW1C
///
/// Read value: [`soc_ifc::regs::CptraHwErrorFatalReadVal`]; Write value: [`soc_ifc::regs::CptraHwErrorFatalWriteVal`]
#[inline(always)]
pub fn cptra_hw_error_fatal(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraHwErrorFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates non-fatal hardware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// cptra_error_non_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, any
/// change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the cptra_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] CPTRA_HW_ERROR_NON_FATAL
/// [br] [*] CPTRA_FW_ERROR_NON_FATAL
/// [br] [*] internal_hw_error_non_fatal_mask
/// [br] [*] internal_fw_error_non_fatal_mask
/// [/list]
/// [br]Caliptra Access: RW1C
/// [br]SOC Access: RW1C
///
/// Read value: [`soc_ifc::regs::CptraHwErrorNonFatalReadVal`]; Write value: [`soc_ifc::regs::CptraHwErrorNonFatalWriteVal`]
#[inline(always)]
pub fn cptra_hw_error_non_fatal(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraHwErrorNonFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates fatal firmware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// cptra_error_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, clearing
/// the bit in this register will not cause the interrupt to deassert.
/// Only a Caliptra reset will clear the fatal error interrupt.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fw_error_fatal(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFwErrorFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates non-fatal firmware error. Assertion of any bit in this
/// register results in the assertion of the SoC interrupt pin,
/// cptra_error_non_fatal, unless that bit is masked using the internal
/// mask register. After the output interrupt is asserted, any
/// change by firmware that results in all set non-fatal errors
/// being masked will immediately deassert the interrupt output. This means
/// that firmware may cause the cptra_error_non_fatal signal to deassert by
/// writing to any of these registers, if the write results in all error
/// bits being cleared or masked:
/// [br][list]
/// [br] [*] CPTRA_HW_ERROR_NON_FATAL
/// [br] [*] CPTRA_FW_ERROR_NON_FATAL
/// [br] [*] internal_hw_error_non_fatal_mask
/// [br] [*] internal_fw_error_non_fatal_mask
/// [/list]
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fw_error_non_fatal(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFwErrorNonFatal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Encoded error value for hardware errors.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_hw_error_enc(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraHwErrorEnc, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Encoded error value for firmware errors.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fw_error_enc(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFwErrorEnc, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Firmware Extended Error information for firmware errors.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fw_extended_error_info(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::soc_ifc::meta::CptraFwExtendedErrorInfo, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the boot status.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_boot_status(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraBootStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the status of the firmware flows.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraFlowStatusReadVal`]; Write value: [`soc_ifc::regs::CptraFlowStatusWriteVal`]
#[inline(always)]
pub fn cptra_flow_status(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraFlowStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates to ROM the originating cause for the PC to be reset to 0.
/// Only reset during cold-boot (sticky).
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraResetReasonReadVal`]; Write value: [`soc_ifc::regs::CptraResetReasonWriteVal`]
#[inline(always)]
pub fn cptra_reset_reason(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraResetReason, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates current hardware security state.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraSecurityStateReadVal`]; Write value: [`soc_ifc::regs::CptraSecurityStateWriteVal`]
#[inline(always)]
pub fn cptra_security_state(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraSecurityState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Valid AXI USER attributes for requests from SoC AXI Interface. Only valid once LOCK is set.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// Read-Only once locked by AXI_USER_LOCK.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_mbox_valid_axi_user(
&self,
) -> ureg::Array<5, ureg::RegRef<crate::soc_ifc::meta::CptraMboxValidAxiUser, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x48 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Valid AXI_USER attributes for requests from SoC AXI Interface.
/// [br]Each bit corresponds to locking the associated MBOX_VALID_AXI_USER register.
/// [br]Associated MBOX_VALID_AXI_USER register is only valid once locked by this bit.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]Read-Only once locked.
///
/// Read value: [`soc_ifc::regs::CptraXxxxAxiUserLockReadVal`]; Write value: [`soc_ifc::regs::CptraXxxxAxiUserLockWriteVal`]
#[inline(always)]
pub fn cptra_mbox_axi_user_lock(
&self,
) -> ureg::Array<5, ureg::RegRef<crate::soc_ifc::meta::CptraMboxAxiUserLock, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Valid AXI USER attributes for TRNG on SoC AXI Interface. Only valid once LOCK is set.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]Read-Only once locked by TRNG_AXI_USER_LOCK.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_trng_valid_axi_user(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraTrngValidAxiUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x70 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Valid AXI USER attributes for requests from SoC AXI Interface.
/// [br]Each bit corresponds to locking the associated TRNG_VALID_AXI_USER register.
/// [br]Associated TRNG_VALID_AXI_USER register is only valid once locked by this bit.
/// [br]Caliptra FW RW access for survivability but cannot unlock once locked
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]Read-Only once locked.
///
/// Read value: [`soc_ifc::regs::CptraXxxxAxiUserLockReadVal`]; Write value: [`soc_ifc::regs::CptraXxxxAxiUserLockWriteVal`]
#[inline(always)]
pub fn cptra_trng_axi_user_lock(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraTrngAxiUserLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x74 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// TRNG Control register to clear data registers
///
/// Read value: [`soc_ifc::regs::CptraTrngCtrlReadVal`]; Write value: [`soc_ifc::regs::CptraTrngCtrlWriteVal`]
#[inline(always)]
pub fn cptra_trng_ctrl(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraTrngCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Writes to fuse registers are completed. After the done bit is set, any subsequent writes to a fuse register will be dropped unless there is a power cycle.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RW1-S
///
/// Read value: [`soc_ifc::regs::CptraFuseWrDoneReadVal`]; Write value: [`soc_ifc::regs::CptraFuseWrDoneWriteVal`]
#[inline(always)]
pub fn cptra_fuse_wr_done(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFuseWrDone, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides the clock period of the system clock.
/// Used to standardize the RISC-V Standard MTIME count register.
/// Clock Period is indicated as an integer number of picoseconds.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_timer_config(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraTimerConfig, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Indicates that the BootFSM can continue to execute to bring the uController out of reset
/// [br]Caliptra Access: RO
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RW
///
/// Read value: [`soc_ifc::regs::CptraBootfsmGoReadVal`]; Write value: [`soc_ifc::regs::CptraBootfsmGoWriteVal`]
#[inline(always)]
pub fn cptra_bootfsm_go(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraBootfsmGo, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// JTAG in debug/manuf mode or SOC can write to this register for ROM/FW defined skips or services; ROM/FW maintains the defintion of these bits.
/// [br]
/// [br]Field decode:
/// [br] [lb]0[rb] MFG_FLAG_GEN_IDEV_CSR: Enable bit for Caliptra to generate an IDEV CSR
/// [br] [lb]1[rb] MFG_FLAG_RNG_UNAVAIL: Random Number Generator Unavailable
/// [br] [lb]15:2[rb] MFG_FLAG_RSVD
/// [br] [lb]29:16[rb] FAKE_ROM_RSVD
/// [br] [lb]30[rb] FAKE_ROM_PROD_MODE_EN: Enable bit to allow the fake-rom to run in the production lifecycle mode
/// [br] [lb]31[rb] FAKE_ROM_IMAGE_VERIFY_EN: Enable bit to perform image verification within the fake-rom feature
/// [br]
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_dbg_manuf_service_reg(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraDbgManufServiceReg, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xbc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Control register to enable or disable all of the caliptra clk gating. Default is 0 (disabled).
/// [br]Caliptra Access: RO
/// [br]SOC Access: RW
///
/// Read value: [`soc_ifc::regs::CptraClkGatingEnReadVal`]; Write value: [`soc_ifc::regs::CptraClkGatingEnWriteVal`]
#[inline(always)]
pub fn cptra_clk_gating_en(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraClkGatingEn, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Generic input wires connected to SoC interface.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_generic_input_wires(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraGenericInputWires, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xc4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Generic output wires connected to SoC interface.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_generic_output_wires(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraGenericOutputWires, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xcc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra HW revision ID that matches the official final release milestone
/// SoC stepping ID is repopulated with the value in the fuse register on every warm reset
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraHwRevIdReadVal`]; Write value: [`soc_ifc::regs::CptraHwRevIdWriteVal`]
#[inline(always)]
pub fn cptra_hw_rev_id(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraHwRevId, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xd4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra FW revision ID
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fw_rev_id(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraFwRevId, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xd8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra HW Configuration
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraHwConfigReadVal`]; Write value: [`soc_ifc::regs::CptraHwConfigWriteVal`]
#[inline(always)]
pub fn cptra_hw_config(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraHwConfig, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xe0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer1 enable register
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraWdtTimer1EnReadVal`]; Write value: [`soc_ifc::regs::CptraWdtTimer1EnWriteVal`]
#[inline(always)]
pub fn cptra_wdt_timer1_en(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraWdtTimer1En, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xe4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer1 control register
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraWdtTimer1CtrlReadVal`]; Write value: [`soc_ifc::regs::CptraWdtTimer1CtrlWriteVal`]
#[inline(always)]
pub fn cptra_wdt_timer1_ctrl(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraWdtTimer1Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xe8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer1 timeout register
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_wdt_timer1_timeout_period(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraWdtTimer1TimeoutPeriod, &TMmio>>
{
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xec / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer2 enable register. Note: Setting this to 1 will disable the default cascaded mode and will have both timers count independently.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraWdtTimer2EnReadVal`]; Write value: [`soc_ifc::regs::CptraWdtTimer2EnWriteVal`]
#[inline(always)]
pub fn cptra_wdt_timer2_en(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraWdtTimer2En, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xf4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer2 control register
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraWdtTimer2CtrlReadVal`]; Write value: [`soc_ifc::regs::CptraWdtTimer2CtrlWriteVal`]
#[inline(always)]
pub fn cptra_wdt_timer2_ctrl(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraWdtTimer2Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xf8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer2 timeout register
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_wdt_timer2_timeout_period(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraWdtTimer2TimeoutPeriod, &TMmio>>
{
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xfc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra watchdog timer status register
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`soc_ifc::regs::CptraWdtStatusReadVal`]; Write value: [`soc_ifc::regs::CptraWdtStatusWriteVal`]
#[inline(always)]
pub fn cptra_wdt_status(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraWdtStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Valid AXI USER attributes for FUSE on SoC AXI Interface. Only valid once LOCK is set.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]Read-Only once locked by FUSE_AXI_USER_LOCK.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fuse_valid_axi_user(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFuseValidAxiUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Valid AXI_USER attributes for requests from SoC AXI Interface.
/// [br]Each bit corresponds to locking the associated FUSE_VALID_AXI_USER register.
/// [br]Associated FUSE_VALID_AXI_USER register is only valid once locked by this bit.
/// [br]Caliptra FW RW access for survivability but cannot unlock once locked
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]Read-Only once locked.
///
/// Read value: [`soc_ifc::regs::CptraXxxxAxiUserLockReadVal`]; Write value: [`soc_ifc::regs::CptraXxxxAxiUserLockWriteVal`]
#[inline(always)]
pub fn cptra_fuse_axi_user_lock(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFuseAxiUserLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SOC provided count in cycles for WDT1 timeout.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_wdt_cfg(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraWdtCfg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x110 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Adaptive threshold values for entropy source health tests.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`soc_ifc::regs::CptraItrngEntropyConfig0ReadVal`]; Write value: [`soc_ifc::regs::CptraItrngEntropyConfig0WriteVal`]
#[inline(always)]
pub fn cptra_i_trng_entropy_config_0(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraItrngEntropyConfig0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x118 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Repetition count value for entropy source health tests.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`soc_ifc::regs::CptraItrngEntropyConfig1ReadVal`]; Write value: [`soc_ifc::regs::CptraItrngEntropyConfig1WriteVal`]
#[inline(always)]
pub fn cptra_i_trng_entropy_config_1(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraItrngEntropyConfig1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x11c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Set of reserved registers for survivability
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_rsvd_reg(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::soc_ifc::meta::CptraRsvdReg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x120 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra HW Capabilities. Initialized with reset values, rewritable by Caliptra firmware.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
/// [br]Read-only once locked.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_hw_capabilities(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraHwCapabilities, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x128 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Caliptra FW Capabilities. Initialized with reset values, rewritable by Caliptra firmware.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
/// [br]Read-only once locked.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_fw_capabilities(
&self,
) -> ureg::RegRef<crate::soc_ifc::meta::CptraFwCapabilities, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x12c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Lock register to disable further firmware modifications to capabilities registers.
/// [br]Once set, this register may not be cleared until a warm reset. If set, the values in CPTRA_HW_CAPABILITIES and CPTRA_FW_CAPABILITIES may not be modified.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
/// [br]Read-only once locked.
///
/// Read value: [`soc_ifc::regs::CptraXxxxxxxkReadVal`]; Write value: [`soc_ifc::regs::CptraXxxxxxxkWriteVal`]
#[inline(always)]
pub fn cptra_cap_lock(&self) -> ureg::RegRef<crate::soc_ifc::meta::CptraCapLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x130 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Owner PK hash lockable register.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RWL-S
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cptra_owner_pk_hash(
&self,
) -> ureg::Array<12, ureg::RegRef<crate::soc_ifc::meta::CptraOwnerPkHash, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x140 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/el2_pic_ctrl.rs | hw/latest/registers/src/el2_pic_ctrl.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct El2PicCtrl {
_priv: (),
}
impl El2PicCtrl {
pub const PTR: *mut u32 = 0x60000000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// There are 255 priority level registers, one for each external
/// interrupt source. Implementing individual priority level
/// registers allows a debugger to autonomously discover how many
/// priority level bits are supported for this interrupt source.
/// Firmware must initialize the priority level for each used
/// interrupt source. Firmware may also read the priority level.
///
/// Read value: [`el2_pic_ctrl::regs::MeiplReadVal`]; Write value: [`el2_pic_ctrl::regs::MeiplWriteVal`]
#[inline(always)]
pub fn meipl(
&self,
) -> ureg::Array<256, ureg::RegRef<crate::el2_pic_ctrl::meta::Meipl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Eight external interrupt pending registers are needed to
/// report the current status of up to 255 independent external
/// interrupt sources. Each bit of these registers corresponds
/// to an interrupt pending indication of a single external
/// interrupt source. These registers only provide the status
/// of pending interrupts and cannot be written.
///
/// Read value: [`el2_pic_ctrl::regs::MeipReadVal`]; Write value: [`el2_pic_ctrl::regs::MeipWriteVal`]
#[inline(always)]
pub fn meip(&self) -> ureg::Array<256, ureg::RegRef<crate::el2_pic_ctrl::meta::Meip, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x1000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Each of the up to 255 independently controlled external
/// interrupt sources has a dedicated interrupt enable register.
/// Separate registers per interrupt source were chosen for
/// ease-of-use and compatibility with existing controllers.
///
/// Read value: [`el2_pic_ctrl::regs::MeieReadVal`]; Write value: [`el2_pic_ctrl::regs::MeieWriteVal`]
#[inline(always)]
pub fn meie(&self) -> ureg::Array<256, ureg::RegRef<crate::el2_pic_ctrl::meta::Meie, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x2000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// The PIC configuration register is used to select the operational
/// parameters of the PIC.
///
/// Read value: [`el2_pic_ctrl::regs::MpiccfgReadVal`]; Write value: [`el2_pic_ctrl::regs::MpiccfgWriteVal`]
#[inline(always)]
pub fn mpiccfg(&self) -> ureg::RegRef<crate::el2_pic_ctrl::meta::Mpiccfg, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Each configurable gateway has a dedicated configuration register
/// to control the interrupt type (i.e., edge- vs. level-triggered)
/// as well as the interrupt signal polarity (i.e., low-to-high vs.
/// high-to-low transition for edge-triggered interrupts, active-high
/// vs. -low for level-triggered interrupts).
///
/// Read value: [`el2_pic_ctrl::regs::MeigwctrlReadVal`]; Write value: [`el2_pic_ctrl::regs::MeigwctrlWriteVal`]
#[inline(always)]
pub fn meigwctrl(
&self,
) -> ureg::Array<256, ureg::RegRef<crate::el2_pic_ctrl::meta::Meigwctrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x4000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Each configurable gateway has a dedicated clear register
/// to reset its interrupt pending (IP) bit. For edge-triggered
/// interrupts, firmware must clear the gateway’s IP bit while
/// servicing the external interrupt of source ID S by writing to
/// the meigwclrS register.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn meigwclr(
&self,
) -> ureg::Array<256, ureg::RegRef<crate::el2_pic_ctrl::meta::Meigwclr, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x5000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct MeieReadVal(u32);
impl MeieReadVal {
/// External interrupt enable
#[inline(always)]
pub fn inten(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MeieWriteVal {
MeieWriteVal(self.0)
}
}
impl From<u32> for MeieReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeieReadVal> for u32 {
#[inline(always)]
fn from(val: MeieReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MeieWriteVal(u32);
impl MeieWriteVal {
/// External interrupt enable
#[inline(always)]
pub fn inten(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for MeieWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeieWriteVal> for u32 {
#[inline(always)]
fn from(val: MeieWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MeigwctrlReadVal(u32);
impl MeigwctrlReadVal {
/// External interrupt polarity
/// 0b0: Active-high interrupt
/// 0b1: Active-low interrupt
#[inline(always)]
pub fn polarity(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// External interrupt type
/// 0b0: Level-triggered interrupt
/// 0b1: Edge-triggered interrupt
#[inline(always)]
pub fn inttype(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MeigwctrlWriteVal {
MeigwctrlWriteVal(self.0)
}
}
impl From<u32> for MeigwctrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeigwctrlReadVal> for u32 {
#[inline(always)]
fn from(val: MeigwctrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MeigwctrlWriteVal(u32);
impl MeigwctrlWriteVal {
/// External interrupt polarity
/// 0b0: Active-high interrupt
/// 0b1: Active-low interrupt
#[inline(always)]
pub fn polarity(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// External interrupt type
/// 0b0: Level-triggered interrupt
/// 0b1: Edge-triggered interrupt
#[inline(always)]
pub fn inttype(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for MeigwctrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeigwctrlWriteVal> for u32 {
#[inline(always)]
fn from(val: MeigwctrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MeipReadVal(u32);
impl MeipReadVal {
/// External interrupt pending
#[inline(always)]
pub fn intpend(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
}
impl From<u32> for MeipReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeipReadVal> for u32 {
#[inline(always)]
fn from(val: MeipReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MeiplReadVal(u32);
impl MeiplReadVal {
/// External interrupt priority level
#[inline(always)]
pub fn priority(&self) -> u32 {
(self.0 >> 0) & 0xf
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MeiplWriteVal {
MeiplWriteVal(self.0)
}
}
impl From<u32> for MeiplReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeiplReadVal> for u32 {
#[inline(always)]
fn from(val: MeiplReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MeiplWriteVal(u32);
impl MeiplWriteVal {
/// External interrupt priority level
#[inline(always)]
pub fn priority(self, val: u32) -> Self {
Self((self.0 & !(0xf << 0)) | ((val & 0xf) << 0))
}
}
impl From<u32> for MeiplWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MeiplWriteVal> for u32 {
#[inline(always)]
fn from(val: MeiplWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MpiccfgReadVal(u32);
impl MpiccfgReadVal {
/// Interrupt priority order
/// 0b0: RISC-V standard compliant priority order (0=lowest to 15=highest)
/// 0b1: Reverse priority order (15=lowest to 0=highest)
#[inline(always)]
pub fn priord(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MpiccfgWriteVal {
MpiccfgWriteVal(self.0)
}
}
impl From<u32> for MpiccfgReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MpiccfgReadVal> for u32 {
#[inline(always)]
fn from(val: MpiccfgReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MpiccfgWriteVal(u32);
impl MpiccfgWriteVal {
/// Interrupt priority order
/// 0b0: RISC-V standard compliant priority order (0=lowest to 15=highest)
/// 0b1: Reverse priority order (15=lowest to 0=highest)
#[inline(always)]
pub fn priord(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for MpiccfgWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MpiccfgWriteVal> for u32 {
#[inline(always)]
fn from(val: MpiccfgWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type Meipl = ureg::ReadWriteReg32<
0,
crate::el2_pic_ctrl::regs::MeiplReadVal,
crate::el2_pic_ctrl::regs::MeiplWriteVal,
>;
pub type Meip = ureg::ReadOnlyReg32<crate::el2_pic_ctrl::regs::MeipReadVal>;
pub type Meie = ureg::ReadWriteReg32<
0,
crate::el2_pic_ctrl::regs::MeieReadVal,
crate::el2_pic_ctrl::regs::MeieWriteVal,
>;
pub type Mpiccfg = ureg::ReadWriteReg32<
0,
crate::el2_pic_ctrl::regs::MpiccfgReadVal,
crate::el2_pic_ctrl::regs::MpiccfgWriteVal,
>;
pub type Meigwctrl = ureg::ReadWriteReg32<
0,
crate::el2_pic_ctrl::regs::MeigwctrlReadVal,
crate::el2_pic_ctrl::regs::MeigwctrlWriteVal,
>;
pub type Meigwclr = ureg::ReadWriteReg32<0, u32, u32>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/sha3.rs | hw/latest/registers/src/sha3.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct Sha3 {
_priv: (),
}
impl Sha3 {
pub const PTR: *mut u32 = 0x10041000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing the name
/// of SHA3 component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn name(&self) -> ureg::Array<2, ureg::RegRef<crate::sha3::meta::Name, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing the version
/// of SHA3/SHAKE component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn version(&self) -> ureg::Array<2, ureg::RegRef<crate::sha3::meta::Version, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`sha3::regs::AlertTestReadVal`]; Write value: [`sha3::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::sha3::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the configurability of CFG_SHADOWED register.
/// This register ensures the contents of CFG_SHADOWED register cannot be changed by the
/// software while the SHA3 is in operation mode.
///
/// Read value: [`sha3::regs::CfgRegwenReadVal`]; Write value: [`sha3::regs::CfgRegwenWriteVal`]
#[inline(always)]
pub fn cfg_regwen(&self) -> ureg::RegRef<crate::sha3::meta::CfgRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register is shadowed and protected by CFG_REGWEN.en.
/// This register is updated when the hashing engine is in Idle.
/// If the software updates the register while the engine computes, the updated value will be discarded.
/// Two subsequent write operation are required to change its content,
/// If the two write operations try to set a different value, a recoverable alert is triggered (See Status Register).
/// A read operation clears the internal phase tracking.
/// If storage error(~staged_reg!=committed_reg) happen, it will trigger fatal fault alert.
///
/// Read value: [`sha3::regs::CfgShadowedReadVal`]; Write value: [`sha3::regs::CfgShadowedWriteVal`]
#[inline(always)]
pub fn cfg_shadowed(&self) -> ureg::RegRef<crate::sha3::meta::CfgShadowed, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register is to control the SHA3 component to start accepting message,
/// to process the message, and to manually run additional Keccak rounds at the end.
/// Only at certain stage, the CMD affects to the control logic. It follows the sequence of
/// start -> process -> (run if needed ->) done
///
/// Read value: [`sha3::regs::CmdReadVal`]; Write value: [`sha3::regs::CmdWriteVal`]
#[inline(always)]
pub fn cmd(&self) -> ureg::RegRef<crate::sha3::meta::Cmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`sha3::regs::StatusReadVal`]; Write value: [`sha3::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::sha3::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA3 Error Code
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn err_code(&self) -> ureg::RegRef<crate::sha3::meta::ErrCode, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xd0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Keccak State (1600 bit) memory.
/// The software can get the processed digest by reading this memory region.
/// Unlike MSG_FIFO, STATE memory space sees the addr[9:0].
///
/// 1. Output length <= rate length, sha3_done will be raised or software can poll STATUS.squeeze become 1.
/// 2. Output length > rate length, after software read 1st keccak state, software should issue run cmd to trigger keccak round logic to run full 24 rounds.
/// And then software should check STATUS.squeeze register field for the readiness of STATE value(SHA3 FSM become MANUAL_RUN before keccak state complete).
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn state(&self) -> ureg::Array<64, ureg::RegRef<crate::sha3::meta::State, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Message FIFO. window size is 2048 bytes.
/// Any write operation to this window will be appended to MSG_FIFO.
/// Software can simply write bytes/words to any address within this address range.
/// Ordering and packing of the incoming bytes/words are handled internally.
/// Therefore, the least significant 12 bits of the address are ignored.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn msg_fifo(&self) -> ureg::Array<64, ureg::RegRef<crate::sha3::meta::MsgFifo, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xc00 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x400 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha3::regs::ErrorIntrEnTReadVal`]; Write value: [`sha3::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha3::regs::NotifIntrEnTReadVal`]; Write value: [`sha3::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Non-sticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Non-sticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
/// SHA3 error occurred. ERR_CODE register shows the details
///
/// Read value: [`sha3::regs::ErrorIntrTReadVal`]; Write value: [`sha3::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha3::regs::NotifIntrTReadVal`]; Write value: [`sha3::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha3::regs::ErrorIntrTrigTReadVal`]; Write value: [`sha3::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha3::regs::NotifIntrTrigTReadVal`]; Write value: [`sha3::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn sha3_error_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfSha3ErrorIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error1_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfError1IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn sha3_error_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfSha3ErrorIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error1_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfError1IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha3::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x400 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AlertTestWriteVal(u32);
impl AlertTestWriteVal {
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn recov_operation_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_fault_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for AlertTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AlertTestWriteVal> for u32 {
#[inline(always)]
fn from(val: AlertTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CfgRegwenReadVal(u32);
impl CfgRegwenReadVal {
/// Configuration enable.
#[inline(always)]
pub fn en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
}
impl From<u32> for CfgRegwenReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CfgRegwenReadVal> for u32 {
#[inline(always)]
fn from(val: CfgRegwenReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CfgShadowedReadVal(u32);
impl CfgShadowedReadVal {
/// Hashing Strength, Protected by CFG_REGWEN.en
/// bit field to select the security strength of SHA3 hashing engine.
/// If mode field is set to SHAKE or cSHAKE, only 128 and 256 strength can be selected.
/// Other value will result error when hashing starts.
#[inline(always)]
pub fn kstrength(&self) -> u32 {
(self.0 >> 1) & 7
}
/// Keccak hashing mode, Protected by CFG_REGWEN.en
/// This module supports SHA3 main hashing algorithm and the part of its derived functions,
/// SHAKE with limitations. This field is to select the mode.
#[inline(always)]
pub fn mode(&self) -> u32 {
(self.0 >> 4) & 3
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual multi-byte value, regardless of its alignment,
/// written to MSG_FIFO will be added to the message in big-endian byte order.
/// If 0, each value will be added to the message in little-endian byte order.
/// A message written to MSG_FIFO one byte at a time will not be affected by this setting.
/// From a hardware perspective byte swaps are performed on a bus word granularity.
#[inline(always)]
pub fn msg_endianness(&self) -> bool {
((self.0 >> 8) & 1) != 0
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual word in the STATE output register is converted to big-endian byte order.
/// The order of the words in relation to one another is not changed.
/// This setting does not affect how the state is interpreted during computation.
#[inline(always)]
pub fn state_endianness(&self) -> bool {
((self.0 >> 9) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CfgShadowedWriteVal {
CfgShadowedWriteVal(self.0)
}
}
impl From<u32> for CfgShadowedReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CfgShadowedReadVal> for u32 {
#[inline(always)]
fn from(val: CfgShadowedReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CfgShadowedWriteVal(u32);
impl CfgShadowedWriteVal {
/// Hashing Strength, Protected by CFG_REGWEN.en
/// bit field to select the security strength of SHA3 hashing engine.
/// If mode field is set to SHAKE or cSHAKE, only 128 and 256 strength can be selected.
/// Other value will result error when hashing starts.
#[inline(always)]
pub fn kstrength(self, val: u32) -> Self {
Self((self.0 & !(7 << 1)) | ((val & 7) << 1))
}
/// Keccak hashing mode, Protected by CFG_REGWEN.en
/// This module supports SHA3 main hashing algorithm and the part of its derived functions,
/// SHAKE with limitations. This field is to select the mode.
#[inline(always)]
pub fn mode(self, val: u32) -> Self {
Self((self.0 & !(3 << 4)) | ((val & 3) << 4))
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual multi-byte value, regardless of its alignment,
/// written to MSG_FIFO will be added to the message in big-endian byte order.
/// If 0, each value will be added to the message in little-endian byte order.
/// A message written to MSG_FIFO one byte at a time will not be affected by this setting.
/// From a hardware perspective byte swaps are performed on a bus word granularity.
#[inline(always)]
pub fn msg_endianness(self, val: bool) -> Self {
Self((self.0 & !(1 << 8)) | (u32::from(val) << 8))
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual word in the STATE output register is converted to big-endian byte order.
/// The order of the words in relation to one another is not changed.
/// This setting does not affect how the state is interpreted during computation.
#[inline(always)]
pub fn state_endianness(self, val: bool) -> Self {
Self((self.0 & !(1 << 9)) | (u32::from(val) << 9))
}
}
impl From<u32> for CfgShadowedWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CfgShadowedWriteVal> for u32 {
#[inline(always)]
fn from(val: CfgShadowedWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CmdReadVal(u32);
impl CmdReadVal {
/// Issues a command to the SHA3 IP. The command is sparse encoded.
/// To prevent sw from writing multiple commands at once, the field is defined as enum.
/// Always return 0 for SW reads.
/// START: Writing 6'b011101 or dec 29 into this field when SHA3/SHAKE is in idle, SHA3/SHAKE begins its operation and start absorbing.
/// PROCESS: Writing 6'b101110 or dec 46 into this field when SHA3/SHAKE began its operation and received the entire message, it computes the digest or signing.
/// RUN: The run field is used in the sponge squeezing stage.
/// It triggers the keccak round logic to run full 24 rounds.
/// This is optional and used when software needs more digest bits than the Keccak rate.
/// It only affects when the SHA3/SHAKE operation is completed.
/// DONE: Writing 6'b010110 or dec 22 into this field when SHA3 squeezing is completed,
/// SHA3/SHAKE hashing engine clears internal variables and goes back to Idle state for next command.
#[inline(always)]
pub fn cmd(&self) -> u32 {
(self.0 >> 0) & 0x3f
}
/// When error occurs and one of the state machine stays at Error handling state,
/// SW may process the error based on ERR_CODE, then let FSM back to the reset state.
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/aes_clp.rs | hw/latest/registers/src/aes_clp.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct AesClpReg {
_priv: (),
}
impl AesClpReg {
pub const PTR: *mut u32 = 0x10011800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing of the name
/// of AES component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn aes_name(&self) -> ureg::Array<2, ureg::RegRef<crate::aes_clp::meta::AesName, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of AES component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn aes_version(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::aes_clp::meta::AesVersion, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Nine 32-bit write-only registers for providing a new 288-bit state seed for the
/// Trivium stream cipher primitive driving the EDN interface of AES.
///
/// After reset and whenever firmware wants to reseed the Trivium stream cipher
/// primitive, it has to write every register once. The order in which the registers
/// are written doesn't matter. Upon writing the last register, the provided 288-bit
/// value is loaded into the Trivium primitive.
///
/// It's fine to write the registers while AES is busy and even while it's performing a
/// a reseed operation of the internal PRNGs via the EDN interface.
///
/// Note: Upon reset, the state of the Trivium primitive is initialized to a netlist
/// constant. The primitive thus always generates the same output after reset. It is the
/// responsibility of firmware to provide a new state seed after reset.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn entropy_if_seed(
&self,
) -> ureg::Array<9, ureg::RegRef<crate::aes_clp::meta::EntropyIfSeed, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x110 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// AES Wrapper Controls
///
/// Read value: [`aes_clp::regs::Ctrl0ReadVal`]; Write value: [`aes_clp::regs::Ctrl0WriteVal`]
#[inline(always)]
pub fn ctrl0(&self) -> ureg::RegRef<crate::aes_clp::meta::Ctrl0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x134 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn aes_kv_rd_key_ctrl(&self) -> ureg::RegRef<crate::aes_clp::meta::AesKvRdKeyCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn aes_kv_rd_key_status(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::AesKvRdKeyStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault write access for this engine
///
/// Read value: [`regs::KvWriteCtrlRegReadVal`]; Write value: [`regs::KvWriteCtrlRegWriteVal`]
#[inline(always)]
pub fn aes_kv_wr_ctrl(&self) -> ureg::RegRef<crate::aes_clp::meta::AesKvWrCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn aes_kv_wr_status(&self) -> ureg::RegRef<crate::aes_clp::meta::AesKvWrStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x400 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::ErrorIntrEnTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::NotifIntrEnTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::NotifIntrTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::NotifIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error0_intr_count_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError0IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error1_intr_count_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError1IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error0_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError0IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error1_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError1IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::aes_clp::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x400 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct Ctrl0ReadVal(u32);
impl Ctrl0ReadVal {
/// Default behavior assumes that data written into and read out of AES is little endian.
/// [br]When set to 0, data written to AES and data read out of AES is left as is and is in little endian format.
/// [br]When set to 1, data written to AES DATAIN and data read from DATAOUT is big endian format. Since the AES core always assumes little endian format, this control swizzles write data to DATAIN from big endian to little endian format. When data is read from DATAOUT it swizzle the read data from little endian to big endian format. Allowing for the user to stream big endian data into and out of the AES.
#[inline(always)]
pub fn endian_swap(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> Ctrl0WriteVal {
Ctrl0WriteVal(self.0)
}
}
impl From<u32> for Ctrl0ReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<Ctrl0ReadVal> for u32 {
#[inline(always)]
fn from(val: Ctrl0ReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct Ctrl0WriteVal(u32);
impl Ctrl0WriteVal {
/// Default behavior assumes that data written into and read out of AES is little endian.
/// [br]When set to 0, data written to AES and data read out of AES is left as is and is in little endian format.
/// [br]When set to 1, data written to AES DATAIN and data read from DATAOUT is big endian format. Since the AES core always assumes little endian format, this control swizzles write data to DATAIN from big endian to little endian format. When data is read from DATAOUT it swizzle the read data from little endian to big endian format. Allowing for the user to stream big endian data into and out of the AES.
#[inline(always)]
pub fn endian_swap(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for Ctrl0WriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<Ctrl0WriteVal> for u32 {
#[inline(always)]
fn from(val: Ctrl0WriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrEnTWriteVal {
ErrorIntrEnTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTWriteVal(u32);
impl ErrorIntrEnTWriteVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrEnTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTReadVal(u32);
impl ErrorIntrTReadVal {
/// Interrupt Event 0 status bit
#[inline(always)]
pub fn error0_sts(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Event 1 status bit
#[inline(always)]
pub fn error1_sts(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTWriteVal {
ErrorIntrTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTWriteVal(u32);
impl ErrorIntrTWriteVal {
/// Interrupt Event 0 status bit
#[inline(always)]
pub fn error0_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Interrupt Event 1 status bit
#[inline(always)]
pub fn error1_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTrigTReadVal(u32);
impl ErrorIntrTrigTReadVal {
/// Interrupt Trigger 0 bit
#[inline(always)]
pub fn error0_trig(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Trigger 1 bit
#[inline(always)]
pub fn error1_trig(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Trigger 2 bit
#[inline(always)]
pub fn error2_trig(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Trigger 3 bit
#[inline(always)]
pub fn error3_trig(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTrigTWriteVal {
ErrorIntrTrigTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTrigTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTrigTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTrigTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTrigTWriteVal(u32);
impl ErrorIntrTrigTWriteVal {
/// Interrupt Trigger 0 bit
#[inline(always)]
pub fn error0_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Interrupt Trigger 1 bit
#[inline(always)]
pub fn error1_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/sha512.rs | hw/latest/registers/src/sha512.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct Sha512Reg {
_priv: (),
}
impl Sha512Reg {
pub const PTR: *mut u32 = 0x10020000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing of the name
/// of SHA512 component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn name(&self) -> ureg::Array<2, ureg::RegRef<crate::sha512::meta::Name, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of SHA512 component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn version(&self) -> ureg::Array<2, ureg::RegRef<crate::sha512::meta::Version, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA512 component control register type definition
///
/// Read value: [`sha512::regs::CtrlReadVal`]; Write value: [`sha512::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::sha512::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA512 component status register type definition
///
/// Read value: [`sha512::regs::StatusReadVal`]; Write value: [`sha512::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::sha512::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA512 component block register type definition
/// 32 32-bit registers storing the 1024-bit padded input in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn block(&self) -> ureg::Array<32, ureg::RegRef<crate::sha512::meta::Block, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA512 component digest register type definition
/// 16 32-bit registers storing the 512-bit digest output in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn digest(&self) -> ureg::Array<16, ureg::RegRef<crate::sha512::meta::Digest, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn vault_rd_ctrl(&self) -> ureg::RegRef<crate::sha512::meta::VaultRdCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x600 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn vault_rd_status(&self) -> ureg::RegRef<crate::sha512::meta::VaultRdStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x604 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault write access for this engine
///
/// Read value: [`regs::KvWriteCtrlRegReadVal`]; Write value: [`regs::KvWriteCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_wr_ctrl(&self) -> ureg::RegRef<crate::sha512::meta::KvWrCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x608 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_wr_status(&self) -> ureg::RegRef<crate::sha512::meta::KvWrStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Nonce for PCR Gen Hash Function
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn gen_pcr_hash_nonce(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::sha512::meta::GenPcrHashNonce, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x610 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Control register for PCR Gen Hash Function
///
/// Read value: [`sha512::regs::GenPcrHashCtrlReadVal`]; Write value: [`sha512::regs::GenPcrHashCtrlWriteVal`]
#[inline(always)]
pub fn gen_pcr_hash_ctrl(&self) -> ureg::RegRef<crate::sha512::meta::GenPcrHashCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x630 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status register for PCR Gen Hash Function
///
/// Read value: [`sha512::regs::GenPcrHashStatusReadVal`]; Write value: [`sha512::regs::GenPcrHashStatusWriteVal`]
#[inline(always)]
pub fn gen_pcr_hash_status(
&self,
) -> ureg::RegRef<crate::sha512::meta::GenPcrHashStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x634 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 16 32-bit registers storing the 512-bit digest output.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn gen_pcr_hash_digest(
&self,
) -> ureg::Array<16, ureg::RegRef<crate::sha512::meta::GenPcrHashDigest, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x638 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::ErrorIntrEnTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::NotifIntrEnTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::NotifIntrTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::NotifIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error0_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError0IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error1_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError1IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error0_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError0IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error1_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError1IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct CtrlWriteVal(u32);
impl CtrlWriteVal {
/// Control init command bit: Trigs the SHA512 core to start the
/// processing for the first padded message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn init(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Control next command bit: Trigs the SHA512 core to start the
/// processing for the remining padded message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn next(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Control mode command bits: Indicates the SHA512 core to set dynamically
/// the type of hashing algorithm. This can be:
/// 00 for SHA512/224
/// 01 for SHA512/256
/// 10 for SHA384
/// 11 for SHA512
#[inline(always)]
pub fn mode(self, val: u32) -> Self {
Self((self.0 & !(3 << 2)) | ((val & 3) << 2))
}
/// Zeroize all internal registers: Zeroize all internal registers after SHA process, to avoid SCA leakage.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn zeroize(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Indicates last iteration for keyvault or hash extend function.
/// Result of this INIT or NEXT cycle will be written back to the appropriate vault
#[inline(always)]
pub fn last(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
/// Control restore command bit: Restore SHA512 core to use the given digest to continue the
/// processing for the remining padded message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn restore(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
}
impl From<u32> for CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct GenPcrHashCtrlWriteVal(u32);
impl GenPcrHashCtrlWriteVal {
/// Command to start hash function
#[inline(always)]
pub fn start(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for GenPcrHashCtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<GenPcrHashCtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: GenPcrHashCtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct GenPcrHashStatusReadVal(u32);
impl GenPcrHashStatusReadVal {
/// Status ready bit
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Status valid bit
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for GenPcrHashStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<GenPcrHashStatusReadVal> for u32 {
#[inline(always)]
fn from(val: GenPcrHashStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Status ready bit: Indicates if the core is ready to take
/// a control command and process the block.
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Status valid bit: Indicates if the process is done and the
/// hash value stored in DIGEST registers is valid.
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrEnTWriteVal {
ErrorIntrEnTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTWriteVal(u32);
impl ErrorIntrEnTWriteVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Enable bit for Event 3
#[inline(always)]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/spi_host.rs | hw/latest/registers/src/spi_host.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 9f80a2bebb755233696929bf1da5ca0b90eba9a1
//
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct SpiHostReg {
_priv: (),
}
impl SpiHostReg {
pub const PTR: *mut u32 = 0x20000000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`spi_host::regs::InterruptStateReadVal`]; Write value: [`spi_host::regs::InterruptStateWriteVal`]
#[inline(always)]
pub fn interrupt_state(&self) -> ureg::RegRef<crate::spi_host::meta::InterruptState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::InterruptEnableReadVal`]; Write value: [`spi_host::regs::InterruptEnableWriteVal`]
#[inline(always)]
pub fn interrupt_enable(&self) -> ureg::RegRef<crate::spi_host::meta::InterruptEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::InterruptTestReadVal`]; Write value: [`spi_host::regs::InterruptTestWriteVal`]
#[inline(always)]
pub fn interrupt_test(&self) -> ureg::RegRef<crate::spi_host::meta::InterruptTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::AlertTestReadVal`]; Write value: [`spi_host::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::spi_host::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::ControlReadVal`]; Write value: [`spi_host::regs::ControlWriteVal`]
#[inline(always)]
pub fn control(&self) -> ureg::RegRef<crate::spi_host::meta::Control, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::StatusReadVal`]; Write value: [`spi_host::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::spi_host::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::ConfigoptsReadVal`]; Write value: [`spi_host::regs::ConfigoptsWriteVal`]
#[inline(always)]
pub fn configopts(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::spi_host::meta::Configopts, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn csid(&self) -> ureg::RegRef<crate::spi_host::meta::Csid, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::CommandReadVal`]; Write value: [`spi_host::regs::CommandWriteVal`]
#[inline(always)]
pub fn command(&self) -> ureg::RegRef<crate::spi_host::meta::Command, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn rxdata(&self) -> ureg::RegRef<crate::spi_host::meta::Rxdata, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn txdata(&self) -> ureg::RegRef<crate::spi_host::meta::Txdata, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::ErrorEnableReadVal`]; Write value: [`spi_host::regs::ErrorEnableWriteVal`]
#[inline(always)]
pub fn error_enable(&self) -> ureg::RegRef<crate::spi_host::meta::ErrorEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::ErrorStatusReadVal`]; Write value: [`spi_host::regs::ErrorStatusWriteVal`]
#[inline(always)]
pub fn error_status(&self) -> ureg::RegRef<crate::spi_host::meta::ErrorStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`spi_host::regs::EventEnableReadVal`]; Write value: [`spi_host::regs::EventEnableWriteVal`]
#[inline(always)]
pub fn event_enable(&self) -> ureg::RegRef<crate::spi_host::meta::EventEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AlertTestWriteVal(u32);
impl AlertTestWriteVal {
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_fault(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for AlertTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AlertTestWriteVal> for u32 {
#[inline(always)]
fn from(val: AlertTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CommandWriteVal(u32);
impl CommandWriteVal {
/// Segment Length.
///
/// For read or write segments, this field controls the
/// number of 1-byte bursts to transmit and or receive in
/// this command segment. The number of cyles required
/// to send or received a byte will depend on !!COMMAND.SPEED.
/// For dummy segments, (!!COMMAND.DIRECTION == 0), this register
/// controls the number of dummy cycles to issue.
/// The number of bytes (or dummy cycles) in the segment will be
/// equal to !!COMMAND.LEN + 1.
#[inline(always)]
pub fn len(self, val: u32) -> Self {
Self((self.0 & !(0x1ff << 0)) | ((val & 0x1ff) << 0))
}
/// Chip select active after transaction. If CSAAT = 0, the
/// chip select line is raised immediately at the end of the
/// command segment. If !!COMMAND.CSAAT = 1, the chip select
/// line is left low at the end of the current transaction
/// segment. This allows the creation longer, more
/// complete SPI transactions, consisting of several separate
/// segments for issuing instructions, pausing for dummy cycles,
/// and transmitting or receiving data from the device.
#[inline(always)]
pub fn csaat(self, val: bool) -> Self {
Self((self.0 & !(1 << 9)) | (u32::from(val) << 9))
}
/// The speed for this command segment: "0" = Standard SPI. "1" = Dual SPI.
/// "2"=Quad SPI, "3": RESERVED.
#[inline(always)]
pub fn speed(self, val: u32) -> Self {
Self((self.0 & !(3 << 10)) | ((val & 3) << 10))
}
/// The direction for the following command: "0" = Dummy cycles
/// (no TX/RX). "1" = Rx only, "2" = Tx only, "3" = Bidirectional
/// Tx/Rx (Standard SPI mode only).
#[inline(always)]
pub fn direction(self, val: u32) -> Self {
Self((self.0 & !(3 << 12)) | ((val & 3) << 12))
}
}
impl From<u32> for CommandWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CommandWriteVal> for u32 {
#[inline(always)]
fn from(val: CommandWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ConfigoptsReadVal(u32);
impl ConfigoptsReadVal {
/// Core clock divider. Slows down subsequent SPI transactions by a
/// factor of (CLKDIV+1) relative to the core clock frequency. The
/// period of sck, T(sck) then becomes `2*(CLK_DIV+1)*T(core)`
#[inline(always)]
pub fn clkdiv(&self) -> u32 {
(self.0 >> 0) & 0xffff
}
/// Minimum idle time between commands. Indicates the minimum
/// number of sck half-cycles to hold cs_n high between commands.
/// Setting this register to zero creates a minimally-wide CS_N-high
/// pulse of one-half sck cycle.
#[inline(always)]
pub fn csnidle(&self) -> u32 {
(self.0 >> 16) & 0xf
}
/// CS_N Trailing Time. Indicates the number of half sck cycles,
/// CSNTRAIL+1, to leave between last edge of sck and the rising
/// edge of cs_n. Setting this register to zero corresponds
/// to the minimum delay of one-half sck cycle.
#[inline(always)]
pub fn csntrail(&self) -> u32 {
(self.0 >> 20) & 0xf
}
/// CS_N Leading Time. Indicates the number of half sck cycles,
/// CSNLEAD+1, to leave between the falling edge of cs_n and
/// the first edge of sck. Setting this register to zero
/// corresponds to the minimum delay of one-half sck cycle
#[inline(always)]
pub fn csnlead(&self) -> u32 {
(self.0 >> 24) & 0xf
}
/// Full cycle. Modifies the CPHA sampling behaviour to allow
/// for longer device logic setup times. Rather than sampling the SD
/// bus a half cycle after shifting out data, the data is sampled
/// a full cycle after shifting data out. This means that if
/// CPHA = 0, data is shifted out on the trailing edge, and
/// sampled a full cycle later. If CPHA = 1, data is shifted and
/// sampled with the trailing edge, also separated by a
/// full cycle.
#[inline(always)]
pub fn fullcyc(&self) -> bool {
((self.0 >> 29) & 1) != 0
}
/// The phase of the sck clock signal relative to the data. When
/// CPHA = 0, the data changes on the trailing edge of sck
/// and is typically sampled on the leading edge. Conversely
/// if CPHA = 1 high, data lines change on the leading edge of
/// sck and are typically sampled on the trailing edge.
/// CPHA should be chosen to match the phase of the selected
/// device. The sampling behavior is modified by the
/// !!CONFIGOPTS.FULLCYC bit.
#[inline(always)]
pub fn cpha(&self) -> bool {
((self.0 >> 30) & 1) != 0
}
/// The polarity of the sck clock signal. When CPOL is 0,
/// sck is low when idle, and emits high pulses. When CPOL
/// is low, sck is high when idle, and emits a series of low
/// pulses.
#[inline(always)]
pub fn cpol(&self) -> bool {
((self.0 >> 31) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ConfigoptsWriteVal {
ConfigoptsWriteVal(self.0)
}
}
impl From<u32> for ConfigoptsReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ConfigoptsReadVal> for u32 {
#[inline(always)]
fn from(val: ConfigoptsReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ConfigoptsWriteVal(u32);
impl ConfigoptsWriteVal {
/// Core clock divider. Slows down subsequent SPI transactions by a
/// factor of (CLKDIV+1) relative to the core clock frequency. The
/// period of sck, T(sck) then becomes `2*(CLK_DIV+1)*T(core)`
#[inline(always)]
pub fn clkdiv(self, val: u32) -> Self {
Self((self.0 & !(0xffff << 0)) | ((val & 0xffff) << 0))
}
/// Minimum idle time between commands. Indicates the minimum
/// number of sck half-cycles to hold cs_n high between commands.
/// Setting this register to zero creates a minimally-wide CS_N-high
/// pulse of one-half sck cycle.
#[inline(always)]
pub fn csnidle(self, val: u32) -> Self {
Self((self.0 & !(0xf << 16)) | ((val & 0xf) << 16))
}
/// CS_N Trailing Time. Indicates the number of half sck cycles,
/// CSNTRAIL+1, to leave between last edge of sck and the rising
/// edge of cs_n. Setting this register to zero corresponds
/// to the minimum delay of one-half sck cycle.
#[inline(always)]
pub fn csntrail(self, val: u32) -> Self {
Self((self.0 & !(0xf << 20)) | ((val & 0xf) << 20))
}
/// CS_N Leading Time. Indicates the number of half sck cycles,
/// CSNLEAD+1, to leave between the falling edge of cs_n and
/// the first edge of sck. Setting this register to zero
/// corresponds to the minimum delay of one-half sck cycle
#[inline(always)]
pub fn csnlead(self, val: u32) -> Self {
Self((self.0 & !(0xf << 24)) | ((val & 0xf) << 24))
}
/// Full cycle. Modifies the CPHA sampling behaviour to allow
/// for longer device logic setup times. Rather than sampling the SD
/// bus a half cycle after shifting out data, the data is sampled
/// a full cycle after shifting data out. This means that if
/// CPHA = 0, data is shifted out on the trailing edge, and
/// sampled a full cycle later. If CPHA = 1, data is shifted and
/// sampled with the trailing edge, also separated by a
/// full cycle.
#[inline(always)]
pub fn fullcyc(self, val: bool) -> Self {
Self((self.0 & !(1 << 29)) | (u32::from(val) << 29))
}
/// The phase of the sck clock signal relative to the data. When
/// CPHA = 0, the data changes on the trailing edge of sck
/// and is typically sampled on the leading edge. Conversely
/// if CPHA = 1 high, data lines change on the leading edge of
/// sck and are typically sampled on the trailing edge.
/// CPHA should be chosen to match the phase of the selected
/// device. The sampling behavior is modified by the
/// !!CONFIGOPTS.FULLCYC bit.
#[inline(always)]
pub fn cpha(self, val: bool) -> Self {
Self((self.0 & !(1 << 30)) | (u32::from(val) << 30))
}
/// The polarity of the sck clock signal. When CPOL is 0,
/// sck is low when idle, and emits high pulses. When CPOL
/// is low, sck is high when idle, and emits a series of low
/// pulses.
#[inline(always)]
pub fn cpol(self, val: bool) -> Self {
Self((self.0 & !(1 << 31)) | (u32::from(val) << 31))
}
}
impl From<u32> for ConfigoptsWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ConfigoptsWriteVal> for u32 {
#[inline(always)]
fn from(val: ConfigoptsWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ControlReadVal(u32);
impl ControlReadVal {
/// If !!EVENT_ENABLE.RXWM is set, the IP will send
/// an interrupt when the depth of the RX FIFO reaches
/// RX_WATERMARK words (32b each).
#[inline(always)]
pub fn rx_watermark(&self) -> u32 {
(self.0 >> 0) & 0xff
}
/// If !!EVENT_ENABLE.TXWM is set, the IP will send
/// an interrupt when the depth of the TX FIFO drops below
/// TX_WATERMARK words (32b each).
#[inline(always)]
pub fn tx_watermark(&self) -> u32 {
(self.0 >> 8) & 0xff
}
/// Enable the SPI host output buffers for the sck, csb, and sd lines. This allows
/// the SPI_HOST IP to connect to the same bus as other SPI controllers without
/// interference.
#[inline(always)]
pub fn output_en(&self) -> bool {
((self.0 >> 29) & 1) != 0
}
/// Clears the entire IP to the reset state when set to 1, including
/// the FIFOs, the CDC's, the core state machine and the shift register.
/// In the current implementation, the CDC FIFOs are drained not reset.
/// Therefore software must confirm that both FIFO's empty before releasing
/// the IP from reset.
#[inline(always)]
pub fn sw_rst(&self) -> bool {
((self.0 >> 30) & 1) != 0
}
/// Enables the SPI host. On reset, this field is 0, meaning
/// that no transactions can proceed.
#[inline(always)]
pub fn spien(&self) -> bool {
((self.0 >> 31) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ControlWriteVal {
ControlWriteVal(self.0)
}
}
impl From<u32> for ControlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ControlReadVal> for u32 {
#[inline(always)]
fn from(val: ControlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ControlWriteVal(u32);
impl ControlWriteVal {
/// If !!EVENT_ENABLE.RXWM is set, the IP will send
/// an interrupt when the depth of the RX FIFO reaches
/// RX_WATERMARK words (32b each).
#[inline(always)]
pub fn rx_watermark(self, val: u32) -> Self {
Self((self.0 & !(0xff << 0)) | ((val & 0xff) << 0))
}
/// If !!EVENT_ENABLE.TXWM is set, the IP will send
/// an interrupt when the depth of the TX FIFO drops below
/// TX_WATERMARK words (32b each).
#[inline(always)]
pub fn tx_watermark(self, val: u32) -> Self {
Self((self.0 & !(0xff << 8)) | ((val & 0xff) << 8))
}
/// Enable the SPI host output buffers for the sck, csb, and sd lines. This allows
/// the SPI_HOST IP to connect to the same bus as other SPI controllers without
/// interference.
#[inline(always)]
pub fn output_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 29)) | (u32::from(val) << 29))
}
/// Clears the entire IP to the reset state when set to 1, including
/// the FIFOs, the CDC's, the core state machine and the shift register.
/// In the current implementation, the CDC FIFOs are drained not reset.
/// Therefore software must confirm that both FIFO's empty before releasing
/// the IP from reset.
#[inline(always)]
pub fn sw_rst(self, val: bool) -> Self {
Self((self.0 & !(1 << 30)) | (u32::from(val) << 30))
}
/// Enables the SPI host. On reset, this field is 0, meaning
/// that no transactions can proceed.
#[inline(always)]
pub fn spien(self, val: bool) -> Self {
Self((self.0 & !(1 << 31)) | (u32::from(val) << 31))
}
}
impl From<u32> for ControlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ControlWriteVal> for u32 {
#[inline(always)]
fn from(val: ControlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorEnableReadVal(u32);
impl ErrorEnableReadVal {
/// Command Error: If this bit is set, the block sends an error
/// interrupt whenever a command is issued while busy (i.e. a 1 is
/// when !!STATUS.READY is not asserted.)
#[inline(always)]
pub fn cmdbusy(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Overflow Errors: If this bit is set, the block sends an
/// error interrupt whenever the TX FIFO overflows.
#[inline(always)]
pub fn overflow(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Underflow Errors: If this bit is set, the block sends an
/// error interrupt whenever there is a read from !!RXDATA
/// but the RX FIFO is empty.
#[inline(always)]
pub fn underflow(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Invalid Command Errors: If this bit is set, the block sends an
/// error interrupt whenever a command is sent with invalid values for
/// !!COMMAND.SPEED or !!COMMAND.DIRECTION.
#[inline(always)]
pub fn cmdinval(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Invalid CSID: If this bit is set, the block sends an error interrupt whenever
/// a command is submitted, but CSID exceeds NumCS.
#[inline(always)]
pub fn csidinval(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorEnableWriteVal {
ErrorEnableWriteVal(self.0)
}
}
impl From<u32> for ErrorEnableReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorEnableReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorEnableReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorEnableWriteVal(u32);
impl ErrorEnableWriteVal {
/// Command Error: If this bit is set, the block sends an error
/// interrupt whenever a command is issued while busy (i.e. a 1 is
/// when !!STATUS.READY is not asserted.)
#[inline(always)]
pub fn cmdbusy(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Overflow Errors: If this bit is set, the block sends an
/// error interrupt whenever the TX FIFO overflows.
#[inline(always)]
pub fn overflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Underflow Errors: If this bit is set, the block sends an
/// error interrupt whenever there is a read from !!RXDATA
/// but the RX FIFO is empty.
#[inline(always)]
pub fn underflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Invalid Command Errors: If this bit is set, the block sends an
/// error interrupt whenever a command is sent with invalid values for
/// !!COMMAND.SPEED or !!COMMAND.DIRECTION.
#[inline(always)]
pub fn cmdinval(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Invalid CSID: If this bit is set, the block sends an error interrupt whenever
/// a command is submitted, but CSID exceeds NumCS.
#[inline(always)]
pub fn csidinval(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
}
impl From<u32> for ErrorEnableWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorEnableWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorEnableWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorStatusReadVal(u32);
impl ErrorStatusReadVal {
/// Indicates a write to !!COMMAND when !!STATUS.READY = 0.
#[inline(always)]
pub fn cmdbusy(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Indicates that firmware has overflowed the TX FIFO
#[inline(always)]
pub fn overflow(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Indicates that firmware has attempted to read from
/// !!RXDATA when the RX FIFO is empty.
#[inline(always)]
pub fn underflow(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Indicates an invalid command segment, meaning either an invalid value of
/// !!COMMAND.SPEED or a request for bidirectional data transfer at dual or quad
/// speed
#[inline(always)]
pub fn cmdinval(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Indicates a command was attempted with an invalid value for !!CSID.
#[inline(always)]
pub fn csidinval(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Indicates that TLUL attempted to write to TXDATA with no bytes enabled. Such
/// 'zero byte' writes are not supported.
#[inline(always)]
pub fn accessinval(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorStatusWriteVal {
ErrorStatusWriteVal(self.0)
}
}
impl From<u32> for ErrorStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorStatusReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorStatusWriteVal(u32);
impl ErrorStatusWriteVal {
/// Indicates a write to !!COMMAND when !!STATUS.READY = 0.
#[inline(always)]
pub fn cmdbusy(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Indicates that firmware has overflowed the TX FIFO
#[inline(always)]
pub fn overflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Indicates that firmware has attempted to read from
/// !!RXDATA when the RX FIFO is empty.
#[inline(always)]
pub fn underflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Indicates an invalid command segment, meaning either an invalid value of
/// !!COMMAND.SPEED or a request for bidirectional data transfer at dual or quad
/// speed
#[inline(always)]
pub fn cmdinval(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Indicates a command was attempted with an invalid value for !!CSID.
#[inline(always)]
pub fn csidinval(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Indicates that TLUL attempted to write to TXDATA with no bytes enabled. Such
/// 'zero byte' writes are not supported.
#[inline(always)]
pub fn accessinval(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
}
impl From<u32> for ErrorStatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorStatusWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorStatusWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct EventEnableReadVal(u32);
impl EventEnableReadVal {
/// Assert to send a spi_event interrupt whenever !!STATUS.RXFULL
/// goes high
#[inline(always)]
pub fn rxfull(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Assert to send a spi_event interrupt whenever !!STATUS.TXEMPTY
/// goes high
#[inline(always)]
pub fn txempty(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Assert to send a spi_event interrupt whenever the number of 32-bit words in
/// the RX FIFO is greater than !!CONTROL.RX_WATERMARK. To prevent the
/// reassertion of this interrupt, read more data from the RX FIFO, or
/// increase !!CONTROL.RX_WATERMARK.
#[inline(always)]
pub fn rxwm(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Assert to send a spi_event interrupt whenever the number of 32-bit words in
/// the TX FIFO is less than !!CONTROL.TX_WATERMARK. To prevent the
/// reassertion of this interrupt add more data to the TX FIFO, or
/// reduce !!CONTROL.TX_WATERMARK.
#[inline(always)]
pub fn txwm(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Assert to send a spi_event interrupt whenever !!STATUS.READY
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/ecc.rs | hw/latest/registers/src/ecc.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct EccReg {
_priv: (),
}
impl EccReg {
pub const PTR: *mut u32 = 0x10008000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing of the name
/// of ECC component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn name(&self) -> ureg::Array<2, ureg::RegRef<crate::ecc::meta::Name, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of ECC component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn version(&self) -> ureg::Array<2, ureg::RegRef<crate::ecc::meta::Version, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component control register type definition
///
/// Read value: [`ecc::regs::CtrlReadVal`]; Write value: [`ecc::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::ecc::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component status register type definition
///
/// Read value: [`ecc::regs::StatusReadVal`]; Write value: [`ecc::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::ecc::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component seed register type definition
/// 12 32-bit registers storing the 384-bit seed for keygen in big-endian representation.
/// The seed can be any 384-bit value in [0 : 2^384-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn seed(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::Seed, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component hashed message register type definition
/// 12 32-bit registers storing the hash of the message respect
/// to SHA384 algorithm in big-endian representation.
/// The hashed message can be any 384-bit value in [0 : 2^384-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn msg(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::Msg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component private key output register type definition
/// 12 32-bit registers storing the private key for keygen in big-endian representation.
/// These registers is read by ECC user after keygen operation.
/// The private key is in [1 : q-1] while q is the group
/// order of the Secp384r1 curve.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn privkey_out(
&self,
) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::PrivkeyOut, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component public key (x) register type definition
/// 12 32-bit registers storing the x coordinate of public key in big-endian representation.
/// These registers is read by ECC user after keygen operation,
/// or be set before verifying operation.
/// The public key x should be in [1 : p-1] while p is the prime
/// number of the Secp384r1 curve.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn pubkey_x(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::PubkeyX, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component public key (y) register type definition
/// 12 32-bit registers storing the y coordinate of public key in big-endian representation.
/// These registers is read by ECC user after keygen operation,
/// or be set before verifying operation.
/// The public key y should be in [1 : p-1] while p is the prime
/// number of the Secp384r1 curve.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn pubkey_y(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::PubkeyY, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x280 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component signature R register type definition
/// 12 32-bit registers storing the signature R of the message in big-endian representation.
/// These registers is read by ECC user after signing operation,
/// or be set before verifying operation.
/// The signature R should be in [1 : q-1] while q is the group
/// order of the Secp384r1 curve.
/// Based on RFC6979, If R turns out to be zero, a new nonce (by changing
/// the private key or the message) should be selected and R computed
/// again (this is an utterly improbable occurrence).
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn sign_r(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::SignR, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x300 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component signature S register type definition
/// 12 32-bit registers storing the signature S of the message in big-endian representation.
/// These registers is read by ECC user after signing operation,
/// or be set before verifying operation.
/// The signature S should be in [1 : q-1] while q is the group
/// order of the Secp384r1 curve.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn sign_s(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::SignS, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x380 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component verify R result register type definition
/// 12 32-bit registers storing the result of verifying operation in big-endian representation.
/// Firmware is responsible for comparing the computed result with
/// the signature R, and if they are equal the signature is valid.
/// The verify R result should be in [1 : q-1] while q is the group
/// order of the Secp384r1 curve.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn verify_r(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::VerifyR, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x400 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component IV register type definition
/// 12 32-bit registers storing the 384-bit IV required
/// for SCA countermeasures to randomize the inputs with no change
/// on the ECC outputs.
/// The IV can be any 384-bit value in [0 : 2^384-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn iv(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::Iv, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x480 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component nonce register type definition
/// 12 32-bit registers storing the 384-bit nonce for keygen in big-endian representation.
/// The nonce can be any 384-bit value in [0 : 2^384-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn nonce(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::Nonce, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x500 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// ECC component private key input register type definition
/// 12 32-bit registers storing the private key for signing in big-endian representation.
/// These registers is set before signing operation.
/// The private key should be in [1 : q-1] while q is the group
/// order of the Secp384r1 curve.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn privkey_in(&self) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::PrivkeyIn, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x580 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 12 32-bit registers storing the 384-bit Diffie-Hellman shared key.
/// These registers is read by ECC user after ECDH operation.
/// The shared key should be in [1 : p-1] while p is the prime
/// number of the Secp384r1 curve.
/// These registers are located at ECC_base_address +
/// 0x0000_0600 to 0x0000_062C in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dh_shared_key(
&self,
) -> ureg::Array<12, ureg::RegRef<crate::ecc::meta::DhSharedKey, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x5c0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_rd_pkey_ctrl(&self) -> ureg::RegRef<crate::ecc::meta::KvRdPkeyCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x600 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_rd_pkey_status(&self) -> ureg::RegRef<crate::ecc::meta::KvRdPkeyStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x604 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_rd_seed_ctrl(&self) -> ureg::RegRef<crate::ecc::meta::KvRdSeedCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x608 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_rd_seed_status(&self) -> ureg::RegRef<crate::ecc::meta::KvRdSeedStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault write access for this engine
///
/// Read value: [`regs::KvWriteCtrlRegReadVal`]; Write value: [`regs::KvWriteCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_wr_pkey_ctrl(&self) -> ureg::RegRef<crate::ecc::meta::KvWrPkeyCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x610 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_wr_pkey_status(&self) -> ureg::RegRef<crate::ecc::meta::KvWrPkeyStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x614 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`ecc::regs::ErrorIntrEnTReadVal`]; Write value: [`ecc::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`ecc::regs::NotifIntrEnTReadVal`]; Write value: [`ecc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`ecc::regs::ErrorIntrTReadVal`]; Write value: [`ecc::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`ecc::regs::NotifIntrTReadVal`]; Write value: [`ecc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`ecc::regs::ErrorIntrTrigTReadVal`]; Write value: [`ecc::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`ecc::regs::NotifIntrTrigTReadVal`]; Write value: [`ecc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_internal_intr_count_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfErrorInternalIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfErrorInternalIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::ecc::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct CtrlWriteVal(u32);
impl CtrlWriteVal {
/// Control command field: This can be:
/// [br] 00 for NONE
/// [br] 01 for KEYGEN
/// [br] 10 for SIGNING
/// [br] 11 for VERIFYING
/// [br] After each software write, hardware will erase the register
#[inline(always)]
pub fn ctrl(
self,
f: impl FnOnce(super::enums::selector::CtrlSelector) -> super::enums::Ctrl,
) -> Self {
Self((self.0 & !(3 << 0)) | (u32::from(f(super::enums::selector::CtrlSelector())) << 0))
}
/// Zeroize all internal registers: Zeroize all internal registers after ECC process, to avoid SCA leakage.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn zeroize(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Run PCR Signing flow: Run ECC Signing flow to sign PCRs.
#[inline(always)]
pub fn pcr_sign(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Run ECDH for shared key generation.
#[inline(always)]
pub fn dh_sharedkey(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
}
impl From<u32> for CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Status ready bit: Indicates if the core is ready to take
/// a control command and process the block.
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Status valid bit: Indicates if the process is done and the
/// hash value stored in DIGEST registers is valid.
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Internal Errors
#[inline(always)]
pub fn error_internal_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrEnTWriteVal {
ErrorIntrEnTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTWriteVal(u32);
impl ErrorIntrEnTWriteVal {
/// Enable bit for Internal Errors
#[inline(always)]
pub fn error_internal_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for ErrorIntrEnTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTReadVal(u32);
impl ErrorIntrTReadVal {
/// Internal Errors status bit
#[inline(always)]
pub fn error_internal_sts(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTWriteVal {
ErrorIntrTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTWriteVal(u32);
impl ErrorIntrTWriteVal {
/// Internal Errors status bit
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/axi_dma.rs | hw/latest/registers/src/axi_dma.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct AxiDmaReg {
_priv: (),
}
impl AxiDmaReg {
pub const PTR: *mut u32 = 0x30022000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Gives a unique identifier that FW can query to verify block base address
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn id(&self) -> ureg::RegRef<crate::axi_dma::meta::Id, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides information about configuration and enabled capabilities for the DMA block.
///
/// Read value: [`axi_dma::regs::CapReadVal`]; Write value: [`axi_dma::regs::CapWriteVal`]
#[inline(always)]
pub fn cap(&self) -> ureg::RegRef<crate::axi_dma::meta::Cap, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Used to drive command parameters and initiate operations to DMA block.
///
/// Read value: [`axi_dma::regs::CtrlReadVal`]; Write value: [`axi_dma::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::axi_dma::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports status and diagnostic information for DMA operations.
///
/// Read value: [`axi_dma::regs::Status0ReadVal`]; Write value: [`axi_dma::regs::Status0WriteVal`]
#[inline(always)]
pub fn status0(&self) -> ureg::RegRef<crate::axi_dma::meta::Status0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports additional status and diagnostic information for DMA operations.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn status1(&self) -> ureg::RegRef<crate::axi_dma::meta::Status1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Contains lower 32-bits of address from which current operation will read data. Defines the AXI read address when read route is enabled; defines the offset into the mailbox when write route is set to MBOX.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn src_addr_l(&self) -> ureg::RegRef<crate::axi_dma::meta::SrcAddrL, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Contains upper 32-bits of address from which current operation will read data. Defines the AXI read address when read route is enabled; defines the offset into the mailbox when write route is set to MBOX.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn src_addr_h(&self) -> ureg::RegRef<crate::axi_dma::meta::SrcAddrH, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Contains lower 32-bits of address to which current operation will write data. Defines the AXI write address when write route is enabled; defines the offset into the mailbox when read route is set to MBOX.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dst_addr_l(&self) -> ureg::RegRef<crate::axi_dma::meta::DstAddrL, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Contains upper 32-bits of address to which current operation will write data. Defines the AXI write address when write route is enabled; defines the offset into the mailbox when read route is set to MBOX.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dst_addr_h(&self) -> ureg::RegRef<crate::axi_dma::meta::DstAddrH, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Contains total number of bytes to be transferred by current operation. Must be a multiple of the AXI Data Width. (Narrow/unaligned transfers are not supported)
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn byte_count(&self) -> ureg::RegRef<crate::axi_dma::meta::ByteCount, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Byte size of individual blocks to send as part of the total
/// Byte Count. This register indicates what granularity of AXI
/// transactions are issued at a time.
/// When non-zero, this field instructs the DMA to wait for the
/// input “recovery_data_avail” (a.k.a. payload_available) to be
/// set to 1 before issuing each transaction.
/// Total burst is done once “Byte_count/block_size” transactions
/// have completed.
/// After completion of a burst, if recovery_data_avail is set,
/// the subsequent burst will be issued. Otherwise, DMA will wait
/// for recovery_data_avail to be set.
/// If block_size is larger than the maximum legal AXI burst length,
/// it will be further subdivided to multiple smaller bursts.
/// When zero, DMA issues AXI transactions of maximum size
/// without any stalls in between transactions.
/// Must be a multiple of AXI data width. If block size is not
/// aligned to the AXI data width, it will be rounded down.
/// Must be a power of 2.
/// Value of 4096 or larger is unsupported – AXI native maximum size is 4096.
///
/// Read value: [`axi_dma::regs::BlockSizeReadVal`]; Write value: [`axi_dma::regs::BlockSizeWriteVal`]
#[inline(always)]
pub fn block_size(&self) -> ureg::RegRef<crate::axi_dma::meta::BlockSize, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Access point for Caliptra firmware to submit data into the Write
/// FIFO to be sent as AXI Write transfers.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn write_data(&self) -> ureg::RegRef<crate::axi_dma::meta::WriteData, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Access point for Caliptra firmware to read data from the Read
/// FIFO as it is received via AXI Read transfers.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn read_data(&self) -> ureg::RegRef<crate::axi_dma::meta::ReadData, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`axi_dma::regs::ErrorIntrEnTReadVal`]; Write value: [`axi_dma::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`axi_dma::regs::NotifIntrEnTReadVal`]; Write value: [`axi_dma::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`axi_dma::regs::ErrorIntrTReadVal`]; Write value: [`axi_dma::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`axi_dma::regs::NotifIntrTReadVal`]; Write value: [`axi_dma::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`axi_dma::regs::ErrorIntrTrigTReadVal`]; Write value: [`axi_dma::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`axi_dma::regs::NotifIntrTrigTReadVal`]; Write value: [`axi_dma::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_cmd_dec_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorCmdDecIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_axi_rd_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorAxiRdIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_axi_wr_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorAxiWrIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_mbox_lock_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorMboxLockIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_sha_lock_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorShaLockIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x110 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_fifo_oflow_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorFifoOflowIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x114 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_fifo_uflow_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorFifoUflowIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x118 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_aes_cif_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorAesCifIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x11c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_kv_rd_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorKvRdIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x120 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_kv_rd_large_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorKvRdLargeIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x124 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_txn_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifTxnDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_fifo_empty_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifFifoEmptyIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x184 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_fifo_not_empty_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifFifoNotEmptyIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x188 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_fifo_full_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifFifoFullIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_fifo_not_full_intr_count_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfNotifFifoNotFullIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x190 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_cmd_dec_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorCmdDecIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_axi_rd_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorAxiRdIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_axi_wr_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorAxiWrIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_mbox_lock_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorMboxLockIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_sha_lock_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorShaLockIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_fifo_oflow_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::axi_dma::meta::IntrBlockRfErrorFifoOflowIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x214 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mcu_sram.rs | hw/latest/registers/src/mcu_sram.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct McuSram {
_priv: (),
}
impl McuSram {
pub const PTR: *mut u32 = 0xc00000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
}
pub mod regs {
//! Types that represent the values held by registers.
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/kmac.rs | hw/latest/registers/src/kmac.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct Kmac {
_priv: (),
}
impl Kmac {
pub const PTR: *mut u32 = 0x10040000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`kmac::regs::IntrStateReadVal`]; Write value: [`kmac::regs::IntrStateWriteVal`]
#[inline(always)]
pub fn intr_state(&self) -> ureg::RegRef<crate::kmac::meta::IntrState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kmac::regs::IntrEnableReadVal`]; Write value: [`kmac::regs::IntrEnableWriteVal`]
#[inline(always)]
pub fn intr_enable(&self) -> ureg::RegRef<crate::kmac::meta::IntrEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kmac::regs::IntrTestReadVal`]; Write value: [`kmac::regs::IntrTestWriteVal`]
#[inline(always)]
pub fn intr_test(&self) -> ureg::RegRef<crate::kmac::meta::IntrTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kmac::regs::AlertTestReadVal`]; Write value: [`kmac::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::kmac::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kmac::regs::CfgRegwenReadVal`]; Write value: [`kmac::regs::CfgRegwenWriteVal`]
#[inline(always)]
pub fn cfg_regwen(&self) -> ureg::RegRef<crate::kmac::meta::CfgRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register is shadowed and protected by CFG_REGWEN.en
/// 1. Two subsequent write operation are required to change its content,
/// If the two write operations try to set a different value, a recoverable alert is triggered (See Status Register).
/// 2. A read operation clears the internal phase tracking.
/// 3. If storage error(~staged_reg!=committed_reg) happen, it will trigger fatal fault alert
///
/// Read value: [`kmac::regs::CfgShadowedReadVal`]; Write value: [`kmac::regs::CfgShadowedWriteVal`]
#[inline(always)]
pub fn cfg_shadowed(&self) -> ureg::RegRef<crate::kmac::meta::CfgShadowed, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kmac::regs::CmdReadVal`]; Write value: [`kmac::regs::CmdWriteVal`]
#[inline(always)]
pub fn cmd(&self) -> ureg::RegRef<crate::kmac::meta::Cmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kmac::regs::StatusReadVal`]; Write value: [`kmac::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::kmac::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_0(&self) -> ureg::RegRef<crate::kmac::meta::Prefix0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_1(&self) -> ureg::RegRef<crate::kmac::meta::Prefix1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_2(&self) -> ureg::RegRef<crate::kmac::meta::Prefix2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_3(&self) -> ureg::RegRef<crate::kmac::meta::Prefix3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_4(&self) -> ureg::RegRef<crate::kmac::meta::Prefix4, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_5(&self) -> ureg::RegRef<crate::kmac::meta::Prefix5, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_6(&self) -> ureg::RegRef<crate::kmac::meta::Prefix6, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_7(&self) -> ureg::RegRef<crate::kmac::meta::Prefix7, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_8(&self) -> ureg::RegRef<crate::kmac::meta::Prefix8, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_9(&self) -> ureg::RegRef<crate::kmac::meta::Prefix9, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn prefix_10(&self) -> ureg::RegRef<crate::kmac::meta::Prefix10, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x48 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA3 Error Code
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn err_code(&self) -> ureg::RegRef<crate::kmac::meta::ErrCode, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x4c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Keccak State (1600 bit) memory.
/// The software can get the processed digest by reading this memory
/// region. Unlike MSG_FIFO, STATE memory space sees the addr[9:0].
/// If Masking feature is enabled, the software reads two shares from
/// this memory space.
/// 0x200 - 0x2C7: State share
/// for Keccak State access:
/// 1. Output length <= rate length, sha3_done will be raised or software can poll STATUS.squeeze become 1.
/// 2. Output length > rate length, after software read 1st keccak state, software should issue run cmd to trigger keccak round logic to run full 24 rounds.
/// And then software should check STATUS.squeeze register field for the readiness of STATE value(SHA3 FSM become MANUAL_RUN before keccak state complete).
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn state(&self) -> ureg::Array<64, ureg::RegRef<crate::kmac::meta::State, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x400 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Message FIFO. window size is 2048 bytes.
/// Any write operation to this window will be appended to MSG_FIFO. SW can
/// simply write bytes/words to any address within this address range.
/// Ordering and packing of the incoming bytes/words are handled
/// internally. Therefore, the least significant 10 bits of the address
/// are ignored.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn msg_fifo(&self) -> ureg::Array<64, ureg::RegRef<crate::kmac::meta::MsgFifo, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x800 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AlertTestWriteVal(u32);
impl AlertTestWriteVal {
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn recov_operation_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_fault_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for AlertTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AlertTestWriteVal> for u32 {
#[inline(always)]
fn from(val: AlertTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CfgRegwenReadVal(u32);
impl CfgRegwenReadVal {
/// Configuration enable.
#[inline(always)]
pub fn en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
}
impl From<u32> for CfgRegwenReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CfgRegwenReadVal> for u32 {
#[inline(always)]
fn from(val: CfgRegwenReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CfgShadowedReadVal(u32);
impl CfgShadowedReadVal {
/// Hashing Strength, Protected by CFG_REGWEN.en
/// bit field to select the security strength of SHA3 hashing engine.
/// If mode field is set to SHAKE, only 128 and 256 strength can be selected.
/// Other value will result error when hashing starts.
#[inline(always)]
pub fn kstrength(&self) -> u32 {
(self.0 >> 1) & 7
}
/// Keccak hashing mode, Protected by CFG_REGWEN.en
/// This module supports SHA3 main hashing algorithm and the part of its derived functions,
/// SHAKE with limitations. This field is to select the mode.
#[inline(always)]
pub fn mode(&self) -> u32 {
(self.0 >> 4) & 3
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual multi-byte value, regardless of its alignment,
/// written to MSG_FIFO will be added to the message in big-endian byte order.
/// If 0, each value will be added to the message in little-endian byte order.
/// A message written to MSG_FIFO one byte at a time will not be affected by this setting.
/// From a hardware perspective byte swaps are performed on a TL-UL word granularity.
#[inline(always)]
pub fn msg_endianness(&self) -> bool {
((self.0 >> 8) & 1) != 0
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual multi-byte value, regardless of its alignment,
/// written to MSG_FIFO will be added to the message in big-endian byte order.
/// If 0, each value will be added to the message in little-endian byte order.
/// A message written to MSG_FIFO one byte at a time will not be affected by this setting.
/// From a hardware perspective byte swaps are performed on a TL-UL word granularity.
#[inline(always)]
pub fn state_endianness(&self) -> bool {
((self.0 >> 9) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CfgShadowedWriteVal {
CfgShadowedWriteVal(self.0)
}
}
impl From<u32> for CfgShadowedReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CfgShadowedReadVal> for u32 {
#[inline(always)]
fn from(val: CfgShadowedReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CfgShadowedWriteVal(u32);
impl CfgShadowedWriteVal {
/// Hashing Strength, Protected by CFG_REGWEN.en
/// bit field to select the security strength of SHA3 hashing engine.
/// If mode field is set to SHAKE, only 128 and 256 strength can be selected.
/// Other value will result error when hashing starts.
#[inline(always)]
pub fn kstrength(self, val: u32) -> Self {
Self((self.0 & !(7 << 1)) | ((val & 7) << 1))
}
/// Keccak hashing mode, Protected by CFG_REGWEN.en
/// This module supports SHA3 main hashing algorithm and the part of its derived functions,
/// SHAKE with limitations. This field is to select the mode.
#[inline(always)]
pub fn mode(self, val: u32) -> Self {
Self((self.0 & !(3 << 4)) | ((val & 3) << 4))
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual multi-byte value, regardless of its alignment,
/// written to MSG_FIFO will be added to the message in big-endian byte order.
/// If 0, each value will be added to the message in little-endian byte order.
/// A message written to MSG_FIFO one byte at a time will not be affected by this setting.
/// From a hardware perspective byte swaps are performed on a TL-UL word granularity.
#[inline(always)]
pub fn msg_endianness(self, val: bool) -> Self {
Self((self.0 & !(1 << 8)) | (u32::from(val) << 8))
}
/// Protected by CFG_REGWEN.en
/// If 1 then each individual multi-byte value, regardless of its alignment,
/// written to MSG_FIFO will be added to the message in big-endian byte order.
/// If 0, each value will be added to the message in little-endian byte order.
/// A message written to MSG_FIFO one byte at a time will not be affected by this setting.
/// From a hardware perspective byte swaps are performed on a TL-UL word granularity.
#[inline(always)]
pub fn state_endianness(self, val: bool) -> Self {
Self((self.0 & !(1 << 9)) | (u32::from(val) << 9))
}
}
impl From<u32> for CfgShadowedWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CfgShadowedWriteVal> for u32 {
#[inline(always)]
fn from(val: CfgShadowedWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CmdReadVal(u32);
impl CmdReadVal {
/// Issues a command to the SHA3 IP. The command is sparse encoded.
/// To prevent sw from writing multiple commands at once, the field is defined as enum.
/// Always return 0 for SW reads.
/// START: Writing 6'b011101 or dec 29 into this field when SHA3/SHAKE is in idle, SHA3/SHAKE begins its operation and start absorbing.
/// PROCESS: Writing 6'b101110 or dec 46 into this field when SHA3/SHAKE began its operation and received the entire message, it computes the digest or signing.
/// RUN: The run field is used in the sponge squeezing stage.
/// It triggers the keccak round logic to run full 24 rounds.
/// This is optional and used when software needs more digest bits than the keccak rate.
/// It only affects when the SHA3/SHAKE operation is completed.
/// DONE: Writing 6'b010110 or dec 22 into this field when SHA3 squeezing is completed,
/// SHA3/SHAKE hashing engine clears internal variables and goes back to Idle state for next command.
#[inline(always)]
pub fn cmd(&self) -> u32 {
(self.0 >> 0) & 0x3f
}
/// When error occurs and one of the state machine stays at Error handling state,
/// SW may process the error based on ERR_CODE, then let FSM back to the reset state.
/// Always return 0 for SW reads.
#[inline(always)]
pub fn err_processed(&self) -> bool {
((self.0 >> 10) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CmdWriteVal {
CmdWriteVal(self.0)
}
}
impl From<u32> for CmdReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CmdReadVal> for u32 {
#[inline(always)]
fn from(val: CmdReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CmdWriteVal(u32);
impl CmdWriteVal {
/// Issues a command to the SHA3 IP. The command is sparse encoded.
/// To prevent sw from writing multiple commands at once, the field is defined as enum.
/// Always return 0 for SW reads.
/// START: Writing 6'b011101 or dec 29 into this field when SHA3/SHAKE is in idle, SHA3/SHAKE begins its operation and start absorbing.
/// PROCESS: Writing 6'b101110 or dec 46 into this field when SHA3/SHAKE began its operation and received the entire message, it computes the digest or signing.
/// RUN: The run field is used in the sponge squeezing stage.
/// It triggers the keccak round logic to run full 24 rounds.
/// This is optional and used when software needs more digest bits than the keccak rate.
/// It only affects when the SHA3/SHAKE operation is completed.
/// DONE: Writing 6'b010110 or dec 22 into this field when SHA3 squeezing is completed,
/// SHA3/SHAKE hashing engine clears internal variables and goes back to Idle state for next command.
#[inline(always)]
pub fn cmd(self, val: u32) -> Self {
Self((self.0 & !(0x3f << 0)) | ((val & 0x3f) << 0))
}
/// When error occurs and one of the state machine stays at Error handling state,
/// SW may process the error based on ERR_CODE, then let FSM back to the reset state.
/// Always return 0 for SW reads.
#[inline(always)]
pub fn err_processed(self, val: bool) -> Self {
Self((self.0 & !(1 << 10)) | (u32::from(val) << 10))
}
}
impl From<u32> for CmdWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CmdWriteVal> for u32 {
#[inline(always)]
fn from(val: CmdWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct IntrEnableReadVal(u32);
impl IntrEnableReadVal {
/// SHA3/SHAKE done interrupt
#[inline(always)]
pub fn kmac_done(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// FIFO empty interrupt
#[inline(always)]
pub fn fifo_empty(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// SHA3/SHAKE error interrupt
#[inline(always)]
pub fn kmac_err(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> IntrEnableWriteVal {
IntrEnableWriteVal(self.0)
}
}
impl From<u32> for IntrEnableReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<IntrEnableReadVal> for u32 {
#[inline(always)]
fn from(val: IntrEnableReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct IntrEnableWriteVal(u32);
impl IntrEnableWriteVal {
/// SHA3/SHAKE done interrupt
#[inline(always)]
pub fn kmac_done(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// FIFO empty interrupt
#[inline(always)]
pub fn fifo_empty(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// SHA3/SHAKE error interrupt
#[inline(always)]
pub fn kmac_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
}
impl From<u32> for IntrEnableWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<IntrEnableWriteVal> for u32 {
#[inline(always)]
fn from(val: IntrEnableWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct IntrStateReadVal(u32);
impl IntrStateReadVal {
/// SHA3/SHAKE done interrupt
#[inline(always)]
pub fn kmac_done(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// FIFO empty interrupt
#[inline(always)]
pub fn fifo_empty(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// SHA3/SHAKE error interrupt
#[inline(always)]
pub fn kmac_err(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> IntrStateWriteVal {
IntrStateWriteVal(self.0)
}
}
impl From<u32> for IntrStateReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<IntrStateReadVal> for u32 {
#[inline(always)]
fn from(val: IntrStateReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct IntrStateWriteVal(u32);
impl IntrStateWriteVal {
/// SHA3/SHAKE done interrupt
#[inline(always)]
pub fn kmac_done(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// SHA3/SHAKE error interrupt
#[inline(always)]
pub fn kmac_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
}
impl From<u32> for IntrStateWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<IntrStateWriteVal> for u32 {
#[inline(always)]
fn from(val: IntrStateWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct IntrTestWriteVal(u32);
impl IntrTestWriteVal {
/// SHA3/SHAKE done interrupt
#[inline(always)]
pub fn kmac_done(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// FIFO empty interrupt
#[inline(always)]
pub fn fifo_empty(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// SHA3/SHAKE error interrupt
#[inline(always)]
pub fn kmac_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
}
impl From<u32> for IntrTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<IntrTestWriteVal> for u32 {
#[inline(always)]
fn from(val: IntrTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// If 1, SHA3 hashing engine is in idle state.
#[inline(always)]
pub fn sha3_idle(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// If 1, SHA3 is receiving message stream and processing it
#[inline(always)]
pub fn sha3_absorb(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// If 1, SHA3 completes sponge absorbing stage. In this stage, SW can manually run the hashing engine.
#[inline(always)]
pub fn sha3_squeeze(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Count of occupied entries in the message FIFO.
#[inline(always)]
pub fn fifo_depth(&self) -> u32 {
(self.0 >> 8) & 0x1f
}
/// Message FIFO Empty indicator.
/// The FIFO's Pass parameter is set to 1'b 1. So, by default, if the SHA engine is ready, the write data to FIFO just passes through.
/// In this case, fifo_depth remains 0. fifo_empty, however, lowers the value to 0 for a cycle, then goes back to the empty state, 1.
/// See the Message FIFO section in the spec for the reason.
#[inline(always)]
pub fn fifo_empty(&self) -> bool {
((self.0 >> 14) & 1) != 0
}
/// Message FIFO Full indicator.
#[inline(always)]
pub fn fifo_full(&self) -> bool {
((self.0 >> 15) & 1) != 0
}
/// No fatal fault has occurred inside the SHA3 unit (0).
/// A fatal fault has occured and the SHA3 unit needs to be reset (1),
/// Examples for such faults include i) TL-UL bus integrity fault
/// ii) storage errors in the shadow registers
/// iii) errors in the message, round, or key counter
/// iv) any internal FSM entering an invalid state.
#[inline(always)]
pub fn alert_fatal_fault(&self) -> bool {
((self.0 >> 16) & 1) != 0
}
/// An update error has not occurred (0) or has occured (1) in the shadowed Control Register.
/// SHA3 operation needs to be restarted by re-writing the Control Register.
#[inline(always)]
pub fn alert_recov_ctrl_update_err(&self) -> bool {
((self.0 >> 17) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type IntrState = ureg::ReadWriteReg32<
0,
crate::kmac::regs::IntrStateReadVal,
crate::kmac::regs::IntrStateWriteVal,
>;
pub type IntrEnable = ureg::ReadWriteReg32<
0,
crate::kmac::regs::IntrEnableReadVal,
crate::kmac::regs::IntrEnableWriteVal,
>;
pub type IntrTest = ureg::WriteOnlyReg32<0, crate::kmac::regs::IntrTestWriteVal>;
pub type AlertTest = ureg::WriteOnlyReg32<0, crate::kmac::regs::AlertTestWriteVal>;
pub type CfgRegwen = ureg::ReadOnlyReg32<crate::kmac::regs::CfgRegwenReadVal>;
pub type CfgShadowed = ureg::ReadWriteReg32<
0,
crate::kmac::regs::CfgShadowedReadVal,
crate::kmac::regs::CfgShadowedWriteVal,
>;
pub type Cmd =
ureg::ReadWriteReg32<0, crate::kmac::regs::CmdReadVal, crate::kmac::regs::CmdWriteVal>;
pub type Status = ureg::ReadOnlyReg32<crate::kmac::regs::StatusReadVal>;
pub type Prefix0 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix1 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix2 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix3 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix4 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix5 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix6 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix7 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix8 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix9 = ureg::ReadWriteReg32<0, u32, u32>;
pub type Prefix10 = ureg::ReadWriteReg32<0, u32, u32>;
pub type ErrCode = ureg::ReadOnlyReg32<u32>;
pub type State = ureg::ReadOnlyReg32<u32>;
pub type MsgFifo = ureg::WriteOnlyReg32<0, u32>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/sha256.rs | hw/latest/registers/src/sha256.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct Sha256Reg {
_priv: (),
}
impl Sha256Reg {
pub const PTR: *mut u32 = 0x10028000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing of the name
/// of SHA256 component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn name(&self) -> ureg::Array<2, ureg::RegRef<crate::sha256::meta::Name, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of SHA256 component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn version(&self) -> ureg::Array<2, ureg::RegRef<crate::sha256::meta::Version, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA256 component control register type definition.
/// After each software write, hardware will erase the register.
///
/// Read value: [`sha256::regs::CtrlReadVal`]; Write value: [`sha256::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::sha256::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA256 component status register type definition
///
/// Read value: [`sha256::regs::StatusReadVal`]; Write value: [`sha256::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::sha256::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA256 component block register type definition.
/// 16 32-bit registers storing the 512-bit padded input in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn block(&self) -> ureg::Array<16, ureg::RegRef<crate::sha256::meta::Block, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA256 component digest register type definition
/// 8 32-bit registers storing the 256-bit digest output in big-endian representation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn digest(&self) -> ureg::Array<8, ureg::RegRef<crate::sha256::meta::Digest, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::ErrorIntrEnTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::NotifIntrEnTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::NotifIntrTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::NotifIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error0_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError0IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error1_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError1IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error0_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError0IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error1_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError1IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha256::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct CtrlWriteVal(u32);
impl CtrlWriteVal {
/// Control init command bit: Trigs the SHA256 core to start the
/// processing for the first padded message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn init(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Control next command bit: Trigs the SHA256 core to start the
/// processing for the remining padded message block.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn next(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Control mode command bits: Indicates the SHA256 core to set dynamically
/// the type of hashing algorithm. This can be:
/// 0 for SHA256/224
/// 1 for SHA256
#[inline(always)]
pub fn mode(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Zeroize all internal registers: Zeroize all internal registers after SHA process, to avoid SCA leakage.
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn zeroize(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Control Winternitz verification mode command bits
/// [br] Software write generates only a single-cycle pulse on the
/// hardware interface and then will be erased
#[inline(always)]
pub fn wntz_mode(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Control Winternitz W value
#[inline(always)]
pub fn wntz_w(self, val: u32) -> Self {
Self((self.0 & !(0xf << 5)) | ((val & 0xf) << 5))
}
/// Control Winternitz n value(SHA192/SHA256 --> n = 24/32)
#[inline(always)]
pub fn wntz_n_mode(self, val: bool) -> Self {
Self((self.0 & !(1 << 9)) | (u32::from(val) << 9))
}
}
impl From<u32> for CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Status ready bit: Indicates if the core is ready to take
/// a control command and process the block.
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Status valid bit: Indicates if the process is done and the
/// hash value stored in DIGEST registers is valid.
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Winternitz busy status bit
#[inline(always)]
pub fn wntz_busy(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrEnTWriteVal {
ErrorIntrEnTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTWriteVal(u32);
impl ErrorIntrEnTWriteVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrEnTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTReadVal(u32);
impl ErrorIntrTReadVal {
/// Interrupt Event 0 status bit
#[inline(always)]
pub fn error0_sts(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Event 1 status bit
#[inline(always)]
pub fn error1_sts(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTWriteVal {
ErrorIntrTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTWriteVal(u32);
impl ErrorIntrTWriteVal {
/// Interrupt Event 0 status bit
#[inline(always)]
pub fn error0_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Interrupt Event 1 status bit
#[inline(always)]
pub fn error1_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTrigTReadVal(u32);
impl ErrorIntrTrigTReadVal {
/// Interrupt Trigger 0 bit
#[inline(always)]
pub fn error0_trig(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Trigger 1 bit
#[inline(always)]
pub fn error1_trig(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Trigger 2 bit
#[inline(always)]
pub fn error2_trig(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Trigger 3 bit
#[inline(always)]
pub fn error3_trig(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTrigTWriteVal {
ErrorIntrTrigTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTrigTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTrigTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTrigTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTrigTWriteVal(u32);
impl ErrorIntrTrigTWriteVal {
/// Interrupt Trigger 0 bit
#[inline(always)]
pub fn error0_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Interrupt Trigger 1 bit
#[inline(always)]
pub fn error1_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Interrupt Trigger 2 bit
#[inline(always)]
pub fn error2_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Interrupt Trigger 3 bit
#[inline(always)]
pub fn error3_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrTrigTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTrigTWriteVal> for u32 {
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/entropy_src.rs | hw/latest/registers/src/entropy_src.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct EntropySrcReg {
_priv: (),
}
impl EntropySrcReg {
pub const PTR: *mut u32 = 0x20003000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`entropy_src::regs::InterruptStateReadVal`]; Write value: [`entropy_src::regs::InterruptStateWriteVal`]
#[inline(always)]
pub fn interrupt_state(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::InterruptState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::InterruptEnableReadVal`]; Write value: [`entropy_src::regs::InterruptEnableWriteVal`]
#[inline(always)]
pub fn interrupt_enable(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::InterruptEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::InterruptTestReadVal`]; Write value: [`entropy_src::regs::InterruptTestWriteVal`]
#[inline(always)]
pub fn interrupt_test(&self) -> ureg::RegRef<crate::entropy_src::meta::InterruptTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AlertTestReadVal`]; Write value: [`entropy_src::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::entropy_src::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::MeRegwenReadVal`]; Write value: [`entropy_src::regs::MeRegwenWriteVal`]
#[inline(always)]
pub fn me_regwen(&self) -> ureg::RegRef<crate::entropy_src::meta::MeRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::SwRegupdReadVal`]; Write value: [`entropy_src::regs::SwRegupdWriteVal`]
#[inline(always)]
pub fn sw_regupd(&self) -> ureg::RegRef<crate::entropy_src::meta::SwRegupd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RegwenReadVal`]; Write value: [`entropy_src::regs::RegwenWriteVal`]
#[inline(always)]
pub fn regwen(&self) -> ureg::RegRef<crate::entropy_src::meta::Regwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RevReadVal`]; Write value: [`entropy_src::regs::RevWriteVal`]
#[inline(always)]
pub fn rev(&self) -> ureg::RegRef<crate::entropy_src::meta::Rev, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ModuleEnableReadVal`]; Write value: [`entropy_src::regs::ModuleEnableWriteVal`]
#[inline(always)]
pub fn module_enable(&self) -> ureg::RegRef<crate::entropy_src::meta::ModuleEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ConfReadVal`]; Write value: [`entropy_src::regs::ConfWriteVal`]
#[inline(always)]
pub fn conf(&self) -> ureg::RegRef<crate::entropy_src::meta::Conf, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::EntropyControlReadVal`]; Write value: [`entropy_src::regs::EntropyControlWriteVal`]
#[inline(always)]
pub fn entropy_control(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::EntropyControl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn entropy_data(&self) -> ureg::RegRef<crate::entropy_src::meta::EntropyData, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::HealthTestWindowsReadVal`]; Write value: [`entropy_src::regs::HealthTestWindowsWriteVal`]
#[inline(always)]
pub fn health_test_windows(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::HealthTestWindows, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RepcntThresholdsReadVal`]; Write value: [`entropy_src::regs::RepcntThresholdsWriteVal`]
#[inline(always)]
pub fn repcnt_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::RepcntThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RepcntsThresholdsReadVal`]; Write value: [`entropy_src::regs::RepcntsThresholdsWriteVal`]
#[inline(always)]
pub fn repcnts_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::RepcntsThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AdaptpHiThresholdsReadVal`]; Write value: [`entropy_src::regs::AdaptpHiThresholdsWriteVal`]
#[inline(always)]
pub fn adaptp_hi_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AdaptpHiThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AdaptpLoThresholdsReadVal`]; Write value: [`entropy_src::regs::AdaptpLoThresholdsWriteVal`]
#[inline(always)]
pub fn adaptp_lo_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AdaptpLoThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::BucketThresholdsReadVal`]; Write value: [`entropy_src::regs::BucketThresholdsWriteVal`]
#[inline(always)]
pub fn bucket_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::BucketThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::MarkovHiThresholdsReadVal`]; Write value: [`entropy_src::regs::MarkovHiThresholdsWriteVal`]
#[inline(always)]
pub fn markov_hi_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::MarkovHiThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x48 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::MarkovLoThresholdsReadVal`]; Write value: [`entropy_src::regs::MarkovLoThresholdsWriteVal`]
#[inline(always)]
pub fn markov_lo_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::MarkovLoThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x4c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ExthtHiThresholdsReadVal`]; Write value: [`entropy_src::regs::ExthtHiThresholdsWriteVal`]
#[inline(always)]
pub fn extht_hi_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtHiThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x50 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ExthtLoThresholdsReadVal`]; Write value: [`entropy_src::regs::ExthtLoThresholdsWriteVal`]
#[inline(always)]
pub fn extht_lo_thresholds(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtLoThresholds, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x54 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RepcntHiWatermarksReadVal`]; Write value: [`entropy_src::regs::RepcntHiWatermarksWriteVal`]
#[inline(always)]
pub fn repcnt_hi_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::RepcntHiWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x58 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RepcntsHiWatermarksReadVal`]; Write value: [`entropy_src::regs::RepcntsHiWatermarksWriteVal`]
#[inline(always)]
pub fn repcnts_hi_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::RepcntsHiWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AdaptpHiWatermarksReadVal`]; Write value: [`entropy_src::regs::AdaptpHiWatermarksWriteVal`]
#[inline(always)]
pub fn adaptp_hi_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AdaptpHiWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AdaptpLoWatermarksReadVal`]; Write value: [`entropy_src::regs::AdaptpLoWatermarksWriteVal`]
#[inline(always)]
pub fn adaptp_lo_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AdaptpLoWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x64 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ExthtHiWatermarksReadVal`]; Write value: [`entropy_src::regs::ExthtHiWatermarksWriteVal`]
#[inline(always)]
pub fn extht_hi_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtHiWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x68 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ExthtLoWatermarksReadVal`]; Write value: [`entropy_src::regs::ExthtLoWatermarksWriteVal`]
#[inline(always)]
pub fn extht_lo_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtLoWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x6c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::BucketHiWatermarksReadVal`]; Write value: [`entropy_src::regs::BucketHiWatermarksWriteVal`]
#[inline(always)]
pub fn bucket_hi_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::BucketHiWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x70 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::MarkovHiWatermarksReadVal`]; Write value: [`entropy_src::regs::MarkovHiWatermarksWriteVal`]
#[inline(always)]
pub fn markov_hi_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::MarkovHiWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x74 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::MarkovLoWatermarksReadVal`]; Write value: [`entropy_src::regs::MarkovLoWatermarksWriteVal`]
#[inline(always)]
pub fn markov_lo_watermarks(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::MarkovLoWatermarks, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x78 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn repcnt_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::RepcntTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x7c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn repcnts_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::RepcntsTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn adaptp_hi_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AdaptpHiTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x84 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn adaptp_lo_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AdaptpLoTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x88 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn bucket_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::BucketTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x8c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn markov_hi_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::MarkovHiTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x90 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn markov_lo_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::MarkovLoTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x94 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn extht_hi_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtHiTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x98 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn extht_lo_total_fails(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtLoTotalFails, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x9c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AlertThresholdReadVal`]; Write value: [`entropy_src::regs::AlertThresholdWriteVal`]
#[inline(always)]
pub fn alert_threshold(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AlertThreshold, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AlertSummaryFailCountsReadVal`]; Write value: [`entropy_src::regs::AlertSummaryFailCountsWriteVal`]
#[inline(always)]
pub fn alert_summary_fail_counts(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AlertSummaryFailCounts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::AlertFailCountsReadVal`]; Write value: [`entropy_src::regs::AlertFailCountsWriteVal`]
#[inline(always)]
pub fn alert_fail_counts(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::AlertFailCounts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xa8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ExthtFailCountsReadVal`]; Write value: [`entropy_src::regs::ExthtFailCountsWriteVal`]
#[inline(always)]
pub fn extht_fail_counts(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ExthtFailCounts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xac / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::FwOvControlReadVal`]; Write value: [`entropy_src::regs::FwOvControlWriteVal`]
#[inline(always)]
pub fn fw_ov_control(&self) -> ureg::RegRef<crate::entropy_src::meta::FwOvControl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::FwOvSha3StartReadVal`]; Write value: [`entropy_src::regs::FwOvSha3StartWriteVal`]
#[inline(always)]
pub fn fw_ov_sha3_start(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::FwOvSha3Start, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::FwOvWrFifoFullReadVal`]; Write value: [`entropy_src::regs::FwOvWrFifoFullWriteVal`]
#[inline(always)]
pub fn fw_ov_wr_fifo_full(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::FwOvWrFifoFull, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xb8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::FwOvRdFifoOverflowReadVal`]; Write value: [`entropy_src::regs::FwOvRdFifoOverflowWriteVal`]
#[inline(always)]
pub fn fw_ov_rd_fifo_overflow(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::FwOvRdFifoOverflow, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xbc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_ov_rd_data(&self) -> ureg::RegRef<crate::entropy_src::meta::FwOvRdData, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn fw_ov_wr_data(&self) -> ureg::RegRef<crate::entropy_src::meta::FwOvWrData, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ObserveFifoThreshReadVal`]; Write value: [`entropy_src::regs::ObserveFifoThreshWriteVal`]
#[inline(always)]
pub fn observe_fifo_thresh(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ObserveFifoThresh, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ObserveFifoDepthReadVal`]; Write value: [`entropy_src::regs::ObserveFifoDepthWriteVal`]
#[inline(always)]
pub fn observe_fifo_depth(
&self,
) -> ureg::RegRef<crate::entropy_src::meta::ObserveFifoDepth, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xcc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::DebugStatusReadVal`]; Write value: [`entropy_src::regs::DebugStatusWriteVal`]
#[inline(always)]
pub fn debug_status(&self) -> ureg::RegRef<crate::entropy_src::meta::DebugStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xd0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::RecovAlertStsReadVal`]; Write value: [`entropy_src::regs::RecovAlertStsWriteVal`]
#[inline(always)]
pub fn recov_alert_sts(&self) -> ureg::RegRef<crate::entropy_src::meta::RecovAlertSts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xd4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ErrCodeReadVal`]; Write value: [`entropy_src::regs::ErrCodeWriteVal`]
#[inline(always)]
pub fn err_code(&self) -> ureg::RegRef<crate::entropy_src::meta::ErrCode, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xd8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::ErrCodeTestReadVal`]; Write value: [`entropy_src::regs::ErrCodeTestWriteVal`]
#[inline(always)]
pub fn err_code_test(&self) -> ureg::RegRef<crate::entropy_src::meta::ErrCodeTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xdc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`entropy_src::regs::MainSmStateReadVal`]; Write value: [`entropy_src::regs::MainSmStateWriteVal`]
#[inline(always)]
pub fn main_sm_state(&self) -> ureg::RegRef<crate::entropy_src::meta::MainSmState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xe0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AdaptpHiThresholdsReadVal(u32);
impl AdaptpHiThresholdsReadVal {
/// This is the threshold size for the adaptive proportion health test.
/// This value is used in FIPS mode.
/// This register must be written before the module is enabled.
/// Writing to this register will only update the register if the
/// written value is less than the current value of this register.
/// A read from this register always reflects the current value.
#[inline(always)]
pub fn fips_thresh(&self) -> u32 {
(self.0 >> 0) & 0xffff
}
/// This is the threshold size for the adaptive proportion health test
/// running in bypass mode. This mode is active after reset for the
/// first and only test run, or when this mode is programmed by firmware.
/// This register must be written before the module is enabled.
/// Writing to this register will only update the register if the
/// written value is less than the current value of this register.
/// A read from this register always reflects the current value.
#[inline(always)]
pub fn bypass_thresh(&self) -> u32 {
(self.0 >> 16) & 0xffff
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> AdaptpHiThresholdsWriteVal {
AdaptpHiThresholdsWriteVal(self.0)
}
}
impl From<u32> for AdaptpHiThresholdsReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AdaptpHiThresholdsReadVal> for u32 {
#[inline(always)]
fn from(val: AdaptpHiThresholdsReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct AdaptpHiThresholdsWriteVal(u32);
impl AdaptpHiThresholdsWriteVal {
/// This is the threshold size for the adaptive proportion health test.
/// This value is used in FIPS mode.
/// This register must be written before the module is enabled.
/// Writing to this register will only update the register if the
/// written value is less than the current value of this register.
/// A read from this register always reflects the current value.
#[inline(always)]
pub fn fips_thresh(self, val: u32) -> Self {
Self((self.0 & !(0xffff << 0)) | ((val & 0xffff) << 0))
}
/// This is the threshold size for the adaptive proportion health test
/// running in bypass mode. This mode is active after reset for the
/// first and only test run, or when this mode is programmed by firmware.
/// This register must be written before the module is enabled.
/// Writing to this register will only update the register if the
/// written value is less than the current value of this register.
/// A read from this register always reflects the current value.
#[inline(always)]
pub fn bypass_thresh(self, val: u32) -> Self {
Self((self.0 & !(0xffff << 16)) | ((val & 0xffff) << 16))
}
}
impl From<u32> for AdaptpHiThresholdsWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AdaptpHiThresholdsWriteVal> for u32 {
#[inline(always)]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/uart.rs | hw/latest/registers/src/uart.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 9f80a2bebb755233696929bf1da5ca0b90eba9a1
//
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct Uart {
_priv: (),
}
impl Uart {
pub const PTR: *mut u32 = 0x20001000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`uart::regs::InterruptStateReadVal`]; Write value: [`uart::regs::InterruptStateWriteVal`]
#[inline(always)]
pub fn interrupt_state(&self) -> ureg::RegRef<crate::uart::meta::InterruptState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::InterruptEnableReadVal`]; Write value: [`uart::regs::InterruptEnableWriteVal`]
#[inline(always)]
pub fn interrupt_enable(&self) -> ureg::RegRef<crate::uart::meta::InterruptEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::InterruptTestReadVal`]; Write value: [`uart::regs::InterruptTestWriteVal`]
#[inline(always)]
pub fn interrupt_test(&self) -> ureg::RegRef<crate::uart::meta::InterruptTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::AlertTestReadVal`]; Write value: [`uart::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::uart::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::CtrlReadVal`]; Write value: [`uart::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::uart::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::StatusReadVal`]; Write value: [`uart::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::uart::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::RdataReadVal`]; Write value: [`uart::regs::RdataWriteVal`]
#[inline(always)]
pub fn rdata(&self) -> ureg::RegRef<crate::uart::meta::Rdata, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::WdataReadVal`]; Write value: [`uart::regs::WdataWriteVal`]
#[inline(always)]
pub fn wdata(&self) -> ureg::RegRef<crate::uart::meta::Wdata, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::FifoCtrlReadVal`]; Write value: [`uart::regs::FifoCtrlWriteVal`]
#[inline(always)]
pub fn fifo_ctrl(&self) -> ureg::RegRef<crate::uart::meta::FifoCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::FifoStatusReadVal`]; Write value: [`uart::regs::FifoStatusWriteVal`]
#[inline(always)]
pub fn fifo_status(&self) -> ureg::RegRef<crate::uart::meta::FifoStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::OvrdReadVal`]; Write value: [`uart::regs::OvrdWriteVal`]
#[inline(always)]
pub fn ovrd(&self) -> ureg::RegRef<crate::uart::meta::Ovrd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::ValReadVal`]; Write value: [`uart::regs::ValWriteVal`]
#[inline(always)]
pub fn val(&self) -> ureg::RegRef<crate::uart::meta::Val, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`uart::regs::TimeoutCtrlReadVal`]; Write value: [`uart::regs::TimeoutCtrlWriteVal`]
#[inline(always)]
pub fn timeout_ctrl(&self) -> ureg::RegRef<crate::uart::meta::TimeoutCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AlertTestWriteVal(u32);
impl AlertTestWriteVal {
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_fault(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for AlertTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AlertTestWriteVal> for u32 {
#[inline(always)]
fn from(val: AlertTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlReadVal(u32);
impl CtrlReadVal {
/// TX enable
#[inline(always)]
pub fn tx(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// RX enable
#[inline(always)]
pub fn rx(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// RX noise filter enable.
/// If the noise filter is enabled, RX line goes through the 3-tap
/// repetition code. It ignores single IP clock period noise.
#[inline(always)]
pub fn nf(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// System loopback enable.
///
/// If this bit is turned on, any outgoing bits to TX are received through RX.
/// See Block Diagram. Note that the TX line goes 1 if System loopback is enabled.
#[inline(always)]
pub fn slpbk(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Line loopback enable.
///
/// If this bit is turned on, incoming bits are forwarded to TX for testing purpose.
/// See Block Diagram. Note that the internal design sees RX value as 1 always if line
/// loopback is enabled.
#[inline(always)]
pub fn llpbk(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// If true, parity is enabled in both RX and TX directions.
#[inline(always)]
pub fn parity_en(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// If PARITY_EN is true, this determines the type, 1 for odd parity, 0 for even.
#[inline(always)]
pub fn parity_odd(&self) -> bool {
((self.0 >> 7) & 1) != 0
}
/// Trigger level for RX break detection. Sets the number of character
/// times the line must be low to detect a break.
#[inline(always)]
pub fn rxblvl(&self) -> u32 {
(self.0 >> 8) & 3
}
/// BAUD clock rate control.
#[inline(always)]
pub fn nco(&self) -> u32 {
(self.0 >> 16) & 0xffff
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlWriteVal {
CtrlWriteVal(self.0)
}
}
impl From<u32> for CtrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlWriteVal(u32);
impl CtrlWriteVal {
/// TX enable
#[inline(always)]
pub fn tx(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// RX enable
#[inline(always)]
pub fn rx(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// RX noise filter enable.
/// If the noise filter is enabled, RX line goes through the 3-tap
/// repetition code. It ignores single IP clock period noise.
#[inline(always)]
pub fn nf(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// System loopback enable.
///
/// If this bit is turned on, any outgoing bits to TX are received through RX.
/// See Block Diagram. Note that the TX line goes 1 if System loopback is enabled.
#[inline(always)]
pub fn slpbk(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Line loopback enable.
///
/// If this bit is turned on, incoming bits are forwarded to TX for testing purpose.
/// See Block Diagram. Note that the internal design sees RX value as 1 always if line
/// loopback is enabled.
#[inline(always)]
pub fn llpbk(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
/// If true, parity is enabled in both RX and TX directions.
#[inline(always)]
pub fn parity_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
/// If PARITY_EN is true, this determines the type, 1 for odd parity, 0 for even.
#[inline(always)]
pub fn parity_odd(self, val: bool) -> Self {
Self((self.0 & !(1 << 7)) | (u32::from(val) << 7))
}
/// Trigger level for RX break detection. Sets the number of character
/// times the line must be low to detect a break.
#[inline(always)]
pub fn rxblvl(self, val: u32) -> Self {
Self((self.0 & !(3 << 8)) | ((val & 3) << 8))
}
/// BAUD clock rate control.
#[inline(always)]
pub fn nco(self, val: u32) -> Self {
Self((self.0 & !(0xffff << 16)) | ((val & 0xffff) << 16))
}
}
impl From<u32> for CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct FifoCtrlReadVal(u32);
impl FifoCtrlReadVal {
/// RX fifo reset. Write 1 to the register resets RX_FIFO. Read returns 0
#[inline(always)]
pub fn rxrst(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// TX fifo reset. Write 1 to the register resets TX_FIFO. Read returns 0
#[inline(always)]
pub fn txrst(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Trigger level for RX interrupts. If the FIFO depth is greater than or equal to
/// the setting, it raises rx_watermark interrupt.
#[inline(always)]
pub fn rxilvl(&self) -> u32 {
(self.0 >> 2) & 7
}
/// Trigger level for TX interrupts. If the FIFO depth is less than the setting, it
/// raises tx_watermark interrupt.
#[inline(always)]
pub fn txilvl(&self) -> u32 {
(self.0 >> 5) & 3
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> FifoCtrlWriteVal {
FifoCtrlWriteVal(self.0)
}
}
impl From<u32> for FifoCtrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<FifoCtrlReadVal> for u32 {
#[inline(always)]
fn from(val: FifoCtrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct FifoCtrlWriteVal(u32);
impl FifoCtrlWriteVal {
/// RX fifo reset. Write 1 to the register resets RX_FIFO. Read returns 0
#[inline(always)]
pub fn rxrst(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// TX fifo reset. Write 1 to the register resets TX_FIFO. Read returns 0
#[inline(always)]
pub fn txrst(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Trigger level for RX interrupts. If the FIFO depth is greater than or equal to
/// the setting, it raises rx_watermark interrupt.
#[inline(always)]
pub fn rxilvl(self, val: u32) -> Self {
Self((self.0 & !(7 << 2)) | ((val & 7) << 2))
}
/// Trigger level for TX interrupts. If the FIFO depth is less than the setting, it
/// raises tx_watermark interrupt.
#[inline(always)]
pub fn txilvl(self, val: u32) -> Self {
Self((self.0 & !(3 << 5)) | ((val & 3) << 5))
}
}
impl From<u32> for FifoCtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<FifoCtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: FifoCtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct FifoStatusReadVal(u32);
impl FifoStatusReadVal {
/// Current fill level of TX fifo
#[inline(always)]
pub fn txlvl(&self) -> u32 {
(self.0 >> 0) & 0x3f
}
/// Current fill level of RX fifo
#[inline(always)]
pub fn rxlvl(&self) -> u32 {
(self.0 >> 16) & 0x3f
}
}
impl From<u32> for FifoStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<FifoStatusReadVal> for u32 {
#[inline(always)]
fn from(val: FifoStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct InterruptEnableReadVal(u32);
impl InterruptEnableReadVal {
/// Enable interrupt when tx_watermark is set.
#[inline(always)]
pub fn tx_watermark(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable interrupt when rx_watermark is set.
#[inline(always)]
pub fn rx_watermark(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable interrupt when tx_empty is set.
#[inline(always)]
pub fn tx_empty(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable interrupt when rx_overflow is set.
#[inline(always)]
pub fn rx_overflow(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Enable interrupt when rx_frame_err is set.
#[inline(always)]
pub fn rx_frame_err(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Enable interrupt when rx_break_err is set.
#[inline(always)]
pub fn rx_break_err(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// Enable interrupt when rx_timeout is set.
#[inline(always)]
pub fn rx_timeout(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// Enable interrupt when rx_parity_err is set.
#[inline(always)]
pub fn rx_parity_err(&self) -> bool {
((self.0 >> 7) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> InterruptEnableWriteVal {
InterruptEnableWriteVal(self.0)
}
}
impl From<u32> for InterruptEnableReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<InterruptEnableReadVal> for u32 {
#[inline(always)]
fn from(val: InterruptEnableReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct InterruptEnableWriteVal(u32);
impl InterruptEnableWriteVal {
/// Enable interrupt when tx_watermark is set.
#[inline(always)]
pub fn tx_watermark(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Enable interrupt when rx_watermark is set.
#[inline(always)]
pub fn rx_watermark(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Enable interrupt when tx_empty is set.
#[inline(always)]
pub fn tx_empty(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Enable interrupt when rx_overflow is set.
#[inline(always)]
pub fn rx_overflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Enable interrupt when rx_frame_err is set.
#[inline(always)]
pub fn rx_frame_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Enable interrupt when rx_break_err is set.
#[inline(always)]
pub fn rx_break_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
/// Enable interrupt when rx_timeout is set.
#[inline(always)]
pub fn rx_timeout(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
/// Enable interrupt when rx_parity_err is set.
#[inline(always)]
pub fn rx_parity_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 7)) | (u32::from(val) << 7))
}
}
impl From<u32> for InterruptEnableWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<InterruptEnableWriteVal> for u32 {
#[inline(always)]
fn from(val: InterruptEnableWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct InterruptStateReadVal(u32);
impl InterruptStateReadVal {
/// raised if the transmit FIFO is past the high-water mark.
#[inline(always)]
pub fn tx_watermark(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// raised if the receive FIFO is past the high-water mark.
#[inline(always)]
pub fn rx_watermark(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// raised if the transmit FIFO has emptied and no transmit is ongoing.
#[inline(always)]
pub fn tx_empty(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// raised if the receive FIFO has overflowed.
#[inline(always)]
pub fn rx_overflow(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// raised if a framing error has been detected on receive.
#[inline(always)]
pub fn rx_frame_err(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// raised if break condition has been detected on receive.
#[inline(always)]
pub fn rx_break_err(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// raised if RX FIFO has characters remaining in the FIFO without being
/// retrieved for the programmed time period.
#[inline(always)]
pub fn rx_timeout(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// raised if the receiver has detected a parity error.
#[inline(always)]
pub fn rx_parity_err(&self) -> bool {
((self.0 >> 7) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> InterruptStateWriteVal {
InterruptStateWriteVal(self.0)
}
}
impl From<u32> for InterruptStateReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<InterruptStateReadVal> for u32 {
#[inline(always)]
fn from(val: InterruptStateReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct InterruptStateWriteVal(u32);
impl InterruptStateWriteVal {
/// raised if the transmit FIFO is past the high-water mark.
#[inline(always)]
pub fn tx_watermark(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// raised if the receive FIFO is past the high-water mark.
#[inline(always)]
pub fn rx_watermark(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// raised if the transmit FIFO has emptied and no transmit is ongoing.
#[inline(always)]
pub fn tx_empty(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// raised if the receive FIFO has overflowed.
#[inline(always)]
pub fn rx_overflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// raised if a framing error has been detected on receive.
#[inline(always)]
pub fn rx_frame_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// raised if break condition has been detected on receive.
#[inline(always)]
pub fn rx_break_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
/// raised if RX FIFO has characters remaining in the FIFO without being
/// retrieved for the programmed time period.
#[inline(always)]
pub fn rx_timeout(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
/// raised if the receiver has detected a parity error.
#[inline(always)]
pub fn rx_parity_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 7)) | (u32::from(val) << 7))
}
}
impl From<u32> for InterruptStateWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<InterruptStateWriteVal> for u32 {
#[inline(always)]
fn from(val: InterruptStateWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct InterruptTestWriteVal(u32);
impl InterruptTestWriteVal {
/// Write 1 to force tx_watermark to 1.
#[inline(always)]
pub fn tx_watermark(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Write 1 to force rx_watermark to 1.
#[inline(always)]
pub fn rx_watermark(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Write 1 to force tx_empty to 1.
#[inline(always)]
pub fn tx_empty(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Write 1 to force rx_overflow to 1.
#[inline(always)]
pub fn rx_overflow(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Write 1 to force rx_frame_err to 1.
#[inline(always)]
pub fn rx_frame_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
/// Write 1 to force rx_break_err to 1.
#[inline(always)]
pub fn rx_break_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 5)) | (u32::from(val) << 5))
}
/// Write 1 to force rx_timeout to 1.
#[inline(always)]
pub fn rx_timeout(self, val: bool) -> Self {
Self((self.0 & !(1 << 6)) | (u32::from(val) << 6))
}
/// Write 1 to force rx_parity_err to 1.
#[inline(always)]
pub fn rx_parity_err(self, val: bool) -> Self {
Self((self.0 & !(1 << 7)) | (u32::from(val) << 7))
}
}
impl From<u32> for InterruptTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<InterruptTestWriteVal> for u32 {
#[inline(always)]
fn from(val: InterruptTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct OvrdReadVal(u32);
impl OvrdReadVal {
/// Enable TX pin override control
#[inline(always)]
pub fn txen(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Write to set the value of the TX pin
#[inline(always)]
pub fn txval(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> OvrdWriteVal {
OvrdWriteVal(self.0)
}
}
impl From<u32> for OvrdReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<OvrdReadVal> for u32 {
#[inline(always)]
fn from(val: OvrdReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct OvrdWriteVal(u32);
impl OvrdWriteVal {
/// Enable TX pin override control
#[inline(always)]
pub fn txen(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Write to set the value of the TX pin
#[inline(always)]
pub fn txval(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for OvrdWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<OvrdWriteVal> for u32 {
#[inline(always)]
fn from(val: OvrdWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct RdataReadVal(u32);
impl RdataReadVal {
/// UART read data
#[inline(always)]
pub fn rdata(&self) -> u32 {
(self.0 >> 0) & 0xff
}
}
impl From<u32> for RdataReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<RdataReadVal> for u32 {
#[inline(always)]
fn from(val: RdataReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// TX buffer is full
#[inline(always)]
pub fn txfull(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// RX buffer is full
#[inline(always)]
pub fn rxfull(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// TX FIFO is empty
#[inline(always)]
pub fn txempty(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// TX FIFO is empty and all bits have been transmitted
#[inline(always)]
pub fn txidle(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// RX is idle
#[inline(always)]
pub fn rxidle(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// RX FIFO is empty
#[inline(always)]
pub fn rxempty(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct TimeoutCtrlReadVal(u32);
impl TimeoutCtrlReadVal {
/// RX timeout value in UART bit times
#[inline(always)]
pub fn val(&self) -> u32 {
(self.0 >> 0) & 0xffffff
}
/// Enable RX timeout feature
#[inline(always)]
pub fn en(&self) -> bool {
((self.0 >> 31) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> TimeoutCtrlWriteVal {
TimeoutCtrlWriteVal(self.0)
}
}
impl From<u32> for TimeoutCtrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<TimeoutCtrlReadVal> for u32 {
#[inline(always)]
fn from(val: TimeoutCtrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct TimeoutCtrlWriteVal(u32);
impl TimeoutCtrlWriteVal {
/// RX timeout value in UART bit times
#[inline(always)]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/aes.rs | hw/latest/registers/src/aes.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct AesReg {
_priv: (),
}
impl AesReg {
pub const PTR: *mut u32 = 0x10011000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn key_share0(&self) -> ureg::Array<8, ureg::RegRef<crate::aes::meta::KeyShare0, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn key_share1(&self) -> ureg::Array<8, ureg::RegRef<crate::aes::meta::KeyShare1, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn iv(&self) -> ureg::Array<4, ureg::RegRef<crate::aes::meta::Iv, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn data_in(&self) -> ureg::Array<4, ureg::RegRef<crate::aes::meta::DataIn, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x54 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn data_out(&self) -> ureg::Array<4, ureg::RegRef<crate::aes::meta::DataOut, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x64 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`aes::regs::CtrlShadowedReadVal`]; Write value: [`aes::regs::CtrlShadowedWriteVal`]
#[inline(always)]
pub fn ctrl_shadowed(&self) -> ureg::RegRef<crate::aes::meta::CtrlShadowed, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x74 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`aes::regs::CtrlAuxShadowedReadVal`]; Write value: [`aes::regs::CtrlAuxShadowedWriteVal`]
#[inline(always)]
pub fn ctrl_aux_shadowed(&self) -> ureg::RegRef<crate::aes::meta::CtrlAuxShadowed, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x78 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`aes::regs::CtrlAuxRegwenReadVal`]; Write value: [`aes::regs::CtrlAuxRegwenWriteVal`]
#[inline(always)]
pub fn ctrl_aux_regwen(&self) -> ureg::RegRef<crate::aes::meta::CtrlAuxRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x7c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`aes::regs::TriggerReadVal`]; Write value: [`aes::regs::TriggerWriteVal`]
#[inline(always)]
pub fn trigger(&self) -> ureg::RegRef<crate::aes::meta::Trigger, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`aes::regs::StatusReadVal`]; Write value: [`aes::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::aes::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x84 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`aes::regs::CtrlGcmShadowedReadVal`]; Write value: [`aes::regs::CtrlGcmShadowedWriteVal`]
#[inline(always)]
pub fn ctrl_gcm_shadowed(&self) -> ureg::RegRef<crate::aes::meta::CtrlGcmShadowed, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x88 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct CtrlAuxRegwenReadVal(u32);
impl CtrlAuxRegwenReadVal {
/// Auxiliary Control Register configuration enable
/// bit. If this is cleared to 0, the Auxiliary Control
/// Register cannot be written anymore.
#[inline(always)]
pub fn ctrl_aux_regwen(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlAuxRegwenWriteVal {
CtrlAuxRegwenWriteVal(self.0)
}
}
impl From<u32> for CtrlAuxRegwenReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlAuxRegwenReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlAuxRegwenReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlAuxRegwenWriteVal(u32);
impl CtrlAuxRegwenWriteVal {
/// Auxiliary Control Register configuration enable
/// bit. If this is cleared to 0, the Auxiliary Control
/// Register cannot be written anymore.
#[inline(always)]
pub fn ctrl_aux_regwen(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for CtrlAuxRegwenWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlAuxRegwenWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlAuxRegwenWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlAuxShadowedReadVal(u32);
impl CtrlAuxShadowedReadVal {
/// Controls whether providing a new key triggers the reseeding
/// of internal pseudo-random number generators used for clearing and
/// masking (1) or not (0).
#[inline(always)]
pub fn key_touch_forces_reseed(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Allow the internal masking PRNG to advance (0) or
/// force its internal state (1) leading to constant masks.
/// Setting all masks to constant value can be useful when
/// performing SCA. To completely disable the masking, the
/// second key share (KEY_SHARE1_0 - KEY_SHARE1_7) must be
/// zero as well. In addition, a special seed needs to be
/// loaded into the masking PRNG using the EDN interface.
/// Only applicable if both the Masking parameter and the
/// SecAllowForcingMasks parameter are set to one.
#[inline(always)]
pub fn force_masks(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlAuxShadowedWriteVal {
CtrlAuxShadowedWriteVal(self.0)
}
}
impl From<u32> for CtrlAuxShadowedReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlAuxShadowedReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlAuxShadowedReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlAuxShadowedWriteVal(u32);
impl CtrlAuxShadowedWriteVal {
/// Controls whether providing a new key triggers the reseeding
/// of internal pseudo-random number generators used for clearing and
/// masking (1) or not (0).
#[inline(always)]
pub fn key_touch_forces_reseed(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Allow the internal masking PRNG to advance (0) or
/// force its internal state (1) leading to constant masks.
/// Setting all masks to constant value can be useful when
/// performing SCA. To completely disable the masking, the
/// second key share (KEY_SHARE1_0 - KEY_SHARE1_7) must be
/// zero as well. In addition, a special seed needs to be
/// loaded into the masking PRNG using the EDN interface.
/// Only applicable if both the Masking parameter and the
/// SecAllowForcingMasks parameter are set to one.
#[inline(always)]
pub fn force_masks(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for CtrlAuxShadowedWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlAuxShadowedWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlAuxShadowedWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlGcmShadowedReadVal(u32);
impl CtrlGcmShadowedReadVal {
/// 6-bit one-hot field to select the phase of the
/// Galois/Counter Mode (GCM) of operation. Invalid input
/// values, i.e., values with multiple bits set and value
/// 6'b00_0000, are mapped to GCM_INIT (6'b00_0001). In case
/// support for GCM has been disabled at compile time, this
/// field is not writable and always reads as GCM_INIT
/// (6'b00_0001).
#[inline(always)]
pub fn phase(&self) -> u32 {
(self.0 >> 0) & 0x3f
}
/// Number of valid bytes of the current input block.
/// Only the last block in the GCM_AAD and GCM_TEXT phases are
/// expected to have not all bytes marked as valid. For all
/// other blocks, the number of valid bytes should be set to 16.
/// Invalid input values, i.e., the value 5'b0_0000, and all
/// other values different from 5'b1_0000 in case GCM is not
/// supported (because disabled at compile time) are mapped to
/// 5'b1_0000.
#[inline(always)]
pub fn num_valid_bytes(&self) -> u32 {
(self.0 >> 6) & 0x1f
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlGcmShadowedWriteVal {
CtrlGcmShadowedWriteVal(self.0)
}
}
impl From<u32> for CtrlGcmShadowedReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlGcmShadowedReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlGcmShadowedReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlGcmShadowedWriteVal(u32);
impl CtrlGcmShadowedWriteVal {
/// 6-bit one-hot field to select the phase of the
/// Galois/Counter Mode (GCM) of operation. Invalid input
/// values, i.e., values with multiple bits set and value
/// 6'b00_0000, are mapped to GCM_INIT (6'b00_0001). In case
/// support for GCM has been disabled at compile time, this
/// field is not writable and always reads as GCM_INIT
/// (6'b00_0001).
#[inline(always)]
pub fn phase(self, val: u32) -> Self {
Self((self.0 & !(0x3f << 0)) | ((val & 0x3f) << 0))
}
/// Number of valid bytes of the current input block.
/// Only the last block in the GCM_AAD and GCM_TEXT phases are
/// expected to have not all bytes marked as valid. For all
/// other blocks, the number of valid bytes should be set to 16.
/// Invalid input values, i.e., the value 5'b0_0000, and all
/// other values different from 5'b1_0000 in case GCM is not
/// supported (because disabled at compile time) are mapped to
/// 5'b1_0000.
#[inline(always)]
pub fn num_valid_bytes(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 6)) | ((val & 0x1f) << 6))
}
}
impl From<u32> for CtrlGcmShadowedWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlGcmShadowedWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlGcmShadowedWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlShadowedReadVal(u32);
impl CtrlShadowedReadVal {
/// 2-bit one-hot field to select the operation of AES
/// unit. Invalid input values, i.e., values with multiple
/// bits set and value 2'b00, are mapped to AES_ENC (2'b01).
#[inline(always)]
pub fn operation(&self) -> u32 {
(self.0 >> 0) & 3
}
/// 6-bit one-hot field to select AES block cipher
/// mode. Invalid input values, i.e., values with multiple
/// bits set and value 6'b00_0000, are mapped to AES_NONE
/// (6'b11_1111).
#[inline(always)]
pub fn mode(&self) -> u32 {
(self.0 >> 2) & 0x3f
}
/// 3-bit one-hot field to select AES key length.
/// Invalid input values, i.e., values with multiple bits set,
/// value 3'b000, and value 3'b010 in case 192-bit keys are
/// not supported (because disabled at compile time) are
/// mapped to AES_256 (3'b100).
#[inline(always)]
pub fn key_len(&self) -> u32 {
(self.0 >> 8) & 7
}
/// Controls whether the AES unit uses the key
/// provided by the key manager via key sideload interface (1)
/// or the key provided by software via Initial Key Registers
/// KEY_SHARE1_0 - KEY_SHARE1_7 (0).
#[inline(always)]
pub fn sideload(&self) -> bool {
((self.0 >> 11) & 1) != 0
}
/// 3-bit one-hot field to control the reseeding rate
/// of the internal pseudo-random number generator (PRNG) used
/// for masking. Invalid input values, i.e., values with
/// multiple bits set and value 3'b000 are mapped to the
/// highest reseeding rate PER_1 (3'b001).
#[inline(always)]
pub fn prng_reseed_rate(&self) -> u32 {
(self.0 >> 12) & 7
}
/// Controls whether the AES unit is operated in
/// normal/automatic mode (0) or fully manual mode (1). In
/// automatic mode (0), the AES unit automatically i) starts
/// to encrypt/decrypt when it receives new input data, and
/// ii) stalls during the last encryption/decryption cycle if
/// the previous output data has not yet been read. This is
/// the most efficient mode to operate in. Note that the
/// corresponding status tracking is automatically cleared
/// upon a write to the Control Register. In manual mode (1),
/// the AES unit i) only starts to encrypt/decrypt after
/// receiving a start trigger (see Trigger Register), and ii)
/// overwrites previous output data irrespective of whether it
/// has been read out or not. This mode is useful if software needs full
/// control over the AES unit.
#[inline(always)]
pub fn manual_operation(&self) -> bool {
((self.0 >> 15) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlShadowedWriteVal {
CtrlShadowedWriteVal(self.0)
}
}
impl From<u32> for CtrlShadowedReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlShadowedReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlShadowedReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlShadowedWriteVal(u32);
impl CtrlShadowedWriteVal {
/// 2-bit one-hot field to select the operation of AES
/// unit. Invalid input values, i.e., values with multiple
/// bits set and value 2'b00, are mapped to AES_ENC (2'b01).
#[inline(always)]
pub fn operation(self, val: u32) -> Self {
Self((self.0 & !(3 << 0)) | ((val & 3) << 0))
}
/// 6-bit one-hot field to select AES block cipher
/// mode. Invalid input values, i.e., values with multiple
/// bits set and value 6'b00_0000, are mapped to AES_NONE
/// (6'b11_1111).
#[inline(always)]
pub fn mode(self, val: u32) -> Self {
Self((self.0 & !(0x3f << 2)) | ((val & 0x3f) << 2))
}
/// 3-bit one-hot field to select AES key length.
/// Invalid input values, i.e., values with multiple bits set,
/// value 3'b000, and value 3'b010 in case 192-bit keys are
/// not supported (because disabled at compile time) are
/// mapped to AES_256 (3'b100).
#[inline(always)]
pub fn key_len(self, val: u32) -> Self {
Self((self.0 & !(7 << 8)) | ((val & 7) << 8))
}
/// Controls whether the AES unit uses the key
/// provided by the key manager via key sideload interface (1)
/// or the key provided by software via Initial Key Registers
/// KEY_SHARE1_0 - KEY_SHARE1_7 (0).
#[inline(always)]
pub fn sideload(self, val: bool) -> Self {
Self((self.0 & !(1 << 11)) | (u32::from(val) << 11))
}
/// 3-bit one-hot field to control the reseeding rate
/// of the internal pseudo-random number generator (PRNG) used
/// for masking. Invalid input values, i.e., values with
/// multiple bits set and value 3'b000 are mapped to the
/// highest reseeding rate PER_1 (3'b001).
#[inline(always)]
pub fn prng_reseed_rate(self, val: u32) -> Self {
Self((self.0 & !(7 << 12)) | ((val & 7) << 12))
}
/// Controls whether the AES unit is operated in
/// normal/automatic mode (0) or fully manual mode (1). In
/// automatic mode (0), the AES unit automatically i) starts
/// to encrypt/decrypt when it receives new input data, and
/// ii) stalls during the last encryption/decryption cycle if
/// the previous output data has not yet been read. This is
/// the most efficient mode to operate in. Note that the
/// corresponding status tracking is automatically cleared
/// upon a write to the Control Register. In manual mode (1),
/// the AES unit i) only starts to encrypt/decrypt after
/// receiving a start trigger (see Trigger Register), and ii)
/// overwrites previous output data irrespective of whether it
/// has been read out or not. This mode is useful if software needs full
/// control over the AES unit.
#[inline(always)]
pub fn manual_operation(self, val: bool) -> Self {
Self((self.0 & !(1 << 15)) | (u32::from(val) << 15))
}
}
impl From<u32> for CtrlShadowedWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlShadowedWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlShadowedWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// The AES unit is idle (1) or busy (0). This flag
/// is `0` if one of the following operations is currently
/// running: i) encryption/decryption, ii) register clearing or
/// iii) PRNG reseeding. This flag is also `0` if an
/// encryption/decryption is running but the AES unit is
/// stalled.
#[inline(always)]
pub fn idle(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// The AES unit is not stalled (0) or stalled (1)
/// because there is previous output data that must be read by
/// the processor before the AES unit can overwrite this data.
/// This flag is not meaningful if MANUAL_OPERATION=1 (see
/// Control Register).
#[inline(always)]
pub fn stall(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// All previous output data has been fully read by
/// the processor (0) or at least one previous output data block
/// has been lost (1). It has been overwritten by the AES unit
/// before the processor could fully read it. Once set to `1`,
/// this flag remains set until AES operation is restarted by
/// re-writing the Control Register. The primary use of this
/// flag is for design verification. This flag is not
/// meaningful if MANUAL_OPERATION=0 (see Control Register).
#[inline(always)]
pub fn output_lost(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// The AES unit has no valid output (0) or has valid output data (1).
#[inline(always)]
pub fn output_valid(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// The AES unit is ready (1) or not ready (0) to
/// receive new data input via the DATA_IN registers. If the
/// present values in the DATA_IN registers have not yet been
/// loaded into the module this flag is `0` (not ready).
#[inline(always)]
pub fn input_ready(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// An update error has not occurred (0) or has
/// occurred (1) in the shadowed Control Register. AES
/// operation needs to be restarted by re-writing the Control
/// Register.
#[inline(always)]
pub fn alert_recov_ctrl_update_err(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// No fatal fault has occurred inside the AES unit
/// (0). A fatal fault has occurred and the AES unit needs to
/// be reset (1). Examples for fatal faults include i) storage
/// errors in the Control Register, ii) if any internal FSM
/// enters an invalid state, iii) if any sparsely encoded signal
/// takes on an invalid value, iv) errors in the internal round
/// counter, v) escalations triggered by the life cycle
/// controller, and vi) fatal integrity failures on the TL-UL bus.
#[inline(always)]
pub fn alert_fatal_fault(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct TriggerWriteVal(u32);
impl TriggerWriteVal {
/// Keep AES unit paused (0) or trigger the
/// encryption/decryption of one data block (1). This trigger
/// is cleared to `0` if MANUAL_OPERATION=0 or if MODE=AES_NONE
/// (see Control Register).
#[inline(always)]
pub fn start(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Keep current values in Initial Key, internal Full
/// Key and Decryption Key registers, IV registers and Input
/// Data registers (0) or clear all those registers with
/// pseudo-random data (1).
#[inline(always)]
pub fn key_iv_data_in_clear(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Keep current values in Output Data registers (0) or
/// clear those registers with pseudo-random data (1).
#[inline(always)]
pub fn data_out_clear(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Keep continuing with the current states of the
/// internal pseudo-random number generators used for register
/// clearing and masking (0) or perform a reseed of the internal
/// states from the connected entropy source (1). If the
/// KEY_TOUCH_FORCES_RESEED bit in the Auxiliary Control
/// Register is set to one, this trigger will automatically get
/// set after providing a new initial key.
#[inline(always)]
pub fn prng_reseed(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for TriggerWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<TriggerWriteVal> for u32 {
#[inline(always)]
fn from(val: TriggerWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type KeyShare0 = ureg::WriteOnlyReg32<0, u32>;
pub type KeyShare1 = ureg::WriteOnlyReg32<0, u32>;
pub type Iv = ureg::ReadWriteReg32<0, u32, u32>;
pub type DataIn = ureg::WriteOnlyReg32<0, u32>;
pub type DataOut = ureg::ReadOnlyReg32<u32>;
pub type CtrlShadowed = ureg::ReadWriteReg32<
0,
crate::aes::regs::CtrlShadowedReadVal,
crate::aes::regs::CtrlShadowedWriteVal,
>;
pub type CtrlAuxShadowed = ureg::ReadWriteReg32<
0,
crate::aes::regs::CtrlAuxShadowedReadVal,
crate::aes::regs::CtrlAuxShadowedWriteVal,
>;
pub type CtrlAuxRegwen = ureg::ReadWriteReg32<
0,
crate::aes::regs::CtrlAuxRegwenReadVal,
crate::aes::regs::CtrlAuxRegwenWriteVal,
>;
pub type Trigger = ureg::WriteOnlyReg32<0, crate::aes::regs::TriggerWriteVal>;
pub type Status = ureg::ReadOnlyReg32<crate::aes::regs::StatusReadVal>;
pub type CtrlGcmShadowed = ureg::ReadWriteReg32<
0,
crate::aes::regs::CtrlGcmShadowedReadVal,
crate::aes::regs::CtrlGcmShadowedWriteVal,
>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/doe.rs | hw/latest/registers/src/doe.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct DoeReg {
_priv: (),
}
impl DoeReg {
pub const PTR: *mut u32 = 0x10000000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// 4 32-bit registers storing the 128-bit IV.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn iv(&self) -> ureg::Array<4, ureg::RegRef<crate::doe::meta::Iv, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the de-obfuscation command to run
///
/// Read value: [`doe::regs::CtrlReadVal`]; Write value: [`doe::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::doe::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides status of the DOE block and the status of the flows it runs
///
/// Read value: [`doe::regs::StatusReadVal`]; Write value: [`doe::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::doe::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::ErrorIntrEnTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::NotifIntrEnTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::NotifIntrTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::NotifIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error0_intr_count_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError0IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error1_intr_count_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError1IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error0_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError0IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error1_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError1IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::doe::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct CtrlReadVal(u32);
impl CtrlReadVal {
/// Indicates the command for DOE to run. Additional command encodings in the CMD_EXT field are combined with this field to define the full command.
#[inline(always)]
pub fn cmd(&self) -> super::enums::DoeCmdE {
super::enums::DoeCmdE::try_from((self.0 >> 0) & 3).unwrap()
}
/// Key Vault entry to store the result.
#[inline(always)]
pub fn dest(&self) -> u32 {
(self.0 >> 2) & 0x1f
}
/// Additional encoding bits for DOE command to run
#[inline(always)]
pub fn cmd_ext(&self) -> super::enums::DoeCmdExtE {
super::enums::DoeCmdExtE::try_from((self.0 >> 7) & 3).unwrap()
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlWriteVal {
CtrlWriteVal(self.0)
}
}
impl From<u32> for CtrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlWriteVal(u32);
impl CtrlWriteVal {
/// Indicates the command for DOE to run. Additional command encodings in the CMD_EXT field are combined with this field to define the full command.
#[inline(always)]
pub fn cmd(
self,
f: impl FnOnce(super::enums::selector::DoeCmdESelector) -> super::enums::DoeCmdE,
) -> Self {
Self(
(self.0 & !(3 << 0))
| (u32::from(f(super::enums::selector::DoeCmdESelector())) << 0),
)
}
/// Key Vault entry to store the result.
#[inline(always)]
pub fn dest(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 2)) | ((val & 0x1f) << 2))
}
/// Additional encoding bits for DOE command to run
#[inline(always)]
pub fn cmd_ext(
self,
f: impl FnOnce(super::enums::selector::DoeCmdExtESelector) -> super::enums::DoeCmdExtE,
) -> Self {
Self(
(self.0 & !(3 << 7))
| (u32::from(f(super::enums::selector::DoeCmdExtESelector())) << 7),
)
}
}
impl From<u32> for CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Status ready bit - Indicates if the core is ready to take a control command and process the block.
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Status valid bit - Indicates if the process is done and the results have been stored in the keyvault.
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// UDS Flow Completed
#[inline(always)]
pub fn uds_flow_done(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// FE flow completed
#[inline(always)]
pub fn fe_flow_done(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Clear Secrets flow completed
#[inline(always)]
pub fn deobf_secrets_cleared(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// HEK flow completed
#[inline(always)]
pub fn hek_flow_done(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// Status error bit - Indicates if the DOE operation failed and results were not written to the keyvault.
#[inline(always)]
pub fn error(&self) -> bool {
((self.0 >> 8) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrEnTWriteVal {
ErrorIntrEnTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTWriteVal(u32);
impl ErrorIntrEnTWriteVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrEnTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrEnTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrEnTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTReadVal(u32);
impl ErrorIntrTReadVal {
/// Interrupt Event 0 status bit
#[inline(always)]
pub fn error0_sts(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Event 1 status bit
#[inline(always)]
pub fn error1_sts(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTWriteVal {
ErrorIntrTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTWriteVal(u32);
impl ErrorIntrTWriteVal {
/// Interrupt Event 0 status bit
#[inline(always)]
pub fn error0_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Interrupt Event 1 status bit
#[inline(always)]
pub fn error1_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Interrupt Event 2 status bit
#[inline(always)]
pub fn error2_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Interrupt Event 3 status bit
#[inline(always)]
pub fn error3_sts(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTrigTReadVal(u32);
impl ErrorIntrTrigTReadVal {
/// Interrupt Trigger 0 bit
#[inline(always)]
pub fn error0_trig(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Interrupt Trigger 1 bit
#[inline(always)]
pub fn error1_trig(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Interrupt Trigger 2 bit
#[inline(always)]
pub fn error2_trig(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Interrupt Trigger 3 bit
#[inline(always)]
pub fn error3_trig(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrorIntrTrigTWriteVal {
ErrorIntrTrigTWriteVal(self.0)
}
}
impl From<u32> for ErrorIntrTrigTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTrigTReadVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTrigTReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrTrigTWriteVal(u32);
impl ErrorIntrTrigTWriteVal {
/// Interrupt Trigger 0 bit
#[inline(always)]
pub fn error0_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Interrupt Trigger 1 bit
#[inline(always)]
pub fn error1_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Interrupt Trigger 2 bit
#[inline(always)]
pub fn error2_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Interrupt Trigger 3 bit
#[inline(always)]
pub fn error3_trig(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
}
impl From<u32> for ErrorIntrTrigTWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrorIntrTrigTWriteVal> for u32 {
#[inline(always)]
fn from(val: ErrorIntrTrigTWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct GlobalIntrEnTReadVal(u32);
impl GlobalIntrEnTReadVal {
/// Global enable bit for all events of type 'Error'
#[inline(always)]
pub fn error_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Global enable bit for all events of type 'Notification'
#[inline(always)]
pub fn notif_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> GlobalIntrEnTWriteVal {
GlobalIntrEnTWriteVal(self.0)
}
}
impl From<u32> for GlobalIntrEnTReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<GlobalIntrEnTReadVal> for u32 {
#[inline(always)]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/pv.rs | hw/latest/registers/src/pv.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct PvReg {
_priv: (),
}
impl PvReg {
pub const PTR: *mut u32 = 0x1001a000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Controls for each pcr entry
///
/// Read value: [`pv::regs::PvctrlReadVal`]; Write value: [`pv::regs::PvctrlWriteVal`]
#[inline(always)]
pub fn pcr_ctrl(&self) -> ureg::Array<32, ureg::RegRef<crate::pv::meta::PcrCtrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Pcr Entries are read only
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn pcr_entry(
&self,
) -> ureg::Array<32, ureg::Array<12, ureg::RegRef<crate::pv::meta::PcrEntry, &TMmio>>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x600 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct PvctrlReadVal(u32);
impl PvctrlReadVal {
/// Lock the PCR from being cleared
#[inline(always)]
pub fn lock(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Clear the data stored in this entry. Lock will prevent this clear.
#[inline(always)]
pub fn clear(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Reserved
#[inline(always)]
pub fn rsvd0(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Reserved
#[inline(always)]
pub fn rsvd1(&self) -> u32 {
(self.0 >> 3) & 0x1f
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> PvctrlWriteVal {
PvctrlWriteVal(self.0)
}
}
impl From<u32> for PvctrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<PvctrlReadVal> for u32 {
#[inline(always)]
fn from(val: PvctrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct PvctrlWriteVal(u32);
impl PvctrlWriteVal {
/// Lock the PCR from being cleared
#[inline(always)]
pub fn lock(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Clear the data stored in this entry. Lock will prevent this clear.
#[inline(always)]
pub fn clear(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Reserved
#[inline(always)]
pub fn rsvd0(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Reserved
#[inline(always)]
pub fn rsvd1(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 3)) | ((val & 0x1f) << 3))
}
}
impl From<u32> for PvctrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<PvctrlWriteVal> for u32 {
#[inline(always)]
fn from(val: PvctrlWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type PcrCtrl =
ureg::ReadWriteReg32<0, crate::pv::regs::PvctrlReadVal, crate::pv::regs::PvctrlWriteVal>;
pub type PcrEntry = ureg::ReadOnlyReg32<u32>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mcu_trace_buffer.rs | hw/latest/registers/src/mcu_trace_buffer.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct McuTraceBufferCsr {
_priv: (),
}
impl McuTraceBufferCsr {
pub const PTR: *mut u32 = 0x10000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Status bits for the Trace Buffer
///
/// Read value: [`mcu_trace_buffer::regs::StatusReadVal`]; Write value: [`mcu_trace_buffer::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::mcu_trace_buffer::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HW configuration of the trace buffer
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn config(&self) -> ureg::RegRef<crate::mcu_trace_buffer::meta::Config, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trace data in the trace buffer at the read pointer.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn data(&self) -> ureg::RegRef<crate::mcu_trace_buffer::meta::Data, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Last valid data written to trace buffer. Only valid if STATUS.valid_data is set.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn write_ptr(&self) -> ureg::RegRef<crate::mcu_trace_buffer::meta::WritePtr, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read pointer for extracting data via the DATA register. NOTE: This is not an address, increment by 1 to get the next 32 bit entry.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn read_ptr(&self) -> ureg::RegRef<crate::mcu_trace_buffer::meta::ReadPtr, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Indicates trace buffer has wrapped at least once. Meaning all entries in the trace buffer are valid.
#[inline(always)]
pub fn wrapped(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Indicates at least one entry in the trace buffer is valid.
#[inline(always)]
pub fn valid_data(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type Status = ureg::ReadOnlyReg32<crate::mcu_trace_buffer::regs::StatusReadVal>;
pub type Config = ureg::ReadOnlyReg32<u32>;
pub type Data = ureg::ReadOnlyReg32<u32>;
pub type WritePtr = ureg::ReadOnlyReg32<u32>;
pub type ReadPtr = ureg::ReadWriteReg32<0, u32, u32>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/dv.rs | hw/latest/registers/src/dv.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct DvReg {
_priv: (),
}
impl DvReg {
pub const PTR: *mut u32 = 0x1001c000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Controls for the Sticky Data Vault Entries (cleared on hard reset)
///
/// Read value: [`dv::regs::DatavaultctrlReadVal`]; Write value: [`dv::regs::DatavaultctrlWriteVal`]
#[inline(always)]
pub fn sticky_data_vault_ctrl(
&self,
) -> ureg::Array<10, ureg::RegRef<crate::dv::meta::Stickydatavaultctrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn sticky_data_vault_entry(
&self,
) -> ureg::Array<10, ureg::Array<12, ureg::RegRef<crate::dv::meta::StickyDataVaultEntry, &TMmio>>>
{
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls for the Data Vault Entries (cleared on warm reset)
///
/// Read value: [`dv::regs::DatavaultctrlReadVal`]; Write value: [`dv::regs::DatavaultctrlWriteVal`]
#[inline(always)]
pub fn data_vault_ctrl(
&self,
) -> ureg::Array<10, ureg::RegRef<crate::dv::meta::Datavaultctrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn data_vault_entry(
&self,
) -> ureg::Array<10, ureg::Array<12, ureg::RegRef<crate::dv::meta::DataVaultEntry, &TMmio>>>
{
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x230 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Scratch Register Controls (cleared on warm reset)
///
/// Read value: [`dv::regs::LockablescratchregctrlReadVal`]; Write value: [`dv::regs::LockablescratchregctrlWriteVal`]
#[inline(always)]
pub fn lockable_scratch_reg_ctrl(
&self,
) -> ureg::Array<10, ureg::RegRef<crate::dv::meta::Lockablescratchregctrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x410 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Scratch Register Entrie (cleared on hard reset)
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn lockable_scratch_reg(
&self,
) -> ureg::Array<10, ureg::RegRef<crate::dv::meta::Lockablescratchreg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x438 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn non_sticky_generic_scratch_reg(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::dv::meta::Nonstickygenericscratchreg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x460 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Sticky Scratch Register Controls (cleared on hard reset)
///
/// Read value: [`dv::regs::LockablescratchregctrlReadVal`]; Write value: [`dv::regs::LockablescratchregctrlWriteVal`]
#[inline(always)]
pub fn sticky_lockable_scratch_reg_ctrl(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::dv::meta::Stickylockablescratchregctrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x480 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Sticky Scratch Register Entries (cleared on hard reset)
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn sticky_lockable_scratch_reg(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::dv::meta::Stickylockablescratchreg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x4a0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct DatavaultctrlReadVal(u32);
impl DatavaultctrlReadVal {
/// Lock writes to this entry. Writes will be suppressed when locked.
#[inline(always)]
pub fn lock_entry(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> DatavaultctrlWriteVal {
DatavaultctrlWriteVal(self.0)
}
}
impl From<u32> for DatavaultctrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<DatavaultctrlReadVal> for u32 {
#[inline(always)]
fn from(val: DatavaultctrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct DatavaultctrlWriteVal(u32);
impl DatavaultctrlWriteVal {
/// Lock writes to this entry. Writes will be suppressed when locked.
#[inline(always)]
pub fn lock_entry(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for DatavaultctrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<DatavaultctrlWriteVal> for u32 {
#[inline(always)]
fn from(val: DatavaultctrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LockablescratchregctrlReadVal(u32);
impl LockablescratchregctrlReadVal {
/// Lock writes to the Scratch registers. Writes will be suppressed when locked.
#[inline(always)]
pub fn lock_entry(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> LockablescratchregctrlWriteVal {
LockablescratchregctrlWriteVal(self.0)
}
}
impl From<u32> for LockablescratchregctrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LockablescratchregctrlReadVal> for u32 {
#[inline(always)]
fn from(val: LockablescratchregctrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LockablescratchregctrlWriteVal(u32);
impl LockablescratchregctrlWriteVal {
/// Lock writes to the Scratch registers. Writes will be suppressed when locked.
#[inline(always)]
pub fn lock_entry(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for LockablescratchregctrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LockablescratchregctrlWriteVal> for u32 {
#[inline(always)]
fn from(val: LockablescratchregctrlWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type Stickydatavaultctrl = ureg::ReadWriteReg32<
0,
crate::dv::regs::DatavaultctrlReadVal,
crate::dv::regs::DatavaultctrlWriteVal,
>;
pub type StickyDataVaultEntry = ureg::ReadWriteReg32<0, u32, u32>;
pub type Datavaultctrl = ureg::ReadWriteReg32<
0,
crate::dv::regs::DatavaultctrlReadVal,
crate::dv::regs::DatavaultctrlWriteVal,
>;
pub type DataVaultEntry = ureg::ReadWriteReg32<0, u32, u32>;
pub type Lockablescratchregctrl = ureg::ReadWriteReg32<
0,
crate::dv::regs::LockablescratchregctrlReadVal,
crate::dv::regs::LockablescratchregctrlWriteVal,
>;
pub type Lockablescratchreg = ureg::ReadWriteReg32<0, u32, u32>;
pub type Nonstickygenericscratchreg = ureg::ReadWriteReg32<0, u32, u32>;
pub type Stickylockablescratchregctrl = ureg::ReadWriteReg32<
0,
crate::dv::regs::LockablescratchregctrlReadVal,
crate::dv::regs::LockablescratchregctrlWriteVal,
>;
pub type Stickylockablescratchreg = ureg::ReadWriteReg32<0, u32, u32>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mcu_mbox1.rs | hw/latest/registers/src/mcu_mbox1.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct McuMbox1Csr {
_priv: (),
}
impl McuMbox1Csr {
pub const PTR: *mut u32 = 0x800000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Mailbox SRAM storage. The maximum size is 2MB, but is configurable by the integration team. Only writable once a lock is obtained. Cleared from 0x0 to max DLEN after lock is released.
/// [br] Root user, user with lock on mailbox, and target user have RW access.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_sram(
&self,
) -> ureg::Array<524288, ureg::RegRef<crate::mcu_mbox1::meta::MboxSram, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Mailbox lock register for mailbox access, reading 0 will set the lock. On reset release lock is set to root_user (MCU) to allow SRAM clearing
///
/// Read value: [`mcu_mbox1::regs::MboxLockReadVal`]; Write value: [`mcu_mbox1::regs::MboxLockWriteVal`]
#[inline(always)]
pub fn mbox_lock(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxLock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the AXI USER that locked the mailbox. Cleared when lock is cleared.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_user(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200004 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the AXI USER for target user access. Only valid when mbox_target_user_valid is set. Only controllable by the root user. Only accessible when mailbox is locked. Cleared when lock is cleared.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_target_user(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxTargetUser, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200008 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Enables access for the mbox_target_user. Only controllable by the root user. Only accessible when mailbox is locked. Cleared when lock is cleared.
///
/// Read value: [`mcu_mbox1::regs::MboxTargetUserValidReadVal`]; Write value: [`mcu_mbox1::regs::MboxTargetUserValidWriteVal`]
#[inline(always)]
pub fn mbox_target_user_valid(
&self,
) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxTargetUserValid, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x20000c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Command requested for data in mailbox. Cleared when lock is cleared.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_cmd(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxCmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200010 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Data length for mailbox access in bytes. Cleared when lock is cleared
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mbox_dlen(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxDlen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200014 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Mailbox execute register indicates to receiver that the sender is done.
///
/// Read value: [`mcu_mbox1::regs::MboxExecuteReadVal`]; Write value: [`mcu_mbox1::regs::MboxExecuteWriteVal`]
#[inline(always)]
pub fn mbox_execute(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxExecute, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200018 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status of the mailbox command
///
/// Read value: [`mcu_mbox1::regs::MboxTargetStatusReadVal`]; Write value: [`mcu_mbox1::regs::MboxTargetStatusWriteVal`]
#[inline(always)]
pub fn mbox_target_status(
&self,
) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxTargetStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x20001c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status of the mailbox command
///
/// Read value: [`mcu_mbox1::regs::MboxCmdStatusReadVal`]; Write value: [`mcu_mbox1::regs::MboxCmdStatusWriteVal`]
#[inline(always)]
pub fn mbox_cmd_status(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxCmdStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200020 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// HW status of the mailbox
///
/// Read value: [`mcu_mbox1::regs::MboxHwStatusReadVal`]; Write value: [`mcu_mbox1::regs::MboxHwStatusWriteVal`]
#[inline(always)]
pub fn mbox_hw_status(&self) -> ureg::RegRef<crate::mcu_mbox1::meta::MboxHwStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr
.wrapping_add(0x200024 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct MboxCmdStatusReadVal(u32);
impl MboxCmdStatusReadVal {
/// Indicates the status of mailbox command.
#[inline(always)]
pub fn status(&self) -> super::enums::MboxStatusE {
super::enums::MboxStatusE::try_from((self.0 >> 0) & 0xf).unwrap()
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxCmdStatusWriteVal {
MboxCmdStatusWriteVal(self.0)
}
}
impl From<u32> for MboxCmdStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxCmdStatusReadVal> for u32 {
#[inline(always)]
fn from(val: MboxCmdStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxCmdStatusWriteVal(u32);
impl MboxCmdStatusWriteVal {
/// Indicates the status of mailbox command.
#[inline(always)]
pub fn status(
self,
f: impl FnOnce(super::enums::selector::MboxStatusESelector) -> super::enums::MboxStatusE,
) -> Self {
Self(
(self.0 & !(0xf << 0))
| (u32::from(f(super::enums::selector::MboxStatusESelector())) << 0),
)
}
}
impl From<u32> for MboxCmdStatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxCmdStatusWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxCmdStatusWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxExecuteReadVal(u32);
impl MboxExecuteReadVal {
#[inline(always)]
pub fn execute(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxExecuteWriteVal {
MboxExecuteWriteVal(self.0)
}
}
impl From<u32> for MboxExecuteReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxExecuteReadVal> for u32 {
#[inline(always)]
fn from(val: MboxExecuteReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxExecuteWriteVal(u32);
impl MboxExecuteWriteVal {
#[inline(always)]
pub fn execute(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for MboxExecuteWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxExecuteWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxExecuteWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxHwStatusReadVal(u32);
impl MboxHwStatusReadVal {
/// Indicates a correctable ECC single-bit error was
/// detected and corrected while reading dataout.
/// Auto-clears when mbox_execute field is cleared.
#[inline(always)]
pub fn ecc_single_error(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Indicates an uncorrectable ECC double-bit error
/// was detected while reading dataout.
/// Firmware developers are advised to set the command
/// status to CMD_FAILURE in response.
/// Auto-clears when mbox_execute field is cleared.
#[inline(always)]
pub fn ecc_double_error(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for MboxHwStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxHwStatusReadVal> for u32 {
#[inline(always)]
fn from(val: MboxHwStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxLockReadVal(u32);
impl MboxLockReadVal {
#[inline(always)]
pub fn lock(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
}
impl From<u32> for MboxLockReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxLockReadVal> for u32 {
#[inline(always)]
fn from(val: MboxLockReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetStatusReadVal(u32);
impl MboxTargetStatusReadVal {
/// Indicates the status of mailbox for the target user. Valid when done is set.
#[inline(always)]
pub fn status(&self) -> super::enums::MboxStatusE {
super::enums::MboxStatusE::try_from((self.0 >> 0) & 0xf).unwrap()
}
/// Indicates target user is done and target status is valid.
#[inline(always)]
pub fn done(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxTargetStatusWriteVal {
MboxTargetStatusWriteVal(self.0)
}
}
impl From<u32> for MboxTargetStatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetStatusReadVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetStatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetStatusWriteVal(u32);
impl MboxTargetStatusWriteVal {
/// Indicates the status of mailbox for the target user. Valid when done is set.
#[inline(always)]
pub fn status(
self,
f: impl FnOnce(super::enums::selector::MboxStatusESelector) -> super::enums::MboxStatusE,
) -> Self {
Self(
(self.0 & !(0xf << 0))
| (u32::from(f(super::enums::selector::MboxStatusESelector())) << 0),
)
}
/// Indicates target user is done and target status is valid.
#[inline(always)]
pub fn done(self, val: bool) -> Self {
Self((self.0 & !(1 << 4)) | (u32::from(val) << 4))
}
}
impl From<u32> for MboxTargetStatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetStatusWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetStatusWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetUserValidReadVal(u32);
impl MboxTargetUserValidReadVal {
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> MboxTargetUserValidWriteVal {
MboxTargetUserValidWriteVal(self.0)
}
}
impl From<u32> for MboxTargetUserValidReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetUserValidReadVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetUserValidReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct MboxTargetUserValidWriteVal(u32);
impl MboxTargetUserValidWriteVal {
#[inline(always)]
pub fn valid(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for MboxTargetUserValidWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<MboxTargetUserValidWriteVal> for u32 {
#[inline(always)]
fn from(val: MboxTargetUserValidWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u32)]
pub enum MboxStatusE {
CmdBusy = 0,
DataReady = 1,
CmdComplete = 2,
CmdFailure = 3,
Reserved4 = 4,
Reserved5 = 5,
Reserved6 = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Reserved10 = 10,
Reserved11 = 11,
Reserved12 = 12,
Reserved13 = 13,
Reserved14 = 14,
Reserved15 = 15,
}
impl MboxStatusE {
#[inline(always)]
pub fn cmd_busy(&self) -> bool {
*self == Self::CmdBusy
}
#[inline(always)]
pub fn data_ready(&self) -> bool {
*self == Self::DataReady
}
#[inline(always)]
pub fn cmd_complete(&self) -> bool {
*self == Self::CmdComplete
}
#[inline(always)]
pub fn cmd_failure(&self) -> bool {
*self == Self::CmdFailure
}
}
impl TryFrom<u32> for MboxStatusE {
type Error = ();
#[inline(always)]
fn try_from(val: u32) -> Result<MboxStatusE, ()> {
if val < 0x10 {
Ok(unsafe { core::mem::transmute::<u32, MboxStatusE>(val) })
} else {
Err(())
}
}
}
impl From<MboxStatusE> for u32 {
fn from(val: MboxStatusE) -> Self {
val as u32
}
}
pub mod selector {
pub struct MboxStatusESelector();
impl MboxStatusESelector {
#[inline(always)]
pub fn cmd_busy(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdBusy
}
#[inline(always)]
pub fn data_ready(&self) -> super::MboxStatusE {
super::MboxStatusE::DataReady
}
#[inline(always)]
pub fn cmd_complete(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdComplete
}
#[inline(always)]
pub fn cmd_failure(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdFailure
}
}
}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type MboxSram = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxLock = ureg::ReadOnlyReg32<crate::mcu_mbox1::regs::MboxLockReadVal>;
pub type MboxUser = ureg::ReadOnlyReg32<u32>;
pub type MboxTargetUser = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxTargetUserValid = ureg::ReadWriteReg32<
0,
crate::mcu_mbox1::regs::MboxTargetUserValidReadVal,
crate::mcu_mbox1::regs::MboxTargetUserValidWriteVal,
>;
pub type MboxCmd = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxDlen = ureg::ReadWriteReg32<0, u32, u32>;
pub type MboxExecute = ureg::ReadWriteReg32<
0,
crate::mcu_mbox1::regs::MboxExecuteReadVal,
crate::mcu_mbox1::regs::MboxExecuteWriteVal,
>;
pub type MboxTargetStatus = ureg::ReadWriteReg32<
0,
crate::mcu_mbox1::regs::MboxTargetStatusReadVal,
crate::mcu_mbox1::regs::MboxTargetStatusWriteVal,
>;
pub type MboxCmdStatus = ureg::ReadWriteReg32<
0,
crate::mcu_mbox1::regs::MboxCmdStatusReadVal,
crate::mcu_mbox1::regs::MboxCmdStatusWriteVal,
>;
pub type MboxHwStatus = ureg::ReadOnlyReg32<crate::mcu_mbox1::regs::MboxHwStatusReadVal>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/kv.rs | hw/latest/registers/src/kv.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct KvReg {
_priv: (),
}
impl KvReg {
pub const PTR: *mut u32 = 0x10018000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Controls for each keyvault and pcr entry
///
/// Read value: [`kv::regs::KvctrlReadVal`]; Write value: [`kv::regs::KvctrlWriteVal`]
#[inline(always)]
pub fn key_ctrl(&self) -> ureg::Array<24, ureg::RegRef<crate::kv::meta::KeyCtrl, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Key Entries are not readable or writeable by software
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn key_entry(
&self,
) -> ureg::Array<24, ureg::Array<16, ureg::RegRef<crate::kv::meta::KeyEntry, &TMmio>>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x600 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`kv::regs::ClearSecretsReadVal`]; Write value: [`kv::regs::ClearSecretsWriteVal`]
#[inline(always)]
pub fn clear_secrets(&self) -> ureg::RegRef<crate::kv::meta::ClearSecrets, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc00 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct ClearSecretsReadVal(u32);
impl ClearSecretsReadVal {
/// Fill the keyvault with debug values
#[inline(always)]
pub fn wr_debug_values(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Selects between debug value 0 or 1 parameter to write to keyvault
#[inline(always)]
pub fn sel_debug_value(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ClearSecretsWriteVal {
ClearSecretsWriteVal(self.0)
}
}
impl From<u32> for ClearSecretsReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ClearSecretsReadVal> for u32 {
#[inline(always)]
fn from(val: ClearSecretsReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ClearSecretsWriteVal(u32);
impl ClearSecretsWriteVal {
/// Fill the keyvault with debug values
#[inline(always)]
pub fn wr_debug_values(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Selects between debug value 0 or 1 parameter to write to keyvault
#[inline(always)]
pub fn sel_debug_value(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for ClearSecretsWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ClearSecretsWriteVal> for u32 {
#[inline(always)]
fn from(val: ClearSecretsWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct KvctrlReadVal(u32);
impl KvctrlReadVal {
/// Lock writes to this entry. Writes will be suppressed and an error will be recorded.
#[inline(always)]
pub fn lock_wr(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Lock use of this entry. Reads will be suppressed and an error will be recorded.
#[inline(always)]
pub fn lock_use(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Clear the data stored in this entry. Lock write will prevent this clear.
#[inline(always)]
pub fn clear(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Reserved
#[inline(always)]
pub fn rsvd0(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Reserved
#[inline(always)]
pub fn rsvd1(&self) -> u32 {
(self.0 >> 4) & 0x1f
}
/// Destination valid bits stored as an array for ease of use in RTL.
/// [br]dest_valid[0] = hmac_key_dest_valid
/// [br]dest_valid[1] = hmac_block_dest_valid
/// [br]dest_valid[2] = mldsa_seed_dest_valid
/// [br]dest_valid[3] = ecc_pkey_dest_valid
/// [br]dest_valid[4] = ecc_seed_dest_valid
/// [br]dest_valid[5] = aes_key_dest_valid
/// [br]dest_valid[6] = mlkem_seed_dest_valid
/// [br]dest_valid[7] = mlkem_msg_dest_valid
/// [br]dest_valid[8] = axi_dma_data_dest_valid
#[inline(always)]
pub fn dest_valid(&self) -> u32 {
(self.0 >> 9) & 0x1ff
}
/// Stores the offset of the last valid dword, used to indicate last cycle on reads.
#[inline(always)]
pub fn last_dword(&self) -> u32 {
(self.0 >> 18) & 0xf
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> KvctrlWriteVal {
KvctrlWriteVal(self.0)
}
}
impl From<u32> for KvctrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvctrlReadVal> for u32 {
#[inline(always)]
fn from(val: KvctrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct KvctrlWriteVal(u32);
impl KvctrlWriteVal {
/// Lock writes to this entry. Writes will be suppressed and an error will be recorded.
#[inline(always)]
pub fn lock_wr(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Lock use of this entry. Reads will be suppressed and an error will be recorded.
#[inline(always)]
pub fn lock_use(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Clear the data stored in this entry. Lock write will prevent this clear.
#[inline(always)]
pub fn clear(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
/// Reserved
#[inline(always)]
pub fn rsvd0(self, val: bool) -> Self {
Self((self.0 & !(1 << 3)) | (u32::from(val) << 3))
}
/// Reserved
#[inline(always)]
pub fn rsvd1(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 4)) | ((val & 0x1f) << 4))
}
}
impl From<u32> for KvctrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<KvctrlWriteVal> for u32 {
#[inline(always)]
fn from(val: KvctrlWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
pub mod selector {}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type KeyCtrl =
ureg::ReadWriteReg32<0, crate::kv::regs::KvctrlReadVal, crate::kv::regs::KvctrlWriteVal>;
pub type KeyEntry = ureg::WriteOnlyReg32<0, u32>;
pub type ClearSecrets = ureg::ReadWriteReg32<
0,
crate::kv::regs::ClearSecretsReadVal,
crate::kv::regs::ClearSecretsWriteVal,
>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/abr.rs | hw/latest/registers/src/abr.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct AbrReg {
_priv: (),
}
impl AbrReg {
pub const PTR: *mut u32 = 0x10030000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Two 32-bit read-only registers representing of the name
/// of MLDSA component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_name(&self) -> ureg::Array<2, ureg::RegRef<crate::abr::meta::MldsaName, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of MLDSA component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_version(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::abr::meta::MldsaVersion, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Control register to set the type of MLDSA operations.
///
/// Read value: [`abr::regs::MldsaCtrlReadVal`]; Write value: [`abr::regs::MldsaCtrlWriteVal`]
#[inline(always)]
pub fn mldsa_ctrl(&self) -> ureg::RegRef<crate::abr::meta::MldsaCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// One 3-bit register including the following flags:
/// [br]bit #0: READY : Indicates if the core is ready to take
/// [br] a control command and process the inputs.
/// [br]bit #1: VALID : Indicates if the process is done and the
/// [br] result is valid.
/// [br]bit #2: MSG_STREAM_READY: Indicates if the core is ready
/// [br] to recieve the message in streaming mode.
/// [br]bit #3: ERROR: Indicates the process ended with an error
///
/// Read value: [`abr::regs::MldsaStatusReadVal`]; Write value: [`abr::regs::MldsaStatusWriteVal`]
#[inline(always)]
pub fn mldsa_status(&self) -> ureg::RegRef<crate::abr::meta::MldsaStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 16 32-bit registers storing the 512-bit entropy
/// required for SCA countermeasures with no change on the outputs.
/// The entropy can be any 512-bit value in [0 : 2^512-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn entropy(&self) -> ureg::Array<16, ureg::RegRef<crate::abr::meta::Entropy, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 8 32-bit registers storing the 256-bit seed for keygen.
/// The seed can be any 256-bit value in [0 : 2^256-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_seed(&self) -> ureg::Array<8, ureg::RegRef<crate::abr::meta::MldsaSeed, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x58 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 8 32-bit registers storing the 256-bit sign_rnd for signing.
/// The sign_rnd can be any 256-bit value in [0 : 2^256-1].
/// sign_rnd should be all zero for deterministic variant.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_sign_rnd(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::abr::meta::MldsaSignRnd, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x78 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 16 32-bit registers storing the message.
/// The message can be a fixed size of 512-bit value in [0 : 2^512-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_msg(&self) -> ureg::Array<16, ureg::RegRef<crate::abr::meta::MldsaMsg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x98 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 16 32-bit registers storing the result of verifying operation.
/// If this register is equal to the first part of the given signature, i.e. c~,
/// the signature is verified.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_verify_res(
&self,
) -> ureg::Array<16, ureg::RegRef<crate::abr::meta::MldsaVerifyRes, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xd8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 16 32-bit registers storing the external_mu.
/// The external_mu can be any 512-bit value in [0 : 2^512-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_external_mu(
&self,
) -> ureg::Array<16, ureg::RegRef<crate::abr::meta::MldsaExternalMu, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x118 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Byte enable strobe for each 32 bits of message.
/// [br] Must be set to 4'b1111 before streaming message, after observing stream_msg_rdy.
/// [br] Set to 1 for each valid byte in the last msg data, starting from LSB.
/// [br] Valid values are 4'b0000, 4'b0001, 4'b0011, 4'b0111, and 4'b1111
/// [br] A 32 bit aligned msg must write this to 4'h0 and write to msg input once.
///
/// Read value: [`abr::regs::MldsaMsgStrobeReadVal`]; Write value: [`abr::regs::MldsaMsgStrobeWriteVal`]
#[inline(always)]
pub fn mldsa_msg_strobe(&self) -> ureg::RegRef<crate::abr::meta::MldsaMsgStrobe, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x158 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Registers defining the size of the context.
/// The context is an optional byte-string.
///
/// Read value: [`abr::regs::MldsaCtxConfigReadVal`]; Write value: [`abr::regs::MldsaCtxConfigWriteVal`]
#[inline(always)]
pub fn mldsa_ctx_config(&self) -> ureg::RegRef<crate::abr::meta::MldsaCtxConfig, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x15c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// up tp 255 bytes registers storing the context.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_ctx(&self) -> ureg::Array<64, ureg::RegRef<crate::abr::meta::MldsaCtx, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x160 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 648 32-bit registers storing the public key.
/// These registers are read by MLDSA user after keygen operation,
/// or set before verifying operation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_pubkey(
&self,
) -> ureg::Array<648, ureg::RegRef<crate::abr::meta::MldsaPubkey, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x1000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 1157 32-bit registers storing the signature of the message.
/// These registers are read by MLDSA user after signing operation,
/// or set before verifying operation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_signature(
&self,
) -> ureg::Array<1157, ureg::RegRef<crate::abr::meta::MldsaSignature, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x2000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 1224 32-bit registers storing the private key for keygen.
/// These registers are read by MLDSA user after keygen operation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_privkey_out(
&self,
) -> ureg::Array<1224, ureg::RegRef<crate::abr::meta::MldsaPrivkeyOut, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x4000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 1224 32-bit entries storing the private key for signing.
/// These entries must be set before signing operation.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mldsa_privkey_in(
&self,
) -> ureg::Array<1224, ureg::RegRef<crate::abr::meta::MldsaPrivkeyIn, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x6000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_mldsa_seed_rd_ctrl(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMldsaSeedRdCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x8000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_mldsa_seed_rd_status(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMldsaSeedRdStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x8004 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the name
/// of MLKEM component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_name(&self) -> ureg::Array<2, ureg::RegRef<crate::abr::meta::MlkemName, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x9000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Two 32-bit read-only registers representing of the version
/// of MLKEM component.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_version(
&self,
) -> ureg::Array<2, ureg::RegRef<crate::abr::meta::MlkemVersion, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x9008 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Control register to set the type of MLKEM operations.
///
/// Read value: [`abr::regs::MlkemCtrlReadVal`]; Write value: [`abr::regs::MlkemCtrlWriteVal`]
#[inline(always)]
pub fn mlkem_ctrl(&self) -> ureg::RegRef<crate::abr::meta::MlkemCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x9010 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// One 3-bit register including the following flags:
/// [br]bit #0: READY : Indicates if the core is ready to take
/// [br] a control command and process the inputs.
/// [br]bit #1: VALID : Indicates if the process is done and the
/// [br] result is valid.
/// [br]bit #2: ERROR : Indicates the process ended in an error.
///
/// Read value: [`abr::regs::MlkemStatusReadVal`]; Write value: [`abr::regs::MlkemStatusWriteVal`]
#[inline(always)]
pub fn mlkem_status(&self) -> ureg::RegRef<crate::abr::meta::MlkemStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x9014 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 8 32-bit registers storing the 256-bit seed for keygen.
/// The seed can be any 256-bit value in [0 : 2^256-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_seed_d(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::abr::meta::MlkemSeedD, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x9018 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 8 32-bit registers storing the 256-bit seed for keygen.
/// The seed can be any 256-bit value in [0 : 2^256-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_seed_z(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::abr::meta::MlkemSeedZ, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x9038 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 8 32-bit registers storing the shared key.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_shared_key(
&self,
) -> ureg::Array<8, ureg::RegRef<crate::abr::meta::MlkemSharedKey, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x9058 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 256-bit message. The message can be a fixed size of 256-bit value in [0 : 2^256-1].
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_msg(&self) -> ureg::Array<8, ureg::RegRef<crate::abr::meta::MlkemMsg, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x9080 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 3,168 byte decapsulation key
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_decaps_key(
&self,
) -> ureg::Array<792, ureg::RegRef<crate::abr::meta::MlkemDecapsKey, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xa000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 1,568 byte encapsulation key
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_encaps_key(
&self,
) -> ureg::Array<392, ureg::RegRef<crate::abr::meta::MlkemEncapsKey, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xb000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 1,568 byte ciphertext
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn mlkem_ciphertext(
&self,
) -> ureg::Array<392, ureg::RegRef<crate::abr::meta::MlkemCiphertext, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0xb800 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_mlkem_seed_rd_ctrl(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMlkemSeedRdCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc000 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_mlkem_seed_rd_status(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMlkemSeedRdStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc004 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault read access for this engine
///
/// Read value: [`regs::KvReadCtrlRegReadVal`]; Write value: [`regs::KvReadCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_mlkem_msg_rd_ctrl(&self) -> ureg::RegRef<crate::abr::meta::KvMlkemMsgRdCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc008 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_mlkem_msg_rd_status(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMlkemMsgRdStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc00c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Controls the Key Vault write access for this engine
///
/// Read value: [`regs::KvWriteCtrlRegReadVal`]; Write value: [`regs::KvWriteCtrlRegWriteVal`]
#[inline(always)]
pub fn kv_mlkem_sharedkey_wr_ctrl(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMlkemSharedkeyWrCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc010 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Reports the Key Vault flow status for this engine
///
/// Read value: [`regs::KvStatusRegReadVal`]; Write value: [`regs::KvStatusRegWriteVal`]
#[inline(always)]
pub fn kv_mlkem_sharedkey_wr_status(
&self,
) -> ureg::RegRef<crate::abr::meta::KvMlkemSharedkeyWrStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc014 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x8100 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`abr::regs::ErrorIntrEnTReadVal`]; Write value: [`abr::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`abr::regs::NotifIntrEnTReadVal`]; Write value: [`abr::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`abr::regs::ErrorIntrTReadVal`]; Write value: [`abr::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`abr::regs::NotifIntrTReadVal`]; Write value: [`abr::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`abr::regs::ErrorIntrTrigTReadVal`]; Write value: [`abr::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`abr::regs::NotifIntrTrigTReadVal`]; Write value: [`abr::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error_internal_intr_count_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfErrorInternalIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfErrorInternalIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::abr::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/sha512_acc.rs | hw/latest/registers/src/sha512_acc.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct Sha512AccCsr {
_priv: (),
}
impl Sha512AccCsr {
pub const PTR: *mut u32 = 0x30021000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// SHA lock register for SHA access, reading 0 will set the lock, Write 1 to clear the lock
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`sha512_acc::regs::LockReadVal`]; Write value: [`sha512_acc::regs::LockWriteVal`]
#[inline(always)]
pub fn lock(&self) -> ureg::RegRef<crate::sha512_acc::meta::Lock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the AXI USER that locked the SHA
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn user(&self) -> ureg::RegRef<crate::sha512_acc::meta::User, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the requested mode for the SHA to execute.
/// SHA Supports both SHA384 and SHA512 modes of operation.
/// SHA Supports streaming mode - SHA is computed on a stream of incoming data to datain register.
/// mailbox mode - SHA is computed on LENGTH bytes of data stored in the mailbox from START_ADDRESS.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`sha512_acc::regs::ModeReadVal`]; Write value: [`sha512_acc::regs::ModeWriteVal`]
#[inline(always)]
pub fn mode(&self) -> ureg::RegRef<crate::sha512_acc::meta::Mode, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// The start address for FW controlled SHA performed on data stored in the mailbox.
/// Start Address must be dword aligned.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn start_address(&self) -> ureg::RegRef<crate::sha512_acc::meta::StartAddress, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// The length of data to be processed in bytes.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dlen(&self) -> ureg::RegRef<crate::sha512_acc::meta::Dlen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Data in register for SHA Streaming function
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn datain(&self) -> ureg::RegRef<crate::sha512_acc::meta::Datain, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// For Streaming Function, indicates that the initiator is done streaming.
/// For the Mailbox SHA Function, indicates that the SHA can begin execution.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`sha512_acc::regs::ExecuteReadVal`]; Write value: [`sha512_acc::regs::ExecuteWriteVal`]
#[inline(always)]
pub fn execute(&self) -> ureg::RegRef<crate::sha512_acc::meta::Execute, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status register indicating when the requested function is complete
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`sha512_acc::regs::StatusReadVal`]; Write value: [`sha512_acc::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::sha512_acc::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 16 32-bit registers storing the 512-bit digest output in
/// big-endian representation.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn digest(&self) -> ureg::Array<16, ureg::RegRef<crate::sha512_acc::meta::Digest, &TMmio>> {
unsafe {
ureg::Array::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// SHA Accelerator control flows.
/// [br]Zeroize the SHA engine internal registers.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
///
/// Read value: [`sha512_acc::regs::ControlReadVal`]; Write value: [`sha512_acc::regs::ControlWriteVal`]
#[inline(always)]
pub fn control(&self) -> ureg::RegRef<crate::sha512_acc::meta::Control, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
#[inline(always)]
pub fn intr_block_rf(&self) -> IntrBlockRfBlock<&TMmio> {
IntrBlockRfBlock {
ptr: unsafe { self.ptr.add(0x800 / core::mem::size_of::<u32>()) },
mmio: core::borrow::Borrow::borrow(&self.mmio),
}
}
}
#[derive(Clone, Copy)]
pub struct IntrBlockRfBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio> IntrBlockRfBlock<TMmio> {
/// Dedicated register with one bit for each event type that may produce an interrupt.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`sha512_acc::regs::GlobalIntrEnTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrEnTWriteVal`]
#[inline(always)]
pub fn global_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfGlobalIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::ErrorIntrEnTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrEnTWriteVal`]
#[inline(always)]
pub fn error_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfErrorIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Dedicated register with one bit for each event that may produce an interrupt.
///
/// Read value: [`sha512_acc::regs::NotifIntrEnTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrEnTWriteVal`]
#[inline(always)]
pub fn notif_intr_en_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfNotifIntrEnR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn error_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfErrorGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of any interrupt event
/// of a given type. E.g. Notifications and Errors may drive
/// to two separate interrupt registers. There may be
/// multiple sources of Notifications or Errors that are
/// aggregated into a single interrupt pin for that
/// respective type. That pin feeds through this register
/// in order to apply a global enablement of that interrupt
/// event type.
/// Nonsticky assertion.
///
/// Read value: [`sha512_acc::regs::GlobalIntrTReadVal`]; Write value: [`sha512_acc::regs::GlobalIntrTWriteVal`]
#[inline(always)]
pub fn notif_global_intr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfNotifGlobalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTWriteVal`]
#[inline(always)]
pub fn error_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfErrorInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit indicating occurrence of each interrupt event.
/// Sticky, level assertion, write-1-to-clear.
///
/// Read value: [`sha512_acc::regs::NotifIntrTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTWriteVal`]
#[inline(always)]
pub fn notif_internal_intr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfNotifInternalIntrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::ErrorIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::ErrorIntrTrigTWriteVal`]
#[inline(always)]
pub fn error_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfErrorIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Single bit for each interrupt event allows SW to manually
/// trigger occurrence of that event. Upon SW write, the trigger bit
/// will pulse for 1 cycle then clear to 0. The pulse on the
/// trigger register bit results in the corresponding interrupt
/// status bit being set to 1.
///
/// Read value: [`sha512_acc::regs::NotifIntrTrigTReadVal`]; Write value: [`sha512_acc::regs::NotifIntrTrigTWriteVal`]
#[inline(always)]
pub fn notif_intr_trig_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfNotifIntrTrigR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error0_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError0IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x100 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error1_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError1IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x104 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error2_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError2IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x108 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn error3_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError3IntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Provides statistics about the number of events that have
/// occurred.
/// Will not overflow ('incrsaturate').
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfNotifCmdDoneIntrCountR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x180 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error0_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError0IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x200 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error1_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError1IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x204 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error2_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError2IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x208 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn error3_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfError3IntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Trigger the event counter to increment based on observing
/// the rising edge of an interrupt event input from the
/// Hardware. The same input signal that causes an interrupt
/// event to be set (sticky) also causes this signal to pulse
/// for 1 clock cycle, resulting in the event counter
/// incrementing by 1 for every interrupt event.
/// This is implemented as a down-counter (1-bit) that will
/// decrement immediately on being set - resulting in a pulse
///
/// Read value: [`sha512_acc::regs::IntrCountIncrTReadVal`]; Write value: [`sha512_acc::regs::IntrCountIncrTWriteVal`]
#[inline(always)]
pub fn notif_cmd_done_intr_count_incr_r(
&self,
) -> ureg::RegRef<crate::sha512_acc::meta::IntrBlockRfNotifCmdDoneIntrCountIncrR, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x210 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct IntrBlockRf {
_priv: (),
}
impl IntrBlockRf {
pub const PTR: *mut u32 = 0x800 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct ControlReadVal(u32);
impl ControlReadVal {
/// Zeroize all internal registers
#[inline(always)]
pub fn zeroize(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ControlWriteVal {
ControlWriteVal(self.0)
}
}
impl From<u32> for ControlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ControlReadVal> for u32 {
#[inline(always)]
fn from(val: ControlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ControlWriteVal(u32);
impl ControlWriteVal {
/// Zeroize all internal registers
#[inline(always)]
pub fn zeroize(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for ControlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ControlWriteVal> for u32 {
#[inline(always)]
fn from(val: ControlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ExecuteReadVal(u32);
impl ExecuteReadVal {
#[inline(always)]
pub fn execute(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ExecuteWriteVal {
ExecuteWriteVal(self.0)
}
}
impl From<u32> for ExecuteReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ExecuteReadVal> for u32 {
#[inline(always)]
fn from(val: ExecuteReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ExecuteWriteVal(u32);
impl ExecuteWriteVal {
#[inline(always)]
pub fn execute(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for ExecuteWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ExecuteWriteVal> for u32 {
#[inline(always)]
fn from(val: ExecuteWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LockReadVal(u32);
impl LockReadVal {
#[inline(always)]
pub fn lock(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> LockWriteVal {
LockWriteVal(self.0)
}
}
impl From<u32> for LockReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LockReadVal> for u32 {
#[inline(always)]
fn from(val: LockReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LockWriteVal(u32);
impl LockWriteVal {
#[inline(always)]
pub fn lock(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for LockWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LockWriteVal> for u32 {
#[inline(always)]
fn from(val: LockWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ModeReadVal(u32);
impl ModeReadVal {
#[inline(always)]
pub fn mode(&self) -> super::enums::ShaCmdE {
super::enums::ShaCmdE::try_from((self.0 >> 0) & 3).unwrap()
}
/// Default behavior assumes that data in mailbox or from streaming input is little endian,
/// When set to 0, data input (from mailbox or streaming data) will be swizzled from little to big endian at the byte level.
/// When set to 1, data input will be loaded into SHA as-is.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
#[inline(always)]
pub fn endian_toggle(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ModeWriteVal {
ModeWriteVal(self.0)
}
}
impl From<u32> for ModeReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ModeReadVal> for u32 {
#[inline(always)]
fn from(val: ModeReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ModeWriteVal(u32);
impl ModeWriteVal {
#[inline(always)]
pub fn mode(
self,
f: impl FnOnce(super::enums::selector::ShaCmdESelector) -> super::enums::ShaCmdE,
) -> Self {
Self(
(self.0 & !(3 << 0))
| (u32::from(f(super::enums::selector::ShaCmdESelector())) << 0),
)
}
/// Default behavior assumes that data in mailbox or from streaming input is little endian,
/// When set to 0, data input (from mailbox or streaming data) will be swizzled from little to big endian at the byte level.
/// When set to 1, data input will be loaded into SHA as-is.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
#[inline(always)]
pub fn endian_toggle(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
}
impl From<u32> for ModeWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ModeWriteVal> for u32 {
#[inline(always)]
fn from(val: ModeWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Valid bit, indicating that the digest is complete
#[inline(always)]
pub fn valid(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Indicates that the current lock was acquired by the SoC
#[inline(always)]
pub fn soc_has_lock(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrorIntrEnTReadVal(u32);
impl ErrorIntrEnTReadVal {
/// Enable bit for Event 0
#[inline(always)]
pub fn error0_en(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Enable bit for Event 1
#[inline(always)]
pub fn error1_en(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// Enable bit for Event 2
#[inline(always)]
pub fn error2_en(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// Enable bit for Event 3
#[inline(always)]
pub fn error3_en(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/lc_ctrl.rs | hw/latest/registers/src/lc_ctrl.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct LcCtrl {
_priv: (),
}
impl LcCtrl {
pub const PTR: *mut u32 = 0x70000400 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`lc_ctrl::regs::AlertTestReadVal`]; Write value: [`lc_ctrl::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::lc_ctrl::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`lc_ctrl::regs::StatusReadVal`]; Write value: [`lc_ctrl::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::lc_ctrl::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Register write enable for the hardware mutex register.
///
/// Read value: [`lc_ctrl::regs::ClaimTransitionIfRegwenReadVal`]; Write value: [`lc_ctrl::regs::ClaimTransitionIfRegwenWriteVal`]
#[inline(always)]
pub fn claim_transition_if_regwen(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::ClaimTransitionIfRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Hardware mutex to claim exclusive access to the transition interface.
///
/// Read value: [`lc_ctrl::regs::ClaimTransitionIfReadVal`]; Write value: [`lc_ctrl::regs::ClaimTransitionIfWriteVal`]
#[inline(always)]
pub fn claim_transition_if(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::ClaimTransitionIf, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Register write enable for the hardware mutex register.
///
/// Read value: [`lc_ctrl::regs::TransitionRegwenReadVal`]; Write value: [`lc_ctrl::regs::TransitionRegwenWriteVal`]
#[inline(always)]
pub fn transition_regwen(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Command register for state transition requests.
///
/// Read value: [`lc_ctrl::regs::TransitionCmdReadVal`]; Write value: [`lc_ctrl::regs::TransitionCmdWriteVal`]
#[inline(always)]
pub fn transition_cmd(&self) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionCmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Control register for state transition requests.
///
/// Read value: [`lc_ctrl::regs::TransitionCtrlReadVal`]; Write value: [`lc_ctrl::regs::TransitionCtrlWriteVal`]
#[inline(always)]
pub fn transition_ctrl(&self) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 128bit token for conditional transitions. Make sure to set this to 0 for unconditional transitions. Note that this register is shared with the life cycle TAP/DMI interface. In order to have exclusive access to this register, SW must first claim the associated hardware mutex via CLAIM_TRANSITION_IF.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn transition_token_0(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionToken0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 128bit token for conditional transitions. Make sure to set this to 0 for unconditional transitions. Note that this register is shared with the life cycle TAP/DMI interface. In order to have exclusive access to this register, SW must first claim the associated hardware mutex via CLAIM_TRANSITION_IF.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn transition_token_1(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionToken1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 128bit token for conditional transitions. Make sure to set this to 0 for unconditional transitions. Note that this register is shared with the life cycle TAP/DMI interface. In order to have exclusive access to this register, SW must first claim the associated hardware mutex via CLAIM_TRANSITION_IF.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn transition_token_2(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionToken2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// 128bit token for conditional transitions. Make sure to set this to 0 for unconditional transitions. Note that this register is shared with the life cycle TAP/DMI interface. In order to have exclusive access to this register, SW must first claim the associated hardware mutex via CLAIM_TRANSITION_IF.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn transition_token_3(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionToken3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register exposes the decoded life cycle state.
///
/// Read value: [`lc_ctrl::regs::TransitionTargetReadVal`]; Write value: [`lc_ctrl::regs::TransitionTargetWriteVal`]
#[inline(always)]
pub fn transition_target(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::TransitionTarget, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Test/vendor-specific settings for the OTP macro wrapper. These values are only active during RAW, TEST_* and RMA life cycle states. In all other states, these values will be gated to zero before sending them to the OTP macro wrapper - even if this register is programmed to a non-zero value.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn otp_vendor_test_ctrl(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::OtpVendorTestCtrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Test/vendor-specific settings for the OTP macro wrapper. These values are only active during RAW, TEST_* and RMA life cycle states. In all other states, these values will read as zero.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn otp_vendor_test_status(
&self,
) -> ureg::RegRef<crate::lc_ctrl::meta::OtpVendorTestStatus, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register exposes the decoded life cycle state.
///
/// Read value: [`lc_ctrl::regs::LcStateReadVal`]; Write value: [`lc_ctrl::regs::LcStateWriteVal`]
#[inline(always)]
pub fn lc_state(&self) -> ureg::RegRef<crate::lc_ctrl::meta::LcState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register exposes the state of the decoded life cycle transition counter.
///
/// Read value: [`lc_ctrl::regs::LcTransitionCntReadVal`]; Write value: [`lc_ctrl::regs::LcTransitionCntWriteVal`]
#[inline(always)]
pub fn lc_transition_cnt(&self) -> ureg::RegRef<crate::lc_ctrl::meta::LcTransitionCnt, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register exposes the id state of the device.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn lc_id_state(&self) -> ureg::RegRef<crate::lc_ctrl::meta::LcIdState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds the SILICON_CREATOR_ID and the PRODUCT_ID.
///
/// Read value: [`lc_ctrl::regs::HwRevision0ReadVal`]; Write value: [`lc_ctrl::regs::HwRevision0WriteVal`]
#[inline(always)]
pub fn hw_revision0(&self) -> ureg::RegRef<crate::lc_ctrl::meta::HwRevision0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This register holds the REVISION_ID.
///
/// Read value: [`lc_ctrl::regs::HwRevision1ReadVal`]; Write value: [`lc_ctrl::regs::HwRevision1WriteVal`]
#[inline(always)]
pub fn hw_revision1(&self) -> ureg::RegRef<crate::lc_ctrl::meta::HwRevision1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x48 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_0(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x4c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_1(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x50 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_2(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x54 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_3(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x58 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_4(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId4, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_5(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId5, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x60 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_6(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId6, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x64 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is the 256bit DEVICE_ID value that is stored in the HW_CFG0 partition in OTP. If this register reads all-one, the HW_CFG0 partition has not been initialized yet or is in error state. If this register reads all-zero, this is indicative that the value has not been programmed to OTP yet.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn device_id_7(&self) -> ureg::RegRef<crate::lc_ctrl::meta::DeviceId7, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x68 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_0(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x6c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_1(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x70 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_2(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x74 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_3(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState3, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x78 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_4(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState4, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x7c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_5(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState5, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x80 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_6(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState6, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x84 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// This is a 256bit field used for keeping track of the manufacturing state.
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn manuf_state_7(&self) -> ureg::RegRef<crate::lc_ctrl::meta::ManufState7, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x88 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AlertTestWriteVal(u32);
impl AlertTestWriteVal {
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_prog_error(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_state_error(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_bus_integ_error(self, val: bool) -> Self {
Self((self.0 & !(1 << 2)) | (u32::from(val) << 2))
}
}
impl From<u32> for AlertTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AlertTestWriteVal> for u32 {
#[inline(always)]
fn from(val: AlertTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ClaimTransitionIfReadVal(u32);
impl ClaimTransitionIfReadVal {
/// Mutex
#[inline(always)]
pub fn mutex(&self) -> u32 {
(self.0 >> 0) & 0xff
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ClaimTransitionIfWriteVal {
ClaimTransitionIfWriteVal(self.0)
}
}
impl From<u32> for ClaimTransitionIfReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ClaimTransitionIfReadVal> for u32 {
#[inline(always)]
fn from(val: ClaimTransitionIfReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ClaimTransitionIfWriteVal(u32);
impl ClaimTransitionIfWriteVal {
/// Mutex
#[inline(always)]
pub fn mutex(self, val: u32) -> Self {
Self((self.0 & !(0xff << 0)) | ((val & 0xff) << 0))
}
}
impl From<u32> for ClaimTransitionIfWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ClaimTransitionIfWriteVal> for u32 {
#[inline(always)]
fn from(val: ClaimTransitionIfWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ClaimTransitionIfRegwenReadVal(u32);
impl ClaimTransitionIfRegwenReadVal {
/// This bit is managed by software and is set to 1 by default. When cleared to 0, the CLAIM_TRANSITION_IF mutex register cannot be written to anymore. Write 0 to clear this bit.
#[inline(always)]
pub fn regwen(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ClaimTransitionIfRegwenWriteVal {
ClaimTransitionIfRegwenWriteVal(self.0)
}
}
impl From<u32> for ClaimTransitionIfRegwenReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ClaimTransitionIfRegwenReadVal> for u32 {
#[inline(always)]
fn from(val: ClaimTransitionIfRegwenReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ClaimTransitionIfRegwenWriteVal(u32);
impl ClaimTransitionIfRegwenWriteVal {
/// This bit is managed by software and is set to 1 by default. When cleared to 0, the CLAIM_TRANSITION_IF mutex register cannot be written to anymore. Write 0 to clear this bit.
#[inline(always)]
pub fn regwen(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for ClaimTransitionIfRegwenWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ClaimTransitionIfRegwenWriteVal> for u32 {
#[inline(always)]
fn from(val: ClaimTransitionIfRegwenWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct HwRevision0ReadVal(u32);
impl HwRevision0ReadVal {
/// Used to identify a class of devices. Assigned by the Silicon Creator. Zero is an invalid value.
#[inline(always)]
pub fn product_id(&self) -> u32 {
(self.0 >> 0) & 0xffff
}
/// ID of the silicon creator. Assigned by the OpenTitan project. Zero is an invalid value.
#[inline(always)]
pub fn silicon_creator_id(&self) -> u32 {
(self.0 >> 16) & 0xffff
}
}
impl From<u32> for HwRevision0ReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<HwRevision0ReadVal> for u32 {
#[inline(always)]
fn from(val: HwRevision0ReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct HwRevision1ReadVal(u32);
impl HwRevision1ReadVal {
/// Product revision ID. Assigned by the Silicon Creator. The encoding is not specified other than that different tapeouts must be assigned different revision numbers. I.e., each base or metal layer respin must be reflected so that software can rely on it to modify firmware and driver behavior. Zero is an invalid value.
#[inline(always)]
pub fn revision_id(&self) -> u32 {
(self.0 >> 0) & 0xff
}
/// Reserved bits. Set to zero.
#[inline(always)]
pub fn reserved(&self) -> u32 {
(self.0 >> 8) & 0xffffff
}
}
impl From<u32> for HwRevision1ReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<HwRevision1ReadVal> for u32 {
#[inline(always)]
fn from(val: HwRevision1ReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LcStateReadVal(u32);
impl LcStateReadVal {
/// OT vendor test control
#[inline(always)]
pub fn state(&self) -> u32 {
(self.0 >> 0) & 0x3fffffff
}
}
impl From<u32> for LcStateReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LcStateReadVal> for u32 {
#[inline(always)]
fn from(val: LcStateReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LcTransitionCntReadVal(u32);
impl LcTransitionCntReadVal {
/// OT vendor test control
#[inline(always)]
pub fn cnt(&self) -> u32 {
(self.0 >> 0) & 0x1f
}
}
impl From<u32> for LcTransitionCntReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LcTransitionCntReadVal> for u32 {
#[inline(always)]
fn from(val: LcTransitionCntReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// This bit is set to 1 if the life cycle controller has successfully initialized and the state exposed in LC_STATE and LC_TRANSITION_CNT is valid.
#[inline(always)]
pub fn initialized(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// This bit is set to 1 if the life cycle controller has successfully initialized and is ready to accept a life cycle transition command.
#[inline(always)]
pub fn ready(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// This bit is set to 1 if the clock manager has successfully switched to the external clock due to EXT_CLOCK_EN being set to 1.
#[inline(always)]
pub fn ext_clock_switched(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// This bit is set to 1 if the last life cycle transition request was successful. Note that each transition attempt increments the LC_TRANSITION_CNT and moves the life cycle state into POST_TRANSITION.
#[inline(always)]
pub fn transition_successful(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// This bit is set to 1 if the LC_TRANSITION_CNT has reached its maximum. If this is the case, no more state transitions can be performed. Note that each transition attempt increments the LC_TRANSITION_CNT and moves the life cycle state into POST_TRANSITION.
#[inline(always)]
pub fn transition_count_error(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// This bit is set to 1 if the last transition command requested an invalid state transition (e.g. DEV -> RAW). Note that each transition attempt increments the LC_TRANSITION_CNT and moves the life cycle state into POST_TRANSITION.
#[inline(always)]
pub fn transition_error(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// This bit is set to 1 if the token supplied for a conditional transition was invalid. Note that each transition attempt increments the LC_TRANSITION_CNT and moves the life cycle state into POST_TRANSITION.
#[inline(always)]
pub fn token_error(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// This bit is set to 1 if flash failed to correctly respond to an RMA request. Note that each transition attempt increments the LC_TRANSITION_CNT and moves the life cycle state into POST_TRANSITION.
#[inline(always)]
pub fn flash_rma_error(&self) -> bool {
((self.0 >> 7) & 1) != 0
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/mbox.rs | hw/latest/registers/src/mbox.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct MboxCsr {
_priv: (),
}
impl MboxCsr {
pub const PTR: *mut u32 = 0x30020000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Mailbox lock register for mailbox access, reading 0 will set the lock
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
///
/// Read value: [`mbox::regs::LockReadVal`]; Write value: [`mbox::regs::LockWriteVal`]
#[inline(always)]
pub fn lock(&self) -> ureg::RegRef<crate::mbox::meta::Lock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Stores the AXI USER that locked the mailbox
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn user(&self) -> ureg::RegRef<crate::mbox::meta::User, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Command requested for data in mailbox
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn cmd(&self) -> ureg::RegRef<crate::mbox::meta::Cmd, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Data length for mailbox access in bytes
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RW
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dlen(&self) -> ureg::RegRef<crate::mbox::meta::Dlen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Data in register, write the next data to mailbox
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: WO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn datain(&self) -> ureg::RegRef<crate::mbox::meta::Datain, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Data out register, read the next data from mailbox
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
///
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn dataout(&self) -> ureg::RegRef<crate::mbox::meta::Dataout, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Mailbox execute register indicates to receiver that the sender is done
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: WO
///
/// Read value: [`mbox::regs::ExecuteReadVal`]; Write value: [`mbox::regs::ExecuteWriteVal`]
#[inline(always)]
pub fn execute(&self) -> ureg::RegRef<crate::mbox::meta::Execute, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Status of the mailbox command
///
/// Read value: [`mbox::regs::StatusReadVal`]; Write value: [`mbox::regs::StatusWriteVal`]
#[inline(always)]
pub fn status(&self) -> ureg::RegRef<crate::mbox::meta::Status, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Capability for uC only to force unlock the mailbox.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`mbox::regs::UnlockReadVal`]; Write value: [`mbox::regs::UnlockWriteVal`]
#[inline(always)]
pub fn unlock(&self) -> ureg::RegRef<crate::mbox::meta::Unlock, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Capability for uC to enable TAP logic to respond to mailbox commands.
/// [br]Caliptra Access: RW
/// [br]SOC Access: RO
///
/// Read value: [`mbox::regs::TapModeReadVal`]; Write value: [`mbox::regs::TapModeWriteVal`]
#[inline(always)]
pub fn tap_mode(&self) -> ureg::RegRef<crate::mbox::meta::TapMode, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct ExecuteReadVal(u32);
impl ExecuteReadVal {
#[inline(always)]
pub fn execute(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ExecuteWriteVal {
ExecuteWriteVal(self.0)
}
}
impl From<u32> for ExecuteReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ExecuteReadVal> for u32 {
#[inline(always)]
fn from(val: ExecuteReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ExecuteWriteVal(u32);
impl ExecuteWriteVal {
#[inline(always)]
pub fn execute(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for ExecuteWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ExecuteWriteVal> for u32 {
#[inline(always)]
fn from(val: ExecuteWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct LockReadVal(u32);
impl LockReadVal {
#[inline(always)]
pub fn lock(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
}
impl From<u32> for LockReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<LockReadVal> for u32 {
#[inline(always)]
fn from(val: LockReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusReadVal(u32);
impl StatusReadVal {
/// Indicates the status of mailbox command
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RW
#[inline(always)]
pub fn status(&self) -> super::enums::MboxStatusE {
super::enums::MboxStatusE::try_from((self.0 >> 0) & 0xf).unwrap()
}
/// Indicates a correctable ECC single-bit error was
/// detected and corrected while reading dataout.
/// Auto-clears when mbox_execute field is cleared.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
#[inline(always)]
pub fn ecc_single_error(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// Indicates an uncorrectable ECC double-bit error
/// was detected while reading dataout.
/// Firmware developers are advised to set the command
/// status to CMD_FAILURE in response.
/// Auto-clears when mbox_execute field is cleared.
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
#[inline(always)]
pub fn ecc_double_error(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// Indicates the present state of the mailbox FSM
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
#[inline(always)]
pub fn mbox_fsm_ps(&self) -> super::enums::MboxFsmE {
super::enums::MboxFsmE::try_from((self.0 >> 6) & 7).unwrap()
}
/// Indicates that the current lock was acquired by the SoC
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
#[inline(always)]
pub fn soc_has_lock(&self) -> bool {
((self.0 >> 9) & 1) != 0
}
/// Returns the current read pointer for the mailbox
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
#[inline(always)]
pub fn mbox_rdptr(&self) -> u32 {
(self.0 >> 10) & 0xffff
}
/// Indicates that the current lock was acquired by the TAP
/// [br]Caliptra Access: RO
/// [br]SOC Access: RO
/// [br]TAP Access [in debug/manuf mode]: RO
#[inline(always)]
pub fn tap_has_lock(&self) -> bool {
((self.0 >> 26) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> StatusWriteVal {
StatusWriteVal(self.0)
}
}
impl From<u32> for StatusReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusReadVal> for u32 {
#[inline(always)]
fn from(val: StatusReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct StatusWriteVal(u32);
impl StatusWriteVal {
/// Indicates the status of mailbox command
/// [br]Caliptra Access: RW
/// [br]SOC Access: RW
/// [br]TAP Access [in debug/manuf mode]: RW
#[inline(always)]
pub fn status(
self,
f: impl FnOnce(super::enums::selector::MboxStatusESelector) -> super::enums::MboxStatusE,
) -> Self {
Self(
(self.0 & !(0xf << 0))
| (u32::from(f(super::enums::selector::MboxStatusESelector())) << 0),
)
}
}
impl From<u32> for StatusWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<StatusWriteVal> for u32 {
#[inline(always)]
fn from(val: StatusWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct TapModeReadVal(u32);
impl TapModeReadVal {
#[inline(always)]
pub fn enabled(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> TapModeWriteVal {
TapModeWriteVal(self.0)
}
}
impl From<u32> for TapModeReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<TapModeReadVal> for u32 {
#[inline(always)]
fn from(val: TapModeReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct TapModeWriteVal(u32);
impl TapModeWriteVal {
#[inline(always)]
pub fn enabled(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for TapModeWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<TapModeWriteVal> for u32 {
#[inline(always)]
fn from(val: TapModeWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct UnlockReadVal(u32);
impl UnlockReadVal {
#[inline(always)]
pub fn unlock(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> UnlockWriteVal {
UnlockWriteVal(self.0)
}
}
impl From<u32> for UnlockReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<UnlockReadVal> for u32 {
#[inline(always)]
fn from(val: UnlockReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct UnlockWriteVal(u32);
impl UnlockWriteVal {
#[inline(always)]
pub fn unlock(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
}
impl From<u32> for UnlockWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<UnlockWriteVal> for u32 {
#[inline(always)]
fn from(val: UnlockWriteVal) -> u32 {
val.0
}
}
}
pub mod enums {
//! Enumerations used by some register fields.
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u32)]
pub enum MboxFsmE {
MboxIdle = 0,
MboxRdyForCmd = 1,
MboxRdyForData = 2,
MboxRdyForDlen = 3,
MboxExecuteSoc = 4,
Reserved5 = 5,
MboxExecuteUc = 6,
MboxError = 7,
}
impl MboxFsmE {
#[inline(always)]
pub fn mbox_idle(&self) -> bool {
*self == Self::MboxIdle
}
#[inline(always)]
pub fn mbox_rdy_for_cmd(&self) -> bool {
*self == Self::MboxRdyForCmd
}
#[inline(always)]
pub fn mbox_rdy_for_data(&self) -> bool {
*self == Self::MboxRdyForData
}
#[inline(always)]
pub fn mbox_rdy_for_dlen(&self) -> bool {
*self == Self::MboxRdyForDlen
}
#[inline(always)]
pub fn mbox_execute_soc(&self) -> bool {
*self == Self::MboxExecuteSoc
}
#[inline(always)]
pub fn mbox_execute_uc(&self) -> bool {
*self == Self::MboxExecuteUc
}
#[inline(always)]
pub fn mbox_error(&self) -> bool {
*self == Self::MboxError
}
}
impl TryFrom<u32> for MboxFsmE {
type Error = ();
#[inline(always)]
fn try_from(val: u32) -> Result<MboxFsmE, ()> {
if val < 8 {
Ok(unsafe { core::mem::transmute::<u32, MboxFsmE>(val) })
} else {
Err(())
}
}
}
impl From<MboxFsmE> for u32 {
fn from(val: MboxFsmE) -> Self {
val as u32
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u32)]
pub enum MboxStatusE {
CmdBusy = 0,
DataReady = 1,
CmdComplete = 2,
CmdFailure = 3,
Reserved4 = 4,
Reserved5 = 5,
Reserved6 = 6,
Reserved7 = 7,
Reserved8 = 8,
Reserved9 = 9,
Reserved10 = 10,
Reserved11 = 11,
Reserved12 = 12,
Reserved13 = 13,
Reserved14 = 14,
Reserved15 = 15,
}
impl MboxStatusE {
#[inline(always)]
pub fn cmd_busy(&self) -> bool {
*self == Self::CmdBusy
}
#[inline(always)]
pub fn data_ready(&self) -> bool {
*self == Self::DataReady
}
#[inline(always)]
pub fn cmd_complete(&self) -> bool {
*self == Self::CmdComplete
}
#[inline(always)]
pub fn cmd_failure(&self) -> bool {
*self == Self::CmdFailure
}
}
impl TryFrom<u32> for MboxStatusE {
type Error = ();
#[inline(always)]
fn try_from(val: u32) -> Result<MboxStatusE, ()> {
if val < 0x10 {
Ok(unsafe { core::mem::transmute::<u32, MboxStatusE>(val) })
} else {
Err(())
}
}
}
impl From<MboxStatusE> for u32 {
fn from(val: MboxStatusE) -> Self {
val as u32
}
}
pub mod selector {
pub struct MboxFsmESelector();
impl MboxFsmESelector {
#[inline(always)]
pub fn mbox_idle(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxIdle
}
#[inline(always)]
pub fn mbox_rdy_for_cmd(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxRdyForCmd
}
#[inline(always)]
pub fn mbox_rdy_for_dlen(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxRdyForDlen
}
#[inline(always)]
pub fn mbox_rdy_for_data(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxRdyForData
}
#[inline(always)]
pub fn mbox_execute_uc(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxExecuteUc
}
#[inline(always)]
pub fn mbox_execute_soc(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxExecuteSoc
}
#[inline(always)]
pub fn mbox_error(&self) -> super::MboxFsmE {
super::MboxFsmE::MboxError
}
}
pub struct MboxStatusESelector();
impl MboxStatusESelector {
#[inline(always)]
pub fn cmd_busy(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdBusy
}
#[inline(always)]
pub fn data_ready(&self) -> super::MboxStatusE {
super::MboxStatusE::DataReady
}
#[inline(always)]
pub fn cmd_complete(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdComplete
}
#[inline(always)]
pub fn cmd_failure(&self) -> super::MboxStatusE {
super::MboxStatusE::CmdFailure
}
}
}
}
pub mod meta {
//! Additional metadata needed by ureg.
pub type Lock = ureg::ReadOnlyReg32<crate::mbox::regs::LockReadVal>;
pub type User = ureg::ReadOnlyReg32<u32>;
pub type Cmd = ureg::ReadWriteReg32<0, u32, u32>;
pub type Dlen = ureg::ReadWriteReg32<0, u32, u32>;
pub type Datain = ureg::ReadWriteReg32<0, u32, u32>;
pub type Dataout = ureg::ReadWriteReg32<0, u32, u32>;
pub type Execute = ureg::ReadWriteReg32<
0,
crate::mbox::regs::ExecuteReadVal,
crate::mbox::regs::ExecuteWriteVal,
>;
pub type Status = ureg::ReadWriteReg32<
0,
crate::mbox::regs::StatusReadVal,
crate::mbox::regs::StatusWriteVal,
>;
pub type Unlock = ureg::ReadWriteReg32<
0,
crate::mbox::regs::UnlockReadVal,
crate::mbox::regs::UnlockWriteVal,
>;
pub type TapMode = ureg::ReadWriteReg32<
0,
crate::mbox::regs::TapModeReadVal,
crate::mbox::regs::TapModeWriteVal,
>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/latest/registers/src/csrng.rs | hw/latest/registers/src/csrng.rs | // Licensed under the Apache-2.0 license.
//
// generated by caliptra_registers_generator with caliptra-rtl repo at 22ef832b4d3aaa17c9cf5e63801ac5d0f21410da
//
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::erasing_op)]
#![allow(clippy::identity_op)]
/// A zero-sized type that represents ownership of this
/// peripheral, used to get access to a Register lock. Most
/// programs create one of these in unsafe code near the top of
/// main(), and pass it to the driver responsible for managing
/// all access to the hardware.
pub struct CsrngReg {
_priv: (),
}
impl CsrngReg {
pub const PTR: *mut u32 = 0x20002000 as *mut u32;
/// # Safety
///
/// Caller must ensure that all concurrent use of this
/// peripheral in the firmware is done so in a compatible
/// way. The simplest way to enforce this is to only call
/// this function once.
#[inline(always)]
pub unsafe fn new() -> Self {
Self { _priv: () }
}
/// Returns a register block that can be used to read
/// registers from this peripheral, but cannot write.
#[inline(always)]
pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
/// Return a register block that can be used to read and
/// write this peripheral's registers.
#[inline(always)]
pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> {
RegisterBlock {
ptr: Self::PTR,
mmio: core::default::Default::default(),
}
}
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>> {
ptr: *mut u32,
mmio: TMmio,
}
impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new(ptr: *mut u32) -> Self {
Self {
ptr,
mmio: core::default::Default::default(),
}
}
}
impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> {
/// # Safety
///
/// The caller is responsible for ensuring that ptr is valid for
/// volatile reads and writes at any of the offsets in this register
/// block.
#[inline(always)]
pub unsafe fn new_with_mmio(ptr: *mut u32, mmio: TMmio) -> Self {
Self { ptr, mmio }
}
/// Read value: [`csrng::regs::InterruptStateReadVal`]; Write value: [`csrng::regs::InterruptStateWriteVal`]
#[inline(always)]
pub fn interrupt_state(&self) -> ureg::RegRef<crate::csrng::meta::InterruptState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::InterruptEnableReadVal`]; Write value: [`csrng::regs::InterruptEnableWriteVal`]
#[inline(always)]
pub fn interrupt_enable(&self) -> ureg::RegRef<crate::csrng::meta::InterruptEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(4 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::InterruptTestReadVal`]; Write value: [`csrng::regs::InterruptTestWriteVal`]
#[inline(always)]
pub fn interrupt_test(&self) -> ureg::RegRef<crate::csrng::meta::InterruptTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(8 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::AlertTestReadVal`]; Write value: [`csrng::regs::AlertTestWriteVal`]
#[inline(always)]
pub fn alert_test(&self) -> ureg::RegRef<crate::csrng::meta::AlertTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0xc / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::RegwenReadVal`]; Write value: [`csrng::regs::RegwenWriteVal`]
#[inline(always)]
pub fn regwen(&self) -> ureg::RegRef<crate::csrng::meta::Regwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x10 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::CtrlReadVal`]; Write value: [`csrng::regs::CtrlWriteVal`]
#[inline(always)]
pub fn ctrl(&self) -> ureg::RegRef<crate::csrng::meta::Ctrl, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x14 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::CmdReqReadVal`]; Write value: [`csrng::regs::CmdReqWriteVal`]
#[inline(always)]
pub fn cmd_req(&self) -> ureg::RegRef<crate::csrng::meta::CmdReq, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x18 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn reseed_interval(&self) -> ureg::RegRef<crate::csrng::meta::ReseedInterval, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x1c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn reseed_counter_0(&self) -> ureg::RegRef<crate::csrng::meta::ReseedCounter0, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x20 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn reseed_counter_1(&self) -> ureg::RegRef<crate::csrng::meta::ReseedCounter1, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x24 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn reseed_counter_2(&self) -> ureg::RegRef<crate::csrng::meta::ReseedCounter2, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x28 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::SwCmdStsReadVal`]; Write value: [`csrng::regs::SwCmdStsWriteVal`]
#[inline(always)]
pub fn sw_cmd_sts(&self) -> ureg::RegRef<crate::csrng::meta::SwCmdSts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x2c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::GenbitsVldReadVal`]; Write value: [`csrng::regs::GenbitsVldWriteVal`]
#[inline(always)]
pub fn genbits_vld(&self) -> ureg::RegRef<crate::csrng::meta::GenbitsVld, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x30 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn genbits(&self) -> ureg::RegRef<crate::csrng::meta::Genbits, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x34 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::IntStateReadEnableReadVal`]; Write value: [`csrng::regs::IntStateReadEnableWriteVal`]
#[inline(always)]
pub fn int_state_read_enable(
&self,
) -> ureg::RegRef<crate::csrng::meta::IntStateReadEnable, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x38 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::IntStateReadEnableRegwenReadVal`]; Write value: [`csrng::regs::IntStateReadEnableRegwenWriteVal`]
#[inline(always)]
pub fn int_state_read_enable_regwen(
&self,
) -> ureg::RegRef<crate::csrng::meta::IntStateReadEnableRegwen, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x3c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::IntStateNumReadVal`]; Write value: [`csrng::regs::IntStateNumWriteVal`]
#[inline(always)]
pub fn int_state_num(&self) -> ureg::RegRef<crate::csrng::meta::IntStateNum, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x40 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`u32`]; Write value: [`u32`]
#[inline(always)]
pub fn int_state_val(&self) -> ureg::RegRef<crate::csrng::meta::IntStateVal, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x44 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::FipsForceReadVal`]; Write value: [`csrng::regs::FipsForceWriteVal`]
#[inline(always)]
pub fn fips_force(&self) -> ureg::RegRef<crate::csrng::meta::FipsForce, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x48 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::HwExcStsReadVal`]; Write value: [`csrng::regs::HwExcStsWriteVal`]
#[inline(always)]
pub fn hw_exc_sts(&self) -> ureg::RegRef<crate::csrng::meta::HwExcSts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x4c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::RecovAlertStsReadVal`]; Write value: [`csrng::regs::RecovAlertStsWriteVal`]
#[inline(always)]
pub fn recov_alert_sts(&self) -> ureg::RegRef<crate::csrng::meta::RecovAlertSts, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x50 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::ErrCodeReadVal`]; Write value: [`csrng::regs::ErrCodeWriteVal`]
#[inline(always)]
pub fn err_code(&self) -> ureg::RegRef<crate::csrng::meta::ErrCode, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x54 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::ErrCodeTestReadVal`]; Write value: [`csrng::regs::ErrCodeTestWriteVal`]
#[inline(always)]
pub fn err_code_test(&self) -> ureg::RegRef<crate::csrng::meta::ErrCodeTest, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x58 / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
/// Read value: [`csrng::regs::MainSmStateReadVal`]; Write value: [`csrng::regs::MainSmStateWriteVal`]
#[inline(always)]
pub fn main_sm_state(&self) -> ureg::RegRef<crate::csrng::meta::MainSmState, &TMmio> {
unsafe {
ureg::RegRef::new_with_mmio(
self.ptr.wrapping_add(0x5c / core::mem::size_of::<u32>()),
core::borrow::Borrow::borrow(&self.mmio),
)
}
}
}
pub mod regs {
//! Types that represent the values held by registers.
#[derive(Clone, Copy)]
pub struct AlertTestWriteVal(u32);
impl AlertTestWriteVal {
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn recov_alert(self, val: bool) -> Self {
Self((self.0 & !(1 << 0)) | (u32::from(val) << 0))
}
/// Write 1 to trigger one alert event of this kind.
#[inline(always)]
pub fn fatal_alert(self, val: bool) -> Self {
Self((self.0 & !(1 << 1)) | (u32::from(val) << 1))
}
}
impl From<u32> for AlertTestWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<AlertTestWriteVal> for u32 {
#[inline(always)]
fn from(val: AlertTestWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CmdReqWriteVal(u32);
impl CmdReqWriteVal {
/// Application Command: Selects one of five operations to perform.
/// The commands supported are instantiate, reseed, generate, update,
/// and uninstantiate. Each application interface port used by peripheral
/// hardware commands a unique instance number in CSRNG.
#[inline(always)]
pub fn acmd(self, val: u32) -> Self {
Self((self.0 & !(0xf << 0)) | ((val & 0xf) << 0))
}
/// Command Length: Number of 32-bit words that can optionally be appended
/// to the command. A value of zero will only transfer the command header.
/// A value of 4'hc will transfer the header plus an additional twelve
/// 32-bit words of data.
#[inline(always)]
pub fn clen(self, val: u32) -> Self {
Self((self.0 & !(0xf << 4)) | ((val & 0xf) << 4))
}
/// Command Flag0: flag0 is associated with current command. Setting this
/// field to kMultiBitBool4True will enable flag0 to be enabled. Note that
/// flag0 is used for the instantiate and reseed commands only, for all other commands its value is ignored.
#[inline(always)]
pub fn flag0(self, val: u32) -> Self {
Self((self.0 & !(0xf << 8)) | ((val & 0xf) << 8))
}
/// Generate Length: Only defined for the generate command, this field
/// is the total number of cryptographic entropy blocks requested. Each
/// unit represents 128 bits of entropy returned. The NIST reference name
/// is max_number_of_bit_per_request, and this field size supports the
/// maximum size of 219 bits. For the maximum size, this field should be
/// set to 4096, resulting in a max_number_of_bit_per_request value of
/// 4096 x 128 bits. For a smaller example, a value of 8 would return
/// a total of 1024 bits.
#[inline(always)]
pub fn glen(self, val: u32) -> Self {
Self((self.0 & !(0x1fff << 12)) | ((val & 0x1fff) << 12))
}
}
impl From<u32> for CmdReqWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CmdReqWriteVal> for u32 {
#[inline(always)]
fn from(val: CmdReqWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlReadVal(u32);
impl CtrlReadVal {
/// Setting this field to kMultiBitBool4True will enable the CSRNG module. The modules
/// of the entropy complex may only be enabled and disabled in a specific order, see
/// Programmers Guide for details.
#[inline(always)]
pub fn enable(&self) -> u32 {
(self.0 >> 0) & 0xf
}
/// Setting this field to kMultiBitBool4True will enable reading from the !!GENBITS register.
/// This application interface for software (register based) will be enabled
/// only if the otp_en_csrng_sw_app_read input vector is set to the enable encoding.
#[inline(always)]
pub fn sw_app_enable(&self) -> u32 {
(self.0 >> 4) & 0xf
}
/// Setting this field to kMultiBitBool4True will enable reading from the !!INT_STATE_VAL register.
/// Reading the internal state of the enable instances will be enabled
/// only if the otp_en_csrng_sw_app_read input vector is set to the enable encoding.
/// Also, the !!INT_STATE_READ_ENABLE bit of the selected instance needs to be set to true for this to work.
#[inline(always)]
pub fn read_int_state(&self) -> u32 {
(self.0 >> 8) & 0xf
}
/// Setting this field to kMultiBitBool4True enables forcing the FIPS/CC compliance flag to true via the !!FIPS_FORCE register.
#[inline(always)]
pub fn fips_force_enable(&self) -> u32 {
(self.0 >> 12) & 0xf
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> CtrlWriteVal {
CtrlWriteVal(self.0)
}
}
impl From<u32> for CtrlReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlReadVal> for u32 {
#[inline(always)]
fn from(val: CtrlReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct CtrlWriteVal(u32);
impl CtrlWriteVal {
/// Setting this field to kMultiBitBool4True will enable the CSRNG module. The modules
/// of the entropy complex may only be enabled and disabled in a specific order, see
/// Programmers Guide for details.
#[inline(always)]
pub fn enable(self, val: u32) -> Self {
Self((self.0 & !(0xf << 0)) | ((val & 0xf) << 0))
}
/// Setting this field to kMultiBitBool4True will enable reading from the !!GENBITS register.
/// This application interface for software (register based) will be enabled
/// only if the otp_en_csrng_sw_app_read input vector is set to the enable encoding.
#[inline(always)]
pub fn sw_app_enable(self, val: u32) -> Self {
Self((self.0 & !(0xf << 4)) | ((val & 0xf) << 4))
}
/// Setting this field to kMultiBitBool4True will enable reading from the !!INT_STATE_VAL register.
/// Reading the internal state of the enable instances will be enabled
/// only if the otp_en_csrng_sw_app_read input vector is set to the enable encoding.
/// Also, the !!INT_STATE_READ_ENABLE bit of the selected instance needs to be set to true for this to work.
#[inline(always)]
pub fn read_int_state(self, val: u32) -> Self {
Self((self.0 & !(0xf << 8)) | ((val & 0xf) << 8))
}
/// Setting this field to kMultiBitBool4True enables forcing the FIPS/CC compliance flag to true via the !!FIPS_FORCE register.
#[inline(always)]
pub fn fips_force_enable(self, val: u32) -> Self {
Self((self.0 & !(0xf << 12)) | ((val & 0xf) << 12))
}
}
impl From<u32> for CtrlWriteVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<CtrlWriteVal> for u32 {
#[inline(always)]
fn from(val: CtrlWriteVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrCodeReadVal(u32);
impl ErrCodeReadVal {
/// This bit will be set to one when an error has been detected for the
/// command stage command FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_cmd_err(&self) -> bool {
((self.0 >> 0) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// command stage genbits FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_genbits_err(&self) -> bool {
((self.0 >> 1) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// cmdreq FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_cmdreq_err(&self) -> bool {
((self.0 >> 2) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// rcstage FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_rcstage_err(&self) -> bool {
((self.0 >> 3) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// keyvrc FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_keyvrc_err(&self) -> bool {
((self.0 >> 4) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// updreq FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_updreq_err(&self) -> bool {
((self.0 >> 5) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// bencreq FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_bencreq_err(&self) -> bool {
((self.0 >> 6) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// bencack FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_bencack_err(&self) -> bool {
((self.0 >> 7) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// pdata FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_pdata_err(&self) -> bool {
((self.0 >> 8) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// final FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_final_err(&self) -> bool {
((self.0 >> 9) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// gbencack FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_gbencack_err(&self) -> bool {
((self.0 >> 10) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// grcstage FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_grcstage_err(&self) -> bool {
((self.0 >> 11) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// ggenreq FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_ggenreq_err(&self) -> bool {
((self.0 >> 12) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// gadstage FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_gadstage_err(&self) -> bool {
((self.0 >> 13) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// ggenbits FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_ggenbits_err(&self) -> bool {
((self.0 >> 14) & 1) != 0
}
/// This bit will be set to one when an error has been detected for the
/// blkenc FIFO. The type of error is reflected in the type status
/// bits (bits 28 through 30 of this register).
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn sfifo_blkenc_err(&self) -> bool {
((self.0 >> 15) & 1) != 0
}
/// This bit will be set to one when an illegal state has been detected for the
/// command stage state machine. This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn cmd_stage_sm_err(&self) -> bool {
((self.0 >> 20) & 1) != 0
}
/// This bit will be set to one when an illegal state has been detected for the
/// main state machine. This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn main_sm_err(&self) -> bool {
((self.0 >> 21) & 1) != 0
}
/// This bit will be set to one when an illegal state has been detected for the
/// ctr_drbg gen state machine. This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn drbg_gen_sm_err(&self) -> bool {
((self.0 >> 22) & 1) != 0
}
/// This bit will be set to one when an illegal state has been detected for the
/// ctr_drbg update block encode state machine. This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn drbg_updbe_sm_err(&self) -> bool {
((self.0 >> 23) & 1) != 0
}
/// This bit will be set to one when an illegal state has been detected for the
/// ctr_drbg update out block state machine. This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn drbg_updob_sm_err(&self) -> bool {
((self.0 >> 24) & 1) != 0
}
/// This bit will be set to one when an AES fatal error has been detected.
/// This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn aes_cipher_sm_err(&self) -> bool {
((self.0 >> 25) & 1) != 0
}
/// This bit will be set to one when a mismatch in any of the hardened counters
/// has been detected.
/// This error will signal a fatal alert, and also
/// an interrupt if enabled.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn cmd_gen_cnt_err(&self) -> bool {
((self.0 >> 26) & 1) != 0
}
/// This bit will be set to one when any of the source bits (bits 0 through 15 of this
/// this register) are asserted as a result of an error pulse generated from
/// any full FIFO that has been recieved a write pulse.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn fifo_write_err(&self) -> bool {
((self.0 >> 28) & 1) != 0
}
/// This bit will be set to one when any of the source bits (bits 0 through 15 of this
/// this register) are asserted as a result of an error pulse generated from
/// any empty FIFO that has recieved a read pulse.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn fifo_read_err(&self) -> bool {
((self.0 >> 29) & 1) != 0
}
/// This bit will be set to one when any of the source bits (bits 0 through 15 of this
/// this register) are asserted as a result of an error pulse generated from
/// any FIFO where both the empty and full status bits are set.
/// This bit will stay set until the next reset.
#[inline(always)]
pub fn fifo_state_err(&self) -> bool {
((self.0 >> 30) & 1) != 0
}
}
impl From<u32> for ErrCodeReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrCodeReadVal> for u32 {
#[inline(always)]
fn from(val: ErrCodeReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrCodeTestReadVal(u32);
impl ErrCodeTestReadVal {
/// Setting this field will set the bit number for which an error
/// will be forced in the hardware. This bit number is that same one
/// found in the !!ERR_CODE register. The action of writing this
/// register will force an error pulse. The sole purpose of this
/// register is to test that any error properly propagates to either
/// an interrupt or an alert.
#[inline(always)]
pub fn err_code_test(&self) -> u32 {
(self.0 >> 0) & 0x1f
}
/// Construct a WriteVal that can be used to modify the contents of this register value.
#[inline(always)]
pub fn modify(self) -> ErrCodeTestWriteVal {
ErrCodeTestWriteVal(self.0)
}
}
impl From<u32> for ErrCodeTestReadVal {
#[inline(always)]
fn from(val: u32) -> Self {
Self(val)
}
}
impl From<ErrCodeTestReadVal> for u32 {
#[inline(always)]
fn from(val: ErrCodeTestReadVal) -> u32 {
val.0
}
}
#[derive(Clone, Copy)]
pub struct ErrCodeTestWriteVal(u32);
impl ErrCodeTestWriteVal {
/// Setting this field will set the bit number for which an error
/// will be forced in the hardware. This bit number is that same one
/// found in the !!ERR_CODE register. The action of writing this
/// register will force an error pulse. The sole purpose of this
/// register is to test that any error properly propagates to either
/// an interrupt or an alert.
#[inline(always)]
pub fn err_code_test(self, val: u32) -> Self {
Self((self.0 & !(0x1f << 0)) | ((val & 0x1f) << 0))
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/verilated/build.rs | hw/verilated/build.rs | // Licensed under the Apache-2.0 license
use std::{
ffi::OsStr,
fs::File,
io::{BufRead, BufReader},
iter,
path::{Path, PathBuf},
process,
};
static DEP_FILES: &[&str] = &[
"caliptra_verilated.cpp",
"caliptra_verilated.h",
"caliptra_verilated.sv",
"out",
"Makefile",
"../config/caliptra_top_tb.vf",
];
fn cmd_args(cmd: &mut process::Command) -> Vec<&OsStr> {
iter::once(cmd.get_program())
.chain(cmd.get_args())
.collect()
}
fn run_command(cmd: &mut process::Command) {
match cmd.status() {
Err(err) => {
eprintln!("Command {:?} failed: {}", cmd_args(cmd), err);
std::process::exit(1);
}
Ok(status) => {
if !status.success() {
eprintln!("Command {:?} exit code {:?}", cmd_args(cmd), status.code());
eprintln!("Please ensure that you have verilator 5.004 or later installed");
std::process::exit(1);
}
}
}
}
fn add_filename(filename: &Path) -> impl FnOnce(std::io::Error) -> std::io::Error + '_ {
move |e| std::io::Error::new(e.kind(), format!("{filename:?}: {e}"))
}
fn sv_files(manifest_dir: &Path) -> Result<Vec<String>, std::io::Error> {
let mut result = vec![];
let filename = manifest_dir.join("../latest/rtl/src/integration/config/caliptra_top_tb.vf");
for line in BufReader::new(File::open(&filename).map_err(add_filename(&filename))?).lines() {
let line = line?;
if line.starts_with('+') {
continue;
}
result.push(line.replace("${WORKSPACE}/Caliptra", "../../.."));
}
Ok(result)
}
fn main() {
if std::env::var_os("CARGO_FEATURE_VERILATOR").is_none() {
return;
}
let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let files = match sv_files(&manifest_dir) {
Ok(files) => files,
Err(e) => panic!(
"{e}; run \"git submodule update --init\" to ensure the RTL submodule is populated."
),
};
let mut make_cmd = process::Command::new("make");
make_cmd.current_dir(&manifest_dir);
if std::env::var_os("CARGO_FEATURE_ITRNG").is_some() {
make_cmd.arg("EXTRA_VERILATOR_FLAGS=-DCALIPTRA_INTERNAL_TRNG");
}
run_command(&mut make_cmd);
for p in DEP_FILES {
println!("cargo:rerun-if-changed={}", manifest_dir.join(p).display());
}
for p in files {
println!("cargo:rerun-if-changed={}", manifest_dir.join(p).display());
}
println!("cargo:rustc-link-search={}/out", manifest_dir.display());
println!("cargo:rustc-link-lib=static=caliptra_verilated");
println!("cargo:rustc-link-lib=dylib=stdc++");
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/verilated/src/lib.rs | hw/verilated/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
--*/
mod bindings;
use std::ffi::CString;
use std::ffi::NulError;
use std::ptr::null;
pub use bindings::caliptra_verilated_init_args as InitArgs;
pub use bindings::caliptra_verilated_sig_in as SigIn;
pub use bindings::caliptra_verilated_sig_out as SigOut;
use rand::Rng;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AhbTxnType {
ReadU8,
ReadU16,
ReadU32,
ReadU64,
WriteU8,
WriteU16,
WriteU32,
WriteU64,
}
impl AhbTxnType {
pub fn is_write(&self) -> bool {
matches!(self, Self::WriteU8 | Self::WriteU16 | Self::WriteU32)
}
fn from_signals(hsize: u8, hwrite: bool) -> Self {
match (hsize, hwrite) {
(0, false) => Self::ReadU8,
(1, false) => Self::ReadU16,
(2, false) => Self::ReadU32,
(3, false) => Self::ReadU64,
(0, true) => Self::WriteU8,
(1, true) => Self::WriteU16,
(2, true) => Self::WriteU32,
(3, true) => Self::WriteU64,
_ => panic!("Unsupported hsize value 0b{hsize:b}"),
}
}
}
pub type GenericOutputWiresChangedCallbackFn = dyn Fn(&CaliptraVerilated, u64);
pub type AhbCallbackFn = dyn Fn(&CaliptraVerilated, AhbTxnType, u32, u64);
struct AhbPendingTxn {
ty: AhbTxnType,
addr: u32,
}
impl AhbPendingTxn {
fn transform_data(&self, data64: u64) -> u64 {
if matches!(self.ty, AhbTxnType::ReadU64 | AhbTxnType::WriteU64) {
data64
} else if (self.addr & 4) == 0 {
data64 & 0xffff_ffff
} else {
(data64 >> 32) & 0xffff_ffff
}
}
}
pub struct CaliptraVerilated {
v: *mut bindings::caliptra_verilated,
pub input: SigIn,
pub output: SigOut,
prev_generic_output_wires: Option<u64>,
generic_output_wires_changed_cb: Box<GenericOutputWiresChangedCallbackFn>,
ahb_cb: Box<AhbCallbackFn>,
total_cycles: u64,
ahb_txn: Option<AhbPendingTxn>,
}
impl CaliptraVerilated {
/// Constructs a new model.
pub fn new(args: InitArgs) -> Self {
Self::with_callbacks(args, Box::new(|_, _| {}), Box::new(|_, _, _, _| {}))
}
/// Creates a model that calls `generic_load_cb` whenever the
/// microcontroller CPU does a load to the generic wires.
#[allow(clippy::type_complexity)]
pub fn with_callbacks(
mut args: InitArgs,
generic_output_wires_changed_cb: Box<GenericOutputWiresChangedCallbackFn>,
ahb_cb: Box<AhbCallbackFn>,
) -> Self {
unsafe {
Self {
v: bindings::caliptra_verilated_new(&mut args),
input: Default::default(),
output: Default::default(),
generic_output_wires_changed_cb,
prev_generic_output_wires: None,
ahb_cb,
total_cycles: 0,
ahb_txn: None,
}
}
}
fn iccm_dccm_write(&mut self, addr: u32, data: [u32; 5]) {
self.input.ext_dccm_we = true;
self.input.ext_iccm_we = true;
self.input.ext_xccm_addr = addr;
self.input.ext_xccm_wdata = data;
self.next_cycle_high(1);
self.input.ext_dccm_we = false;
self.input.ext_iccm_we = false;
}
pub fn init_random_puf_state(&mut self, rng: &mut impl Rng) {
// Randomize all of ICCM and DCCM
for addr in 0..8192 {
self.iccm_dccm_write(addr, rng.gen::<[u32; 5]>());
}
}
/// Set all mailbox SRAM cells to value with double-bit ECC errors
pub fn corrupt_mailbox_ecc_double_bit(&mut self) {
for addr in 0..32768 {
self.input.ext_mbox_we = true;
self.input.ext_xccm_addr = addr;
self.input.ext_xccm_wdata = [
0x0000_0003,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
];
self.next_cycle_high(1);
self.input.ext_mbox_we = false;
}
}
/// Returns the total number of cycles since simulation start
pub fn total_cycles(&self) -> u64 {
self.total_cycles
}
/// Starts tracing to VCD file `path`, with SystemVerilog module depth
/// `depth`. If tracing was previously started to another file, that file
/// will be closed and all new traces will be written to this file.
pub fn start_tracing(&mut self, path: &str, depth: i32) -> Result<(), NulError> {
unsafe {
bindings::caliptra_verilated_trace(self.v, CString::new(path)?.as_ptr(), depth);
}
Ok(())
}
/// Stop any tracing that might have been previously started with `start_tracing()`.
pub fn stop_tracing(&mut self) {
unsafe {
bindings::caliptra_verilated_trace(self.v, null(), 0);
}
}
/// Evaluates the model into self.output, then copies all `self.input`
/// signals into psuedo flip-flops that will be visible to always_ff blocks
/// in subsequent evaluations. Typically `next_cycle_high` is used instead.
pub fn eval(&mut self) {
unsafe { bindings::caliptra_verilated_eval(self.v, &self.input, &mut self.output) }
if !self.input.core_clk {
return;
}
if Some(self.output.generic_output_wires) != self.prev_generic_output_wires {
self.prev_generic_output_wires = Some(self.output.generic_output_wires);
(self.generic_output_wires_changed_cb)(self, self.output.generic_output_wires);
}
if let Some(ahb_txn) = &self.ahb_txn {
if self.output.uc_hready {
if ahb_txn.ty.is_write() {
(self.ahb_cb)(
self,
ahb_txn.ty,
ahb_txn.addr,
ahb_txn.transform_data(self.output.uc_hwdata),
);
} else {
(self.ahb_cb)(
self,
ahb_txn.ty,
ahb_txn.addr,
ahb_txn.transform_data(self.output.uc_hrdata),
);
}
self.ahb_txn = None;
}
}
match self.output.uc_htrans {
0b00 => {}
0b10 => {
// Ignore ROM accesses
if self.output.uc_haddr >= 0x1000_0000 {
self.ahb_txn = Some(AhbPendingTxn {
ty: AhbTxnType::from_signals(self.output.uc_hsize, self.output.uc_hwrite),
addr: self.output.uc_haddr,
})
}
}
other => panic!("Unsupport htrans value 0b{:b}", other),
}
}
/// Toggles core_clk until there have been `n_cycles` rising edges.
pub fn next_cycle_high(&mut self, n_cycles: u32) {
for _ in 0..n_cycles {
self.total_cycles += 1;
loop {
self.input.core_clk = !self.input.core_clk;
self.eval();
if self.input.core_clk {
break;
}
}
}
}
/// Writes a ROM image to the RAM backing the "fake ROM". Typically this should be
/// done before asserting cptra_pwrgood and cptra_rst_b.
pub fn write_rom_image(&mut self, image: &[u8]) {
// TODO: bounds check length against ROM size?
for (addr, data) in image.chunks_exact(8).enumerate() {
// panic is impossible because an 8-byte slice-ref will always
// convert into an 8-byte array-ref.
let data = u64::from_le_bytes(data.try_into().unwrap());
self.write_rom_u64(addr as u32, data);
}
}
/// Initiates a read transaction on the SoC->Caliptra AXI bus with user
/// `pauser` and `addr`, and returns the word read from the bus.
pub fn axi_read_u32(&mut self, pauser: u32, addr: u32) -> u32 {
self.input.paddr = addr;
self.input.psel = true;
self.input.penable = false;
self.input.pwrite = false;
self.input.pauser = pauser;
self.next_cycle_high(1);
self.input.penable = true;
loop {
self.next_cycle_high(1);
if self.output.pready {
break;
}
}
self.input.psel = false;
self.input.penable = false;
self.output.prdata
}
/// Initiates a write transaction on the SoC->Caliptra AXI bus with user
/// `pauser`, `addr` and `data`.
pub fn axi_write_u32(&mut self, pauser: u32, addr: u32, data: u32) {
self.input.paddr = addr;
self.input.psel = true;
self.input.penable = false;
self.input.pwrite = true;
self.input.pwdata = data;
self.input.pauser = pauser;
self.next_cycle_high(1);
self.input.penable = true;
loop {
self.next_cycle_high(1);
if self.output.pready {
break;
}
}
self.input.psel = false;
self.input.penable = false;
self.input.pwrite = false;
self.input.pwdata = 0;
}
fn write_rom_u64(&mut self, addr: u32, data: u64) {
self.input.imem_addr = addr;
self.input.imem_wdata = data;
self.input.imem_we = true;
self.next_cycle_high(1);
self.input.imem_we = false;
}
}
impl Drop for CaliptraVerilated {
fn drop(&mut self) {
unsafe { bindings::caliptra_verilated_destroy(self.v) }
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
// Additional tests in hw-model/src/model_verilated.rs
#[test]
fn test_tracing() {
if !cfg!(feature = "verilator") {
return;
}
let mut v = CaliptraVerilated::new(InitArgs {
security_state: 0,
cptra_obf_key: [0u32; 8],
});
std::fs::remove_file("/tmp/caliptra_verilated_test.vcd").ok();
std::fs::remove_file("/tmp/caliptra_verilated_test2.vcd").ok();
assert!(!Path::new("/tmp/caliptra_verilated_test.vcd").exists());
assert!(!Path::new("/tmp/caliptra_verilated_test2.vcd").exists());
v.start_tracing("/tmp/caliptra_verilated_test.vcd", 99)
.unwrap();
v.next_cycle_high(2);
v.start_tracing("/tmp/caliptra_verilated_test2.vcd", 99)
.unwrap();
v.next_cycle_high(2);
assert!(Path::new("/tmp/caliptra_verilated_test.vcd").exists());
assert!(Path::new("/tmp/caliptra_verilated_test2.vcd").exists());
v.stop_tracing();
v.next_cycle_high(2);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/verilated/src/bindings/mod.rs | hw/verilated/src/bindings/mod.rs | /*++
Licensed under the Apache-2.0 license.
--*/
#[allow(dead_code)]
mod real;
pub use real::{
caliptra_verilated, caliptra_verilated_init_args, caliptra_verilated_sig_in,
caliptra_verilated_sig_out,
};
#[cfg(not(feature = "verilator"))]
mod disabled {
use super::*;
const MSG: &str = "Built without verilator support; use --features=verilator to enable";
pub unsafe fn caliptra_verilated_new(
_args: *mut caliptra_verilated_init_args,
) -> *mut caliptra_verilated {
panic!("{}", MSG);
}
pub unsafe fn caliptra_verilated_destroy(_model: *mut caliptra_verilated) {
panic!("{}", MSG);
}
pub unsafe fn caliptra_verilated_trace(
_model: *mut caliptra_verilated,
_vcd_out_path: *const ::std::os::raw::c_char,
_depth: ::std::os::raw::c_int,
) {
panic!("{}", MSG);
}
pub unsafe fn caliptra_verilated_eval(
_model: *mut caliptra_verilated,
_in_: *const caliptra_verilated_sig_in,
_out: *mut caliptra_verilated_sig_out,
) {
panic!("{}", MSG);
}
}
#[cfg(feature = "verilator")]
pub use real::*;
#[cfg(not(feature = "verilator"))]
pub use disabled::*;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw/verilated/src/bindings/real.rs | hw/verilated/src/bindings/real.rs | /*++
Licensed under the Apache-2.0 license.
--*/
// generated by src/integration/verilated/generate_rust_bindings.sh
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct caliptra_verilated {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct caliptra_verilated_sig_in {
pub core_clk: bool,
pub cptra_pwrgood: bool,
pub cptra_rst_b: bool,
pub paddr: u32,
pub pprot: u8,
pub psel: bool,
pub penable: bool,
pub pwrite: bool,
pub pwdata: u32,
pub pauser: u32,
pub imem_we: bool,
pub imem_addr: u32,
pub imem_wdata: u64,
pub itrng_data: u8,
pub itrng_valid: bool,
pub sram_error_injection_mode: u8,
pub ext_iccm_we: bool,
pub ext_dccm_we: bool,
pub ext_mbox_we: bool,
pub ext_xccm_addr: u32,
pub ext_xccm_wdata: [u32; 5usize],
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct caliptra_verilated_sig_out {
pub ready_for_fuses: bool,
pub ready_for_fw_push: bool,
pub pready: bool,
pub pslverr: bool,
pub prdata: u32,
pub generic_output_wires: u64,
pub etrng_req: bool,
pub uc_haddr: u32,
pub uc_hburst: u8,
pub uc_hmastlock: bool,
pub uc_hprot: u8,
pub uc_hsize: u8,
pub uc_htrans: u8,
pub uc_hwrite: bool,
pub uc_hwdata: u64,
pub uc_hrdata: u64,
pub uc_hready: bool,
pub uc_hresp: bool,
pub cptra_error_fatal: bool,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct caliptra_verilated_init_args {
pub security_state: u32,
pub cptra_obf_key: [u32; 8usize],
}
extern "C" {
pub fn caliptra_verilated_new(
args: *mut caliptra_verilated_init_args,
) -> *mut caliptra_verilated;
}
extern "C" {
pub fn caliptra_verilated_destroy(model: *mut caliptra_verilated);
}
extern "C" {
pub fn caliptra_verilated_trace(
model: *mut caliptra_verilated,
vcd_out_path: *const ::std::os::raw::c_char,
depth: ::std::os::raw::c_int,
);
}
extern "C" {
pub fn caliptra_verilated_eval(
model: *mut caliptra_verilated,
in_: *const caliptra_verilated_sig_in,
out: *mut caliptra_verilated_sig_out,
);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/auth-manifest/app/src/config.rs | auth-manifest/app/src/config.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
config.rs
Abstract:
File contains utilities for parsing image authorization configuration files
--*/
use anyhow::Context;
use caliptra_auth_man_gen::AuthManifestGeneratorKeyConfig;
use caliptra_auth_man_types::ImageMetadataFlags;
use caliptra_auth_man_types::{
Addr64, AuthManifestImageMetadata, AuthManifestPrivKeysConfig, AuthManifestPubKeysConfig,
};
#[cfg(feature = "openssl")]
use caliptra_image_crypto::OsslCrypto as Crypto;
#[cfg(feature = "rustcrypto")]
use caliptra_image_crypto::RustCrypto as Crypto;
use caliptra_image_crypto::{lms_priv_key_from_pem, lms_pub_key_from_pem};
use caliptra_image_gen::*;
use serde_derive::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Authorization Manifest Key configuration from config file.
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct AuthManifestKeyConfigFromFile {
pub ecc_pub_key: String,
pub ecc_priv_key: Option<String>,
pub lms_pub_key: String,
pub lms_priv_key: Option<String>,
pub mldsa_pub_key: String,
pub mldsa_priv_key: Option<String>,
}
#[derive(Serialize, Deserialize)]
pub struct ImageMetadataConfigFromFile {
digest: String,
source: u32,
fw_id: u32,
exec_bit: u32,
ignore_auth_check: bool,
component_id: u32,
image_load_address: u64,
image_staging_address: u64,
classification: u32,
}
// Authorization Manifest configuration from TOML file
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct AuthManifestConfigFromFile {
pub vendor_fw_key_config: Option<AuthManifestKeyConfigFromFile>,
pub vendor_man_key_config: Option<AuthManifestKeyConfigFromFile>,
pub owner_fw_key_config: Option<AuthManifestKeyConfigFromFile>,
pub owner_man_key_config: Option<AuthManifestKeyConfigFromFile>,
pub image_metadata_list: Vec<ImageMetadataConfigFromFile>,
}
/// Load Authorization Manifest Key Configuration from file
pub(crate) fn load_auth_man_config_from_file(
path: &PathBuf,
) -> anyhow::Result<AuthManifestConfigFromFile> {
let config_str = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read the config file {}", path.display()))?;
let config: AuthManifestConfigFromFile = toml::from_str(&config_str)
.with_context(|| format!("Failed to parse the config file {}", path.display()))?;
Ok(config)
}
fn key_config_from_file(
path: &Path,
config: &AuthManifestKeyConfigFromFile,
) -> anyhow::Result<AuthManifestGeneratorKeyConfig> {
// Get the Private Keys.
let mut priv_keys = AuthManifestPrivKeysConfig::default();
if let Some(pem_file) = &config.ecc_priv_key {
let priv_key_path = path.join(pem_file);
priv_keys.ecc_priv_key = Crypto::ecc_priv_key_from_pem(&priv_key_path)?;
}
if let Some(pem_file) = &config.lms_priv_key {
let priv_key_path = path.join(pem_file);
priv_keys.lms_priv_key = lms_priv_key_from_pem(&priv_key_path)?;
}
if let Some(pem_file) = &config.mldsa_priv_key {
let priv_key_path = path.join(pem_file);
priv_keys.mldsa_priv_key = Crypto::mldsa_priv_key_from_file(&priv_key_path)?;
}
Ok(AuthManifestGeneratorKeyConfig {
pub_keys: AuthManifestPubKeysConfig {
ecc_pub_key: Crypto::ecc_pub_key_from_pem(&path.join(&config.ecc_pub_key))?,
lms_pub_key: lms_pub_key_from_pem(&path.join(&config.lms_pub_key))?,
mldsa_pub_key: Crypto::mldsa_pub_key_from_file(&path.join(&config.mldsa_pub_key))?,
},
priv_keys: Some(priv_keys),
})
}
pub(crate) fn optional_key_config_from_file(
path: &Path,
config: &Option<AuthManifestKeyConfigFromFile>,
) -> anyhow::Result<Option<AuthManifestGeneratorKeyConfig>> {
if let Some(config) = config {
let gen_config = key_config_from_file(path, config)?;
Ok(Some(gen_config))
} else {
Ok(None)
}
}
pub(crate) fn image_metadata_config_from_file(
config: &Vec<ImageMetadataConfigFromFile>,
) -> anyhow::Result<Vec<AuthManifestImageMetadata>> {
let mut image_metadata_list = Vec::new();
let mut fw_ids: Vec<u32> = Vec::new();
for image in config {
// Check if the firmware ID is already present in the list.
if fw_ids.contains(&image.fw_id) {
return Err(anyhow::anyhow!(
"Duplicate firmware ID found in the image metadata list"
));
} else {
fw_ids.push(image.fw_id);
}
let digest_vec = hex::decode(&image.digest)?;
let mut flags = ImageMetadataFlags(0);
flags.set_ignore_auth_check(image.ignore_auth_check);
flags.set_image_source(image.source);
flags.set_exec_bit(image.exec_bit);
let image_metadata = AuthManifestImageMetadata {
fw_id: image.fw_id,
flags: flags.0,
digest: digest_vec.try_into().unwrap(),
component_id: image.component_id,
image_load_address: {
let addr = image.image_load_address;
Addr64 {
lo: (addr & 0xFFFFFFFF) as u32,
hi: (addr >> 32) as u32,
}
},
image_staging_address: {
let addr = image.image_staging_address;
Addr64 {
lo: (addr & 0xFFFFFFFF) as u32,
hi: (addr >> 32) as u32,
}
},
classification: image.classification,
};
image_metadata_list.push(image_metadata);
}
Ok(image_metadata_list)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/auth-manifest/app/src/main.rs | auth-manifest/app/src/main.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
Main entry point for Caliptra Authorization Manifest application
--*/
use anyhow::Context;
use caliptra_auth_man_gen::{AuthManifestGenerator, AuthManifestGeneratorConfig};
use caliptra_auth_man_types::AuthManifestFlags;
#[cfg(feature = "openssl")]
use caliptra_image_crypto::OsslCrypto as Crypto;
#[cfg(feature = "rustcrypto")]
use caliptra_image_crypto::RustCrypto as Crypto;
use caliptra_image_types::FwVerificationPqcKeyType;
use clap::ArgMatches;
use clap::{arg, value_parser, Command};
use std::io::Write;
use std::path::PathBuf;
use zerocopy::IntoBytes;
mod config;
/// Entry point
fn main() {
let sub_cmds = vec![Command::new("create-auth-man")
.about("Create a new authorization manifest")
.arg(
arg!(--"version" <U32> "Manifest Version Number")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"svn" <U32> "Manifest Security Version Number")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"flags" <U32> "Manifest Flags")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"key-dir" <FILE> "Key files directory path")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"config" <FILE> "Manifest configuration file")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"pqc-key-type" <U32> "Type of PQC key validation: 1: MLDSA; 3: LMS")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"out" <FILE> "Output file")
.required(true)
.value_parser(value_parser!(PathBuf)),
)];
let cmd = Command::new("caliptra-auth-man-app")
.arg_required_else_help(true)
.subcommands(sub_cmds)
.about("Caliptra authorization manifest tools")
.get_matches();
let result = match cmd.subcommand().unwrap() {
("create-auth-man", args) => run_auth_man_cmd(args),
(_, _) => unreachable!(),
};
result.unwrap();
}
pub(crate) fn run_auth_man_cmd(args: &ArgMatches) -> anyhow::Result<()> {
let version: &u32 = args
.get_one::<u32>("version")
.with_context(|| "version arg not specified")?;
let svn: &u32 = args
.get_one::<u32>("svn")
.with_context(|| "svn arg not specified")?;
if *svn > 128 {
return Err(anyhow::anyhow!("Invalid SVN value"));
}
let flags: AuthManifestFlags = AuthManifestFlags::from_bits_truncate(
*args
.get_one::<u32>("flags")
.with_context(|| "flags arg not specified")?,
);
let pqc_key_type: &u32 = args
.get_one::<u32>("pqc-key-type")
.with_context(|| "Type of PQC key validation: 1: MLDSA; 3: LMS")?;
let pqc_key_type = match *pqc_key_type {
1 => FwVerificationPqcKeyType::MLDSA,
3 => FwVerificationPqcKeyType::LMS,
_ => return Err(anyhow::anyhow!("Invalid PQC key type")),
};
let config_path: &PathBuf = args
.get_one::<PathBuf>("config")
.with_context(|| "config arg not specified")?;
if !config_path.exists() {
return Err(anyhow::anyhow!("Invalid config file path"));
}
let key_dir: &PathBuf = args
.get_one::<PathBuf>("key-dir")
.with_context(|| "key-dir arg not specified")?;
if !key_dir.exists() {
return Err(anyhow::anyhow!("Invalid key directory path"));
}
let out_path: &PathBuf = args
.get_one::<PathBuf>("out")
.with_context(|| "out arg not specified")?;
// Load the manifest configuration from the config file.
let config = config::load_auth_man_config_from_file(config_path)?;
// Decode the configuration.
let gen_config = AuthManifestGeneratorConfig {
version: *version,
svn: *svn,
flags,
pqc_key_type,
vendor_man_key_info: config::optional_key_config_from_file(
key_dir,
&config.vendor_man_key_config,
)?,
owner_man_key_info: config::optional_key_config_from_file(
key_dir,
&config.owner_man_key_config,
)?,
vendor_fw_key_info: config::optional_key_config_from_file(
key_dir,
&config.vendor_fw_key_config,
)?,
owner_fw_key_info: config::optional_key_config_from_file(
key_dir,
&config.owner_fw_key_config,
)?,
image_metadata_list: config::image_metadata_config_from_file(&config.image_metadata_list)?,
};
let gen = AuthManifestGenerator::new(Crypto::default());
let manifest = gen.generate(&gen_config).unwrap();
let mut out_file = std::fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(out_path)
.with_context(|| format!("Failed to create file {}", out_path.display()))?;
out_file.write_all(manifest.as_bytes())?;
Ok(())
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.