use crate::bootrom::{self, BootRomError};
pub type Error = BootRomError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SecurityLevel {
Secure,
NonSecure,
Bootloader,
}
impl SecurityLevel {
const fn bits(self) -> u32 {
match self {
Self::Secure => 1,
Self::NonSecure => 2,
Self::Bootloader => 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum AddressSpace {
Storage,
Runtime,
}
impl AddressSpace {
const fn bits(self) -> u32 {
match self {
Self::Storage => 0,
Self::Runtime => 1,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum Op {
Erase,
Program,
Read,
}
impl Op {
const fn bits(self) -> u32 {
match self {
Self::Erase => 0,
Self::Program => 1,
Self::Read => 2,
}
}
}
const ASPACE_LSB: u32 = 0;
const SECLEVEL_LSB: u32 = 8;
const OP_LSB: u32 = 16;
const fn cflash(op: Op, space: AddressSpace, level: SecurityLevel) -> u32 {
(op.bits() << OP_LSB) | (space.bits() << ASPACE_LSB) | (level.bits() << SECLEVEL_LSB)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Options {
space: AddressSpace,
level: SecurityLevel,
}
impl Options {
pub const fn new() -> Self {
Self {
space: AddressSpace::Runtime,
level: SecurityLevel::Secure,
}
}
pub const fn storage(self) -> Self {
Self {
space: AddressSpace::Storage,
level: self.level,
}
}
pub const fn security_level(self, level: SecurityLevel) -> Self {
Self {
space: self.space,
level,
}
}
pub fn erase(self, addr: u32, len: u32) -> Result<(), Error> {
self.run(Op::Erase, addr, len, core::ptr::null_mut())
}
pub fn program(self, addr: u32, data: &[u8]) -> Result<(), Error> {
self.run(
Op::Program,
addr,
data.len() as u32,
data.as_ptr().cast_mut(),
)
}
pub fn read(self, addr: u32, data: &mut [u8]) -> Result<(), Error> {
self.run(Op::Read, addr, data.len() as u32, data.as_mut_ptr())
}
fn run(self, op: Op, addr: u32, len: u32, buffer: *mut u8) -> Result<(), Error> {
let flags = cflash(op, self.space, self.level);
let rc = unsafe { bootrom::flash_op(flags, addr, len, buffer) };
if rc < 0 {
return Err(BootRomError::from(rc));
}
Ok(())
}
}
impl Default for Options {
fn default() -> Self {
Self::new()
}
}
pub fn erase(addr: u32, len: u32) -> Result<(), Error> {
Options::new().erase(addr, len)
}
pub fn program(addr: u32, data: &[u8]) -> Result<(), Error> {
Options::new().program(addr, data)
}
pub fn read(addr: u32, data: &mut [u8]) -> Result<(), Error> {
Options::new().read(addr, data)
}