use core::fmt;
use embedded_hal_async::spi::{Operation, SpiDevice};
use std::time::Duration;
use crate::catalog::lookup_fallback;
use crate::profile::{AddressWidth, EraseMenu, ErasePlan, FlashProfile, ProfileSource, plan_erase};
use crate::sfdp::{Bfpt, ParamHeader, SfdpHeader};
const CMD_RDID: u8 = 0x9F;
const CMD_WREN: u8 = 0x06;
const CMD_WRSR: u8 = 0x01; const CMD_RDSR: u8 = 0x05;
const CMD_READ: u8 = 0x03;
const CMD_PP: u8 = 0x02;
const CMD_CE: u8 = 0xC7; const CMD_SFDP: u8 = 0x5A; const CMD_EN4B: u8 = 0xB7; const CMD_RSTEN: u8 = 0x66; const CMD_RST: u8 = 0x99; const CMD_RELEASE_PD: u8 = 0xAB; const SR_WIP: u8 = 0x01;
const SR_BP_MASK: u8 = 0x1C;
fn push_cmd_addr(cmd: &mut Vec<u8>, opcode: u8, addr: u32, width: AddressWidth) {
cmd.push(opcode);
if width.is_four_byte() {
cmd.push((addr >> 24) as u8);
}
cmd.push((addr >> 16) as u8);
cmd.push((addr >> 8) as u8);
cmd.push(addr as u8);
}
pub const PAGE_SIZE: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlashId {
pub manufacturer: u8,
pub mem_type: u8,
pub capacity_code: u8,
}
impl FlashId {
pub fn capacity_bytes(&self) -> Option<usize> {
match self.capacity_code {
0x10..=0x1B => Some(1usize << self.capacity_code),
_ => None,
}
}
pub fn is_present(&self) -> bool {
self.manufacturer != 0x00 && self.manufacturer != 0xFF
}
pub fn jedec(&self) -> [u8; 3] {
[self.manufacturer, self.mem_type, self.capacity_code]
}
}
impl fmt::Display for FlashId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"mfr=0x{:02X} type=0x{:02X} cap=0x{:02X}",
self.manufacturer, self.mem_type, self.capacity_code
)?;
if let Some(n) = self.capacity_bytes() {
write!(f, " ({} KiB)", n / 1024)?;
}
Ok(())
}
}
pub trait BusAccess {
type Error: fmt::Debug;
fn acquire(&mut self) -> Result<(), Self::Error>;
fn release(&mut self) -> Result<(), Self::Error>;
}
#[derive(Debug)]
pub enum FlashError<S: fmt::Debug, R: fmt::Debug> {
Spi(S),
Bus(R),
Timeout,
VerifyMismatch {
addr: usize,
expected: u8,
got: u8,
},
NoFlash,
UnsupportedChip {
jedec: [u8; 3],
},
NotDetected,
}
impl<S: fmt::Debug, R: fmt::Debug> fmt::Display for FlashError<S, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FlashError::Spi(e) => write!(f, "SPI error: {e:?}"),
FlashError::Bus(e) => write!(f, "bus-hold error: {e:?}"),
FlashError::Timeout => write!(f, "timed out waiting for flash WIP to clear"),
FlashError::VerifyMismatch {
addr,
expected,
got,
} => write!(
f,
"verify mismatch @0x{addr:06X}: expected 0x{expected:02X}, got 0x{got:02X}"
),
FlashError::NoFlash => write!(f, "no SPI-NOR flash detected (RDID read all 0x00/0xFF)"),
FlashError::UnsupportedChip { jedec } => write!(
f,
"unsupported flash: JEDEC {jedec:02X?} has no SFDP and no fallback-table entry (add one)"
),
FlashError::NotDetected => write!(f, "flash geometry unknown; run `detect` first"),
}
}
}
impl<S: fmt::Debug, R: fmt::Debug> std::error::Error for FlashError<S, R> {}
pub struct Flasher<SPI, RST> {
spi: SPI,
reset: RST,
max_chunk: usize,
poll_interval: Duration,
poll_timeout: Duration,
profile: Option<FlashProfile>,
}
impl<SPI, RST> Flasher<SPI, RST>
where
SPI: SpiDevice,
RST: BusAccess,
{
pub fn with_config(
spi: SPI,
reset: RST,
max_chunk: usize,
poll_interval: Duration,
poll_timeout: Duration,
) -> Self {
assert!(max_chunk >= 4, "max_chunk must be >= 4");
Self {
spi,
reset,
max_chunk,
poll_interval,
poll_timeout,
profile: None,
}
}
fn spi_err(e: SPI::Error) -> FlashError<SPI::Error, RST::Error> {
FlashError::Spi(e)
}
fn bus_err(e: RST::Error) -> FlashError<SPI::Error, RST::Error> {
FlashError::Bus(e)
}
pub async fn read_id(&mut self) -> Result<FlashId, FlashError<SPI::Error, RST::Error>> {
let mut id = [0u8; 3];
self.spi
.transaction(&mut [Operation::Write(&[CMD_RDID]), Operation::Read(&mut id)])
.await
.map_err(Self::spi_err)?;
Ok(FlashId {
manufacturer: id[0],
mem_type: id[1],
capacity_code: id[2],
})
}
pub async fn read_sfdp(
&mut self,
addr: u32,
buf: &mut [u8],
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let a = addr.to_be_bytes();
let header = [CMD_SFDP, a[1], a[2], a[3], 0x00]; self.spi
.transaction(&mut [Operation::Write(&header), Operation::Read(buf)])
.await
.map_err(Self::spi_err)
}
async fn write_enable(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.spi
.transaction(&mut [Operation::Write(&[CMD_WREN])])
.await
.map_err(Self::spi_err)
}
async fn enter_4byte(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.spi
.transaction(&mut [Operation::Write(&[CMD_EN4B])])
.await
.map_err(Self::spi_err)
}
async fn read_status(&mut self) -> Result<u8, FlashError<SPI::Error, RST::Error>> {
let mut sr = [0u8; 1];
self.spi
.transaction(&mut [Operation::Write(&[CMD_RDSR]), Operation::Read(&mut sr)])
.await
.map_err(Self::spi_err)?;
Ok(sr[0])
}
async fn wait_ready(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let poll_timeout = self.poll_timeout;
let poll = async {
loop {
if self.read_status().await? & SR_WIP == 0 {
return Ok::<(), FlashError<SPI::Error, RST::Error>>(());
}
tokio::time::sleep(self.poll_interval).await;
}
};
match tokio::time::timeout(poll_timeout, poll).await {
Ok(r) => r,
Err(_) => Err(FlashError::Timeout),
}
}
pub fn profile(&self) -> Option<&FlashProfile> {
self.profile.as_ref()
}
pub fn set_profile(&mut self, profile: FlashProfile) {
self.profile = Some(profile);
}
fn require_profile(&self) -> Result<&FlashProfile, FlashError<SPI::Error, RST::Error>> {
self.profile.as_ref().ok_or(FlashError::NotDetected)
}
pub async fn detect_profile(
&mut self,
) -> Result<FlashProfile, FlashError<SPI::Error, RST::Error>> {
let id = self.read_id().await?;
if !id.is_present() {
return Err(FlashError::NoFlash);
}
if let Some(profile) = self.try_sfdp_profile(id).await? {
return self.adopt_profile(profile).await;
}
if let Some(profile) = lookup_fallback(id.jedec()) {
return self.adopt_profile(profile).await;
}
Err(FlashError::UnsupportedChip { jedec: id.jedec() })
}
async fn adopt_profile(
&mut self,
profile: FlashProfile,
) -> Result<FlashProfile, FlashError<SPI::Error, RST::Error>> {
if profile.address_width.is_four_byte() {
self.enter_4byte().await?;
}
self.set_profile(profile.clone());
Ok(profile)
}
async fn try_sfdp_profile(
&mut self,
id: FlashId,
) -> Result<Option<FlashProfile>, FlashError<SPI::Error, RST::Error>> {
let mut header = [0u8; 8];
self.read_sfdp(0, &mut header).await?;
let Some(h) = SfdpHeader::parse(&header) else {
return Ok(None);
};
let mut bfpt_ph = None;
for i in 0..h.param_header_count() {
let mut ph = [0u8; 8];
self.read_sfdp(8 + (i as u32) * 8, &mut ph).await?;
if let Some(p) = ParamHeader::parse(&ph)
&& p.id == ParamHeader::BFPT_ID
{
bfpt_ph = Some(p);
break;
}
}
let Some(p) = bfpt_ph else {
return Ok(None);
};
let mut bytes = vec![0u8; p.length_dwords as usize * 4];
self.read_sfdp(p.table_pointer, &mut bytes).await?;
let bfpt = Bfpt::parse(&bytes);
let Some(erase) = EraseMenu::new(bfpt.erase_types) else {
return Ok(None); };
Ok(Some(FlashProfile {
page_size: bfpt.page_size,
address_width: bfpt.address_width,
capacity: bfpt.capacity.or(id.capacity_bytes()),
erase,
source: ProfileSource::Sfdp,
sfdp_revision: Some((h.major, h.minor)),
}))
}
async fn erase_op(
&mut self,
addr: u32,
opcode: u8,
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let width = self.require_profile()?.address_width;
self.write_enable().await?;
let mut header = Vec::with_capacity(1 + width.bytes() as usize);
push_cmd_addr(&mut header, opcode, addr, width);
self.spi
.transaction(&mut [Operation::Write(&header)])
.await
.map_err(Self::spi_err)?;
self.wait_ready().await
}
pub async fn chip_erase(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.write_enable().await?;
self.spi
.transaction(&mut [Operation::Write(&[CMD_CE])])
.await
.map_err(Self::spi_err)?;
self.wait_ready().await
}
pub async fn unprotect(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.write_enable().await?;
self.spi
.transaction(&mut [Operation::Write(&[CMD_WRSR, 0x00])])
.await
.map_err(Self::spi_err)?;
self.wait_ready().await
}
pub async fn is_protected(&mut self) -> Result<bool, FlashError<SPI::Error, RST::Error>> {
Ok(self.read_status().await? & SR_BP_MASK != 0)
}
pub async fn protect(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.write_enable().await?;
self.spi
.transaction(&mut [Operation::Write(&[CMD_WRSR, SR_BP_MASK])])
.await
.map_err(Self::spi_err)?;
self.wait_ready().await
}
pub async fn reset_flash(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.spi
.transaction(&mut [Operation::Write(&[CMD_RSTEN])])
.await
.map_err(Self::spi_err)?;
self.spi
.transaction(&mut [Operation::Write(&[CMD_RST])])
.await
.map_err(Self::spi_err)
}
pub fn erase_plan(
&self,
offset: usize,
len: usize,
) -> Result<ErasePlan, FlashError<SPI::Error, RST::Error>> {
Ok(plan_erase(self.require_profile()?, offset, len))
}
pub async fn run_erase(
&mut self,
plan: &ErasePlan,
mut progress: impl FnMut(usize),
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
for (i, op) in plan.ops().iter().enumerate() {
self.erase_op(op.addr as u32, op.ty.opcode).await?;
progress(i + 1);
}
Ok(())
}
pub async fn erase_range(
&mut self,
offset: usize,
len: usize,
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let plan = self.erase_plan(offset, len)?;
self.run_erase(&plan, |_| {}).await
}
async fn page_program(
&mut self,
addr: u32,
data: &[u8],
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let width = self.require_profile()?.address_width;
self.write_enable().await?;
let mut header = Vec::with_capacity(1 + width.bytes() as usize);
push_cmd_addr(&mut header, CMD_PP, addr, width);
let mut ops: Vec<Operation<'_, u8>> =
Vec::with_capacity(1 + data.len() / self.max_chunk + 1);
ops.push(Operation::Write(&header));
for chunk in data.chunks(self.max_chunk) {
ops.push(Operation::Write(chunk));
}
self.spi
.transaction(&mut ops)
.await
.map_err(Self::spi_err)?;
self.wait_ready().await
}
pub async fn program(
&mut self,
offset: usize,
data: &[u8],
mut progress: impl FnMut(usize),
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let page = self.require_profile()?.page_size;
let mut written = 0;
while written < data.len() {
let addr = offset + written;
let page_left = page - (addr % page);
let n = page_left.min(data.len() - written);
self.page_program(addr as u32, &data[written..written + n])
.await?;
written += n;
progress(written);
}
Ok(())
}
pub async fn read(
&mut self,
offset: usize,
buf: &mut [u8],
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let width = self.require_profile()?.address_width;
let mut done = 0;
while done < buf.len() {
let mut header = Vec::with_capacity(1 + width.bytes() as usize);
push_cmd_addr(&mut header, CMD_READ, (offset + done) as u32, width);
let n = self.max_chunk.min(buf.len() - done);
self.spi
.transaction(&mut [
Operation::Write(&header),
Operation::Read(&mut buf[done..done + n]),
])
.await
.map_err(Self::spi_err)?;
done += n;
}
Ok(())
}
pub async fn verify(
&mut self,
offset: usize,
expected: &[u8],
mut progress: impl FnMut(usize),
) -> Result<(), FlashError<SPI::Error, RST::Error>> {
let mut done = 0;
let mut buf = vec![0u8; self.max_chunk];
while done < expected.len() {
let n = self.max_chunk.min(expected.len() - done);
self.read(offset + done, &mut buf[..n]).await?;
for i in 0..n {
if buf[i] != expected[done + i] {
return Err(FlashError::VerifyMismatch {
addr: offset + done + i,
expected: expected[done + i],
got: buf[i],
});
}
}
done += n;
progress(done);
}
Ok(())
}
pub async fn wake(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.spi
.transaction(&mut [Operation::Write(&[CMD_RELEASE_PD])])
.await
.map_err(Self::spi_err)?;
tokio::time::sleep(Duration::from_micros(50)).await;
Ok(())
}
pub async fn acquire_bus(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.reset.acquire().map_err(Self::bus_err)?;
if let Err(e) = self.wake().await {
let _ = self.release_bus(); return Err(e);
}
Ok(())
}
pub fn release_bus(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
self.reset.release().map_err(Self::bus_err)
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::testfakes::{FakeBus, FakeFlash, flasher};
const BLOCK_SIZE: usize = 64 * 1024;
#[test]
fn capacity_decode() {
let id = FlashId {
manufacturer: 0x20,
mem_type: 0x20,
capacity_code: 0x15,
};
assert_eq!(id.capacity_bytes(), Some(2 * 1024 * 1024)); let bad = FlashId {
manufacturer: 0,
mem_type: 0,
capacity_code: 0x00,
};
assert_eq!(bad.capacity_bytes(), None);
}
#[tokio::test]
async fn read_id_returns_jedec() {
let flash = FakeFlash::new(2 * 1024 * 1024, [0x20, 0x20, 0x15]);
let mut f = flasher(flash, FakeBus::new(), 256);
let id = f.read_id().await.unwrap();
assert_eq!(
id,
FlashId {
manufacturer: 0x20,
mem_type: 0x20,
capacity_code: 0x15
}
);
assert_eq!(id.capacity_bytes(), Some(2 * 1024 * 1024));
}
#[tokio::test]
async fn wait_ready_polls_until_wip_clears() {
let flash = FakeFlash::new(1024, [0x20, 0x20, 0x15]);
flash.set_busy_reads(3); let mut f = flasher(flash, FakeBus::new(), 256);
f.write_enable().await.unwrap();
assert_eq!(f.read_status().await.unwrap() & 0x02, 0x02); f.wait_ready().await.unwrap(); }
#[tokio::test]
async fn wait_ready_times_out() {
let flash = FakeFlash::new(1024, [0x20, 0x20, 0x15]);
flash.set_busy_reads(u32::MAX); let mut f =
Flasher::with_config(flash, FakeBus::new(), 256, Duration::ZERO, Duration::ZERO);
assert!(matches!(f.wait_ready().await, Err(FlashError::Timeout)));
}
#[tokio::test]
async fn erase_range_sets_ff_across_covered_blocks() {
let size = 256 * 1024; let flash = FakeFlash::new(size, [0x20, 0x20, 0x15]);
for i in 0..size {
flash.preset(i, &[0x00]);
} let probe = flash.clone();
let mut f = flasher(flash, FakeBus::new(), 256);
f.erase_range(100, 1).await.unwrap();
let mem = probe.mem();
assert!(mem[0..BLOCK_SIZE].iter().all(|&b| b == 0xFF)); assert!(mem[BLOCK_SIZE..].iter().all(|&b| b == 0x00)); }
#[tokio::test]
async fn chip_erase_clears_all() {
let flash = FakeFlash::new(BLOCK_SIZE, [0x20, 0x20, 0x15]);
for i in 0..BLOCK_SIZE {
flash.preset(i, &[0x00]);
}
let probe = flash.clone();
let mut f = flasher(flash, FakeBus::new(), 256);
f.chip_erase().await.unwrap();
assert!(probe.mem().iter().all(|&b| b == 0xFF));
}
#[tokio::test]
async fn program_crossing_page_and_small_chunks() {
let flash = FakeFlash::new(64 * 1024, [0x20, 0x20, 0x15]);
let probe = flash.clone();
let mut f = flasher(flash, FakeBus::new(), 8);
let data: Vec<u8> = (0..300).map(|i| (i % 251) as u8).collect();
f.erase_range(0, 300).await.unwrap();
f.program(250, &data, |_| {}).await.unwrap();
assert_eq!(&probe.mem()[250..250 + 300], &data[..]);
assert_eq!(probe.mem()[249], 0xFF);
}
#[tokio::test]
async fn read_back_and_verify() {
let flash = FakeFlash::new(64 * 1024, [0x20, 0x20, 0x15]);
let mut f = flasher(flash, FakeBus::new(), 8); let data: Vec<u8> = (0..500).map(|i| (i * 7 % 256) as u8).collect();
f.erase_range(0, 500).await.unwrap();
f.program(0, &data, |_| {}).await.unwrap();
let mut buf = vec![0u8; 500];
f.read(0, &mut buf).await.unwrap();
assert_eq!(buf, data);
f.verify(0, &data, |_| {}).await.unwrap();
let mut wrong = data.clone();
wrong[123] ^= 0xFF;
match f.verify(0, &wrong, |_| {}).await {
Err(FlashError::VerifyMismatch { addr, .. }) => assert_eq!(addr, 123),
other => panic!("expected mismatch, got {other:?}"),
}
}
#[tokio::test]
async fn erase_uses_profile_small_sector_at_tail() {
use crate::profile::{AddressWidth, EraseMenu, EraseType, FlashProfile, ProfileSource};
let size = 256 * 1024;
let flash = FakeFlash::new(size, [0xEF, 0x40, 0x15]);
for i in 0..size {
flash.preset(i, &[0x00]);
}
let probe = flash.clone();
let mut f = flasher(flash, FakeBus::new(), 256);
f.set_profile(FlashProfile {
page_size: 256,
address_width: AddressWidth::Three,
capacity: Some(size),
erase: EraseMenu::new(vec![
EraseType {
size: 64 * 1024,
opcode: 0xD8,
},
EraseType {
size: 4 * 1024,
opcode: 0x20,
},
])
.unwrap(),
source: ProfileSource::Sfdp,
sfdp_revision: None,
});
f.erase_range(0, 131_072 + 100).await.unwrap();
let mem = probe.mem();
assert!(mem[0..131_072 + 4096].iter().all(|&b| b == 0xFF)); assert!(mem[131_072 + 4096..].iter().all(|&b| b == 0x00)); }
#[tokio::test]
async fn erase_without_profile_is_not_detected() {
let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
let mut f = Flasher::with_config(
flash,
FakeBus::new(),
256,
Duration::ZERO,
Duration::from_secs(1),
);
assert!(matches!(
f.erase_range(0, 10).await,
Err(FlashError::NotDetected)
));
}
#[tokio::test]
async fn read_sfdp_returns_blob() {
let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
flash.set_sfdp(&[0x53, 0x46, 0x44, 0x50, 0x06, 0x01, 0x00, 0xFF]);
let mut f = flasher(flash, FakeBus::new(), 256);
let mut hdr = [0u8; 8];
f.read_sfdp(0, &mut hdr).await.unwrap();
assert_eq!(&hdr[0..4], b"SFDP");
}
fn sfdp_blob() -> Vec<u8> {
let mut v = vec![0xFFu8; 0x10];
v[0..8].copy_from_slice(&[0x53, 0x46, 0x44, 0x50, 0x06, 0x01, 0x00, 0xFF]); v[8..16].copy_from_slice(&[0x00, 0x01, 0x01, 0x0B, 0x10, 0x00, 0x00, 0xFF]); let mut b = vec![0u8; 11 * 4];
b[0..4].copy_from_slice(&[0xE5, 0x20, 0x00, 0x00]);
b[4..8].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0x00]);
b[28..32].copy_from_slice(&[0x0C, 0x20, 0x0F, 0x52]);
b[32..36].copy_from_slice(&[0x10, 0xD8, 0x00, 0x00]);
b[40..44].copy_from_slice(&[0x80, 0x00, 0x00, 0x00]);
v.extend_from_slice(&b);
v
}
#[tokio::test]
async fn detect_via_sfdp_builds_profile() {
use crate::profile::ProfileSource;
let flash = FakeFlash::new(2 * 1024 * 1024, [0xEF, 0x40, 0x15]);
flash.set_sfdp(&sfdp_blob());
let mut f = flasher(flash, FakeBus::new(), 256);
let p = f.detect_profile().await.unwrap();
assert_eq!(p.source, ProfileSource::Sfdp);
assert_eq!(p.page_size, 256);
assert_eq!(p.capacity, Some(2 * 1024 * 1024));
assert_eq!(p.erase.iter().count(), 3);
assert_eq!(p.erase.largest().size, 64 * 1024); assert_eq!(p.sfdp_revision, Some((1, 6))); }
#[tokio::test]
async fn detect_uses_fallback_table_for_m25p16() {
use crate::profile::{EraseType, ProfileSource};
let flash = FakeFlash::new(2 * 1024 * 1024, [0x20, 0x20, 0x15]); let mut f = flasher(flash, FakeBus::new(), 256);
let p = f.detect_profile().await.unwrap();
assert_eq!(p.source, ProfileSource::Table);
assert_eq!(p.capacity, Some(2 * 1024 * 1024));
assert_eq!(
p.erase.iter().collect::<Vec<_>>(),
vec![EraseType {
size: 64 * 1024,
opcode: 0xD8
}]
);
}
#[tokio::test]
async fn detect_unsupported_chip_errs() {
let flash = FakeFlash::new(1024, [0xAB, 0xCD, 0xEF]);
let mut f = flasher(flash, FakeBus::new(), 256);
assert!(matches!(
f.detect_profile().await,
Err(FlashError::UnsupportedChip { .. })
));
}
#[tokio::test]
async fn detect_no_flash_errs() {
let flash = FakeFlash::new(1024, [0xFF, 0xFF, 0xFF]);
let mut f = flasher(flash, FakeBus::new(), 256);
assert!(matches!(f.detect_profile().await, Err(FlashError::NoFlash)));
}
#[tokio::test]
async fn four_byte_addressing_roundtrips() {
use crate::profile::{AddressWidth, EraseMenu, EraseType, FlashProfile, ProfileSource};
let flash = FakeFlash::new(1024 * 1024, [0xEF, 0x40, 0x19]); let probe = flash.clone();
let mut f = flasher(flash, FakeBus::new(), 256);
f.set_profile(FlashProfile {
page_size: 256,
address_width: AddressWidth::Four,
capacity: Some(32 * 1024 * 1024),
erase: EraseMenu::new(vec![EraseType {
size: 64 * 1024,
opcode: 0xD8,
}])
.unwrap(),
source: ProfileSource::Sfdp,
sfdp_revision: None,
});
f.enter_4byte().await.unwrap(); let addr = 0x0002_0000; let data: Vec<u8> = (0..600).map(|i| (i % 256) as u8).collect();
f.erase_range(addr, data.len()).await.unwrap();
f.program(addr, &data, |_| {}).await.unwrap();
let mut buf = vec![0u8; data.len()];
f.read(addr, &mut buf).await.unwrap();
assert_eq!(buf, data);
assert_eq!(&probe.mem()[addr..addr + data.len()], &data[..]);
}
#[tokio::test]
async fn unprotect_enables_programming() {
let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
flash.set_protected(true);
let probe = flash.clone();
let mut f = flasher(flash, FakeBus::new(), 256);
f.program(0, &[1, 2, 3, 4], |_| {}).await.unwrap();
assert_eq!(&probe.mem()[0..4], &[0xFF, 0xFF, 0xFF, 0xFF]); f.unprotect().await.unwrap();
f.program(0, &[1, 2, 3, 4], |_| {}).await.unwrap();
assert_eq!(&probe.mem()[0..4], &[1, 2, 3, 4]); }
#[tokio::test]
async fn protect_then_unprotect_roundtrip() {
let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
let mut f = flasher(flash, FakeBus::new(), 256);
assert!(!f.is_protected().await.unwrap());
f.protect().await.unwrap();
assert!(f.is_protected().await.unwrap());
f.unprotect().await.unwrap();
assert!(!f.is_protected().await.unwrap());
}
#[tokio::test]
async fn soft_reset_runs() {
let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
let mut f = flasher(flash, FakeBus::new(), 256);
f.reset_flash().await.unwrap(); }
#[tokio::test]
async fn wake_releases_power_down() {
let flash = FakeFlash::new(2 * 1024 * 1024, [0xEF, 0x40, 0x18]);
flash.set_powered_down(true);
let mut f = flasher(flash, FakeBus::new(), 256);
assert!(!f.read_id().await.unwrap().is_present());
f.wake().await.unwrap();
assert_eq!(
f.read_id().await.unwrap(),
FlashId {
manufacturer: 0xEF,
mem_type: 0x40,
capacity_code: 0x18
}
);
}
#[tokio::test]
async fn acquire_bus_wakes_the_flash() {
let flash = FakeFlash::new(2 * 1024 * 1024, [0xEF, 0x40, 0x18]);
flash.set_powered_down(true);
let mut f = flasher(flash, FakeBus::new(), 256);
f.acquire_bus().await.unwrap(); assert!(f.read_id().await.unwrap().is_present());
}
}
#[cfg(test)]
pub(crate) mod testfakes {
use super::*;
use embedded_hal::spi::{Error as SpiErrorTrait, ErrorKind, ErrorType};
use std::cell::RefCell;
use std::convert::Infallible;
use std::rc::Rc;
#[derive(Debug)]
pub struct FakeErr;
impl SpiErrorTrait for FakeErr {
fn kind(&self) -> ErrorKind {
ErrorKind::Other
}
}
struct FakeState {
mem: Vec<u8>,
id: [u8; 3],
wel: bool,
busy_reads: u32, sfdp: Vec<u8>,
mode4b: bool, protected: bool, powered_down: bool, corrupt_next_program: bool, }
#[derive(Clone)]
pub(crate) struct FakeFlash(Rc<RefCell<FakeState>>);
impl FakeFlash {
pub(crate) fn new(size: usize, id: [u8; 3]) -> Self {
FakeFlash(Rc::new(RefCell::new(FakeState {
mem: vec![0xFF; size],
id,
wel: false,
busy_reads: 0,
sfdp: Vec::new(),
mode4b: false,
protected: false,
powered_down: false,
corrupt_next_program: false,
})))
}
pub(crate) fn set_busy_reads(&self, n: u32) {
self.0.borrow_mut().busy_reads = n;
}
pub(crate) fn set_sfdp(&self, blob: &[u8]) {
self.0.borrow_mut().sfdp = blob.to_vec();
}
pub(crate) fn set_protected(&self, p: bool) {
self.0.borrow_mut().protected = p;
}
pub(crate) fn set_powered_down(&self, p: bool) {
self.0.borrow_mut().powered_down = p;
}
pub(crate) fn set_corrupt_next_program(&self) {
self.0.borrow_mut().corrupt_next_program = true;
}
pub(crate) fn mem(&self) -> Vec<u8> {
self.0.borrow().mem.clone()
}
pub(crate) fn preset(&self, addr: usize, bytes: &[u8]) {
self.0.borrow_mut().mem[addr..addr + bytes.len()].copy_from_slice(bytes);
}
}
impl ErrorType for FakeFlash {
type Error = FakeErr;
}
impl embedded_hal_async::spi::SpiDevice for FakeFlash {
async fn transaction(&mut self, ops: &mut [Operation<'_, u8>]) -> Result<(), FakeErr> {
let mut mosi: Vec<u8> = Vec::new();
let mut reads: Vec<&mut [u8]> = Vec::new();
for op in ops.iter_mut() {
match op {
Operation::Write(w) => mosi.extend_from_slice(w),
Operation::Read(r) => reads.push(r),
Operation::Transfer(r, w) => {
mosi.extend_from_slice(w);
reads.push(r);
}
Operation::TransferInPlace(b) => {
let c = b.to_vec();
mosi.extend_from_slice(&c);
reads.push(b);
}
Operation::DelayNs(_) => {}
}
}
if mosi.is_empty() {
return Ok(());
}
let mut st = self.0.borrow_mut();
let mut resp: Vec<u8> = Vec::new();
let ab = if st.mode4b { 4 } else { 3 };
let addr_at = |m: &[u8]| -> usize {
let mut a = 0usize;
for i in 0..ab {
a = (a << 8) | m[1 + i] as usize;
}
a
};
match mosi[0] {
CMD_RELEASE_PD => st.powered_down = false, 0xB9 => st.powered_down = true, _ if st.powered_down => {} CMD_RDID => resp.extend_from_slice(&st.id),
CMD_WREN => st.wel = true,
CMD_EN4B => st.mode4b = true,
CMD_RDSR => {
let wip = if st.busy_reads > 0 {
st.busy_reads -= 1;
SR_WIP
} else {
0
};
let wel = if st.wel { 0x02 } else { 0 };
let bp = if st.protected { 0x1C } else { 0 };
resp.push(wip | wel | bp);
}
CMD_READ => {
let a = addr_at(&mosi);
let total: usize = reads.iter().map(|r| r.len()).sum();
for i in 0..total {
resp.push(*st.mem.get(a + i).unwrap_or(&0xFF));
}
}
CMD_SFDP => {
let a = u32::from_be_bytes([0, mosi[1], mosi[2], mosi[3]]) as usize;
let total: usize = reads.iter().map(|r| r.len()).sum();
for i in 0..total {
resp.push(*st.sfdp.get(a + i).unwrap_or(&0xFF));
}
}
CMD_WRSR => {
if st.wel {
let sr = mosi.get(1).copied().unwrap_or(0);
st.protected = sr & 0x1C != 0; }
st.wel = false;
}
CMD_PP => {
let a = addr_at(&mosi);
if st.wel && !st.protected {
if st.corrupt_next_program {
st.corrupt_next_program = false; } else {
for (i, b) in mosi[1 + ab..].iter().enumerate() {
let page = a & !(PAGE_SIZE - 1);
let off = (a + i - page) % PAGE_SIZE; st.mem[page + off] &= *b; }
}
}
st.wel = false;
}
CMD_CE => {
if st.wel {
st.mem.iter_mut().for_each(|b| *b = 0xFF);
}
st.wel = false;
}
op @ (0x20 | 0x52 | 0xD8) => {
let size = match op {
0x20 => 4 * 1024,
0x52 => 32 * 1024,
_ => 64 * 1024,
};
let a = addr_at(&mosi);
if st.wel {
let base = a & !(size - 1);
for b in &mut st.mem[base..base + size] {
*b = 0xFF;
}
}
st.wel = false;
}
_ => {}
}
let mut ri = 0;
for r in reads.iter_mut() {
for b in r.iter_mut() {
*b = *resp.get(ri).unwrap_or(&0xFF);
ri += 1;
}
}
Ok(())
}
}
#[derive(Clone)]
pub(crate) struct FakeBus(Rc<RefCell<bool>>);
impl FakeBus {
pub(crate) fn new() -> Self {
FakeBus(Rc::new(RefCell::new(false)))
}
}
impl BusAccess for FakeBus {
type Error = Infallible;
fn acquire(&mut self) -> Result<(), Infallible> {
*self.0.borrow_mut() = true;
Ok(())
}
fn release(&mut self) -> Result<(), Infallible> {
*self.0.borrow_mut() = false;
Ok(())
}
}
pub(crate) fn flasher(
flash: FakeFlash,
bus: FakeBus,
max_chunk: usize,
) -> Flasher<FakeFlash, FakeBus> {
let mut f = Flasher::with_config(
flash,
bus,
max_chunk,
Duration::ZERO,
Duration::from_secs(1),
);
f.set_profile(crate::profile::FlashProfile {
page_size: 256,
address_width: crate::profile::AddressWidth::Three,
capacity: Some(2 * 1024 * 1024),
erase: crate::profile::EraseMenu::new(vec![crate::profile::EraseType {
size: 64 * 1024,
opcode: 0xD8,
}])
.unwrap(),
source: crate::profile::ProfileSource::Table,
sfdp_revision: None,
});
f
}
}