#![feature(type_alias_impl_trait)]
#![no_std]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
mod fmt;
use embedded_storage::nor_flash::{ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash};
use embedded_storage_async::nor_flash::AsyncNorFlash;
const BOOT_MAGIC: u8 = 0xD0;
const SWAP_MAGIC: u8 = 0xF0;
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Partition {
pub from: usize,
pub to: usize,
}
impl Partition {
pub const fn new(from: usize, to: usize) -> Self {
Self { from, to }
}
#[allow(clippy::len_without_is_empty)]
pub const fn len(&self) -> usize {
self.to - self.from
}
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum State {
Boot,
Swap,
}
#[derive(PartialEq, Eq, Debug)]
pub enum BootError {
Flash(NorFlashErrorKind),
BadMagic,
}
impl<E> From<E> for BootError
where
E: NorFlashError,
{
fn from(error: E) -> Self {
BootError::Flash(error.kind())
}
}
#[repr(align(32))]
pub struct AlignedBuffer<const N: usize>(pub [u8; N]);
impl<const N: usize> AsRef<[u8]> for AlignedBuffer<N> {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl<const N: usize> AsMut<[u8]> for AlignedBuffer<N> {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
pub trait Flash: NorFlash + ReadNorFlash {
const BLOCK_SIZE: usize;
const ERASE_VALUE: u8 = 0xFF;
}
pub trait FlashConfig {
type STATE: Flash;
type ACTIVE: Flash;
type DFU: Flash;
fn active(&mut self) -> &mut Self::ACTIVE;
fn dfu(&mut self) -> &mut Self::DFU;
fn state(&mut self) -> &mut Self::STATE;
}
pub struct BootLoader {
state: Partition,
active: Partition,
dfu: Partition,
}
impl BootLoader {
pub fn new(active: Partition, dfu: Partition, state: Partition) -> Self {
Self { active, dfu, state }
}
pub fn boot_address(&self) -> usize {
self.active.from
}
pub fn prepare_boot<P: FlashConfig>(
&mut self,
p: &mut P,
magic: &mut [u8],
page: &mut [u8],
) -> Result<State, BootError> {
assert_partitions(self.active, self.dfu, self.state, page.len(), P::STATE::WRITE_SIZE);
assert_eq!(magic.len(), P::STATE::WRITE_SIZE);
let state = self.read_state(p, magic)?;
if state == State::Swap {
if !self.is_swapped(p, magic, page)? {
trace!("Swapping");
self.swap(p, magic, page)?;
trace!("Swapping done");
} else {
trace!("Reverting");
self.revert(p, magic, page)?;
let fstate = p.state();
magic.fill(!P::STATE::ERASE_VALUE);
fstate.write(self.state.from as u32, magic)?;
fstate.erase(self.state.from as u32, self.state.to as u32)?;
magic.fill(BOOT_MAGIC);
fstate.write(self.state.from as u32, magic)?;
}
}
Ok(state)
}
fn is_swapped<P: FlashConfig>(&mut self, p: &mut P, magic: &mut [u8], page: &mut [u8]) -> Result<bool, BootError> {
let page_size = page.len();
let page_count = self.active.len() / page_size;
let progress = self.current_progress(p, magic)?;
Ok(progress >= page_count * 2)
}
fn current_progress<P: FlashConfig>(&mut self, config: &mut P, aligned: &mut [u8]) -> Result<usize, BootError> {
let write_size = aligned.len();
let max_index = ((self.state.len() - write_size) / write_size) - 1;
aligned.fill(!P::STATE::ERASE_VALUE);
let flash = config.state();
for i in 0..max_index {
flash.read((self.state.from + write_size + i * write_size) as u32, aligned)?;
if aligned.iter().any(|&b| b == P::STATE::ERASE_VALUE) {
return Ok(i);
}
}
Ok(max_index)
}
fn update_progress<P: FlashConfig>(&mut self, idx: usize, p: &mut P, magic: &mut [u8]) -> Result<(), BootError> {
let flash = p.state();
let write_size = magic.len();
let w = self.state.from + write_size + idx * write_size;
let aligned = magic;
aligned.fill(!P::STATE::ERASE_VALUE);
flash.write(w as u32, aligned)?;
Ok(())
}
fn active_addr(&self, n: usize, page_size: usize) -> usize {
self.active.from + n * page_size
}
fn dfu_addr(&self, n: usize, page_size: usize) -> usize {
self.dfu.from + n * page_size
}
fn copy_page_once_to_active<P: FlashConfig>(
&mut self,
idx: usize,
from_page: usize,
to_page: usize,
p: &mut P,
magic: &mut [u8],
page: &mut [u8],
) -> Result<(), BootError> {
let buf = page;
if self.current_progress(p, magic)? <= idx {
let mut offset = from_page;
for chunk in buf.chunks_mut(P::DFU::BLOCK_SIZE) {
p.dfu().read(offset as u32, chunk)?;
offset += chunk.len();
}
p.active().erase(to_page as u32, (to_page + buf.len()) as u32)?;
let mut offset = to_page;
for chunk in buf.chunks(P::ACTIVE::BLOCK_SIZE) {
p.active().write(offset as u32, chunk)?;
offset += chunk.len();
}
self.update_progress(idx, p, magic)?;
}
Ok(())
}
fn copy_page_once_to_dfu<P: FlashConfig>(
&mut self,
idx: usize,
from_page: usize,
to_page: usize,
p: &mut P,
magic: &mut [u8],
page: &mut [u8],
) -> Result<(), BootError> {
let buf = page;
if self.current_progress(p, magic)? <= idx {
let mut offset = from_page;
for chunk in buf.chunks_mut(P::ACTIVE::BLOCK_SIZE) {
p.active().read(offset as u32, chunk)?;
offset += chunk.len();
}
p.dfu().erase(to_page as u32, (to_page + buf.len()) as u32)?;
let mut offset = to_page;
for chunk in buf.chunks(P::DFU::BLOCK_SIZE) {
p.dfu().write(offset as u32, chunk)?;
offset += chunk.len();
}
self.update_progress(idx, p, magic)?;
}
Ok(())
}
fn swap<P: FlashConfig>(&mut self, p: &mut P, magic: &mut [u8], page: &mut [u8]) -> Result<(), BootError> {
let page_size = page.len();
let page_count = self.active.len() / page_size;
trace!("Page count: {}", page_count);
for page_num in 0..page_count {
trace!("COPY PAGE {}", page_num);
let active_page = self.active_addr(page_count - 1 - page_num, page_size);
let dfu_page = self.dfu_addr(page_count - page_num, page_size);
self.copy_page_once_to_dfu(page_num * 2, active_page, dfu_page, p, magic, page)?;
let active_page = self.active_addr(page_count - 1 - page_num, page_size);
let dfu_page = self.dfu_addr(page_count - 1 - page_num, page_size);
self.copy_page_once_to_active(page_num * 2 + 1, dfu_page, active_page, p, magic, page)?;
}
Ok(())
}
fn revert<P: FlashConfig>(&mut self, p: &mut P, magic: &mut [u8], page: &mut [u8]) -> Result<(), BootError> {
let page_size = page.len();
let page_count = self.active.len() / page_size;
for page_num in 0..page_count {
let active_page = self.active_addr(page_num, page_size);
let dfu_page = self.dfu_addr(page_num, page_size);
self.copy_page_once_to_dfu(page_count * 2 + page_num * 2, active_page, dfu_page, p, magic, page)?;
let active_page = self.active_addr(page_num, page_size);
let dfu_page = self.dfu_addr(page_num + 1, page_size);
self.copy_page_once_to_active(page_count * 2 + page_num * 2 + 1, dfu_page, active_page, p, magic, page)?;
}
Ok(())
}
fn read_state<P: FlashConfig>(&mut self, config: &mut P, magic: &mut [u8]) -> Result<State, BootError> {
let flash = config.state();
flash.read(self.state.from as u32, magic)?;
if !magic.iter().any(|&b| b != SWAP_MAGIC) {
Ok(State::Swap)
} else {
Ok(State::Boot)
}
}
}
fn assert_partitions(active: Partition, dfu: Partition, state: Partition, page_size: usize, write_size: usize) {
assert_eq!(active.len() % page_size, 0);
assert_eq!(dfu.len() % page_size, 0);
assert!(dfu.len() - active.len() >= page_size);
assert!(2 * (active.len() / page_size) <= (state.len() - write_size) / write_size);
}
pub struct SingleFlashConfig<'a, F>
where
F: Flash,
{
flash: &'a mut F,
}
impl<'a, F> SingleFlashConfig<'a, F>
where
F: Flash,
{
pub fn new(flash: &'a mut F) -> Self {
Self { flash }
}
}
impl<'a, F> FlashConfig for SingleFlashConfig<'a, F>
where
F: Flash,
{
type STATE = F;
type ACTIVE = F;
type DFU = F;
fn active(&mut self) -> &mut Self::STATE {
self.flash
}
fn dfu(&mut self) -> &mut Self::ACTIVE {
self.flash
}
fn state(&mut self) -> &mut Self::DFU {
self.flash
}
}
pub struct BootFlash<F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8 = 0xFF>
where
F: NorFlash + ReadNorFlash,
{
flash: F,
}
impl<F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> BootFlash<F, BLOCK_SIZE, ERASE_VALUE>
where
F: NorFlash + ReadNorFlash,
{
pub fn new(flash: F) -> Self {
Self { flash }
}
}
impl<F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> Flash for BootFlash<F, BLOCK_SIZE, ERASE_VALUE>
where
F: NorFlash + ReadNorFlash,
{
const BLOCK_SIZE: usize = BLOCK_SIZE;
const ERASE_VALUE: u8 = ERASE_VALUE;
}
impl<F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> ErrorType for BootFlash<F, BLOCK_SIZE, ERASE_VALUE>
where
F: ReadNorFlash + NorFlash,
{
type Error = F::Error;
}
impl<F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> NorFlash for BootFlash<F, BLOCK_SIZE, ERASE_VALUE>
where
F: ReadNorFlash + NorFlash,
{
const WRITE_SIZE: usize = F::WRITE_SIZE;
const ERASE_SIZE: usize = F::ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
F::erase(&mut self.flash, from, to)
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
F::write(&mut self.flash, offset, bytes)
}
}
impl<F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> ReadNorFlash for BootFlash<F, BLOCK_SIZE, ERASE_VALUE>
where
F: ReadNorFlash + NorFlash,
{
const READ_SIZE: usize = F::READ_SIZE;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
F::read(&mut self.flash, offset, bytes)
}
fn capacity(&self) -> usize {
F::capacity(&self.flash)
}
}
pub struct MultiFlashConfig<'a, ACTIVE, STATE, DFU>
where
ACTIVE: Flash,
STATE: Flash,
DFU: Flash,
{
active: &'a mut ACTIVE,
state: &'a mut STATE,
dfu: &'a mut DFU,
}
impl<'a, ACTIVE, STATE, DFU> MultiFlashConfig<'a, ACTIVE, STATE, DFU>
where
ACTIVE: Flash,
STATE: Flash,
DFU: Flash,
{
pub fn new(active: &'a mut ACTIVE, state: &'a mut STATE, dfu: &'a mut DFU) -> Self {
Self { active, state, dfu }
}
}
impl<'a, ACTIVE, STATE, DFU> FlashConfig for MultiFlashConfig<'a, ACTIVE, STATE, DFU>
where
ACTIVE: Flash,
STATE: Flash,
DFU: Flash,
{
type STATE = STATE;
type ACTIVE = ACTIVE;
type DFU = DFU;
fn active(&mut self) -> &mut Self::ACTIVE {
self.active
}
fn dfu(&mut self) -> &mut Self::DFU {
self.dfu
}
fn state(&mut self) -> &mut Self::STATE {
self.state
}
}
pub struct FirmwareUpdater {
state: Partition,
dfu: Partition,
}
impl Default for FirmwareUpdater {
fn default() -> Self {
extern "C" {
static __bootloader_state_start: u32;
static __bootloader_state_end: u32;
static __bootloader_dfu_start: u32;
static __bootloader_dfu_end: u32;
}
let dfu = unsafe {
Partition::new(
&__bootloader_dfu_start as *const u32 as usize,
&__bootloader_dfu_end as *const u32 as usize,
)
};
let state = unsafe {
Partition::new(
&__bootloader_state_start as *const u32 as usize,
&__bootloader_state_end as *const u32 as usize,
)
};
trace!("DFU: 0x{:x} - 0x{:x}", dfu.from, dfu.to);
trace!("STATE: 0x{:x} - 0x{:x}", state.from, state.to);
FirmwareUpdater::new(dfu, state)
}
}
impl FirmwareUpdater {
pub const fn new(dfu: Partition, state: Partition) -> Self {
Self { dfu, state }
}
pub fn firmware_len(&self) -> usize {
self.dfu.len()
}
pub async fn get_state<F: AsyncNorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<State, F::Error> {
flash.read(self.state.from as u32, aligned).await?;
if !aligned.iter().any(|&b| b != SWAP_MAGIC) {
Ok(State::Swap)
} else {
Ok(State::Boot)
}
}
pub async fn mark_updated<F: AsyncNorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic(aligned, SWAP_MAGIC, flash).await
}
pub async fn mark_booted<F: AsyncNorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic(aligned, BOOT_MAGIC, flash).await
}
async fn set_magic<F: AsyncNorFlash>(
&mut self,
aligned: &mut [u8],
magic: u8,
flash: &mut F,
) -> Result<(), F::Error> {
flash.read(self.state.from as u32, aligned).await?;
if aligned.iter().any(|&b| b != magic) {
aligned.fill(0);
flash.write(self.state.from as u32, aligned).await?;
flash.erase(self.state.from as u32, self.state.to as u32).await?;
aligned.fill(magic);
flash.write(self.state.from as u32, aligned).await?;
}
Ok(())
}
pub async fn write_firmware<F: AsyncNorFlash>(
&mut self,
offset: usize,
data: &[u8],
flash: &mut F,
block_size: usize,
) -> Result<(), F::Error> {
assert!(data.len() >= F::ERASE_SIZE);
flash
.erase(
(self.dfu.from + offset) as u32,
(self.dfu.from + offset + data.len()) as u32,
)
.await?;
trace!(
"Erased from {} to {}",
self.dfu.from + offset,
self.dfu.from + offset + data.len()
);
FirmwareWriter(self.dfu)
.write_block(offset, data, flash, block_size)
.await?;
Ok(())
}
pub async fn prepare_update<F: AsyncNorFlash>(&mut self, flash: &mut F) -> Result<FirmwareWriter, F::Error> {
flash.erase((self.dfu.from) as u32, (self.dfu.to) as u32).await?;
trace!("Erased from {} to {}", self.dfu.from, self.dfu.to);
Ok(FirmwareWriter(self.dfu))
}
pub fn get_state_blocking<F: NorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<State, F::Error> {
flash.read(self.state.from as u32, aligned)?;
if !aligned.iter().any(|&b| b != SWAP_MAGIC) {
Ok(State::Swap)
} else {
Ok(State::Boot)
}
}
pub fn mark_updated_blocking<F: NorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic_blocking(aligned, SWAP_MAGIC, flash)
}
pub fn mark_booted_blocking<F: NorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic_blocking(aligned, BOOT_MAGIC, flash)
}
fn set_magic_blocking<F: NorFlash>(
&mut self,
aligned: &mut [u8],
magic: u8,
flash: &mut F,
) -> Result<(), F::Error> {
flash.read(self.state.from as u32, aligned)?;
if aligned.iter().any(|&b| b != magic) {
aligned.fill(0);
flash.write(self.state.from as u32, aligned)?;
flash.erase(self.state.from as u32, self.state.to as u32)?;
aligned.fill(magic);
flash.write(self.state.from as u32, aligned)?;
}
Ok(())
}
pub fn write_firmware_blocking<F: NorFlash>(
&mut self,
offset: usize,
data: &[u8],
flash: &mut F,
block_size: usize,
) -> Result<(), F::Error> {
assert!(data.len() >= F::ERASE_SIZE);
flash.erase(
(self.dfu.from + offset) as u32,
(self.dfu.from + offset + data.len()) as u32,
)?;
trace!(
"Erased from {} to {}",
self.dfu.from + offset,
self.dfu.from + offset + data.len()
);
FirmwareWriter(self.dfu).write_block_blocking(offset, data, flash, block_size)?;
Ok(())
}
pub fn prepare_update_blocking<F: NorFlash>(&mut self, flash: &mut F) -> Result<FirmwareWriter, F::Error> {
flash.erase((self.dfu.from) as u32, (self.dfu.to) as u32)?;
trace!("Erased from {} to {}", self.dfu.from, self.dfu.to);
Ok(FirmwareWriter(self.dfu))
}
}
pub struct FirmwareWriter(Partition);
impl FirmwareWriter {
pub async fn write_block<F: AsyncNorFlash>(
&mut self,
offset: usize,
data: &[u8],
flash: &mut F,
block_size: usize,
) -> Result<(), F::Error> {
trace!(
"Writing firmware at offset 0x{:x} len {}",
self.0.from + offset,
data.len()
);
let mut write_offset = self.0.from + offset;
for chunk in data.chunks(block_size) {
trace!("Wrote chunk at {}: {:?}", write_offset, chunk);
flash.write(write_offset as u32, chunk).await?;
write_offset += chunk.len();
}
Ok(())
}
pub fn write_block_blocking<F: NorFlash>(
&mut self,
offset: usize,
data: &[u8],
flash: &mut F,
block_size: usize,
) -> Result<(), F::Error> {
trace!(
"Writing firmware at offset 0x{:x} len {}",
self.0.from + offset,
data.len()
);
let mut write_offset = self.0.from + offset;
for chunk in data.chunks(block_size) {
trace!("Wrote chunk at {}: {:?}", write_offset, chunk);
flash.write(write_offset as u32, chunk)?;
write_offset += chunk.len();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use core::convert::Infallible;
use core::future::Future;
use embedded_storage::nor_flash::ErrorType;
use embedded_storage_async::nor_flash::AsyncReadNorFlash;
use futures::executor::block_on;
use super::*;
#[test]
fn test_boot_state() {
const STATE: Partition = Partition::new(0, 4096);
const ACTIVE: Partition = Partition::new(4096, 61440);
const DFU: Partition = Partition::new(61440, 122880);
let mut flash = MemFlash::<131072, 4096, 4>([0xff; 131072]);
flash.0[0..4].copy_from_slice(&[BOOT_MAGIC; 4]);
let mut flash = SingleFlashConfig::new(&mut flash);
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Boot,
bootloader.prepare_boot(&mut flash, &mut magic, &mut page).unwrap()
);
}
#[test]
fn test_swap_state() {
const STATE: Partition = Partition::new(0, 4096);
const ACTIVE: Partition = Partition::new(4096, 61440);
const DFU: Partition = Partition::new(61440, 122880);
let mut flash = MemFlash::<131072, 4096, 4>([0xff; 131072]);
let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
let mut aligned = [0; 4];
for i in ACTIVE.from..ACTIVE.to {
flash.0[i] = original[i - ACTIVE.from];
}
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut updater = FirmwareUpdater::new(DFU, STATE);
let mut offset = 0;
for chunk in update.chunks(4096) {
block_on(updater.write_firmware(offset, chunk, &mut flash, 4096)).unwrap();
offset += chunk.len();
}
block_on(updater.mark_updated(&mut flash, &mut aligned)).unwrap();
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Swap,
bootloader
.prepare_boot(&mut SingleFlashConfig::new(&mut flash), &mut magic, &mut page)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(flash.0[i], update[i - ACTIVE.from], "Index {}", i);
}
for i in DFU.from + 4096..DFU.to {
assert_eq!(flash.0[i], original[i - DFU.from - 4096], "Index {}", i);
}
assert_eq!(
State::Swap,
bootloader
.prepare_boot(&mut SingleFlashConfig::new(&mut flash), &mut magic, &mut page)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(flash.0[i], original[i - ACTIVE.from], "Index {}", i);
}
for i in DFU.from..DFU.to - 4096 {
assert_eq!(flash.0[i], update[i - DFU.from], "Index {}", i);
}
block_on(updater.mark_booted(&mut flash, &mut aligned)).unwrap();
assert_eq!(
State::Boot,
bootloader
.prepare_boot(&mut SingleFlashConfig::new(&mut flash), &mut magic, &mut page)
.unwrap()
);
}
#[test]
fn test_separate_flash_active_page_biggest() {
const STATE: Partition = Partition::new(2048, 4096);
const ACTIVE: Partition = Partition::new(4096, 16384);
const DFU: Partition = Partition::new(0, 16384);
let mut active = MemFlash::<16384, 4096, 8>([0xff; 16384]);
let mut dfu = MemFlash::<16384, 2048, 8>([0xff; 16384]);
let mut state = MemFlash::<4096, 128, 4>([0xff; 4096]);
let mut aligned = [0; 4];
let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
for i in ACTIVE.from..ACTIVE.to {
active.0[i] = original[i - ACTIVE.from];
}
let mut updater = FirmwareUpdater::new(DFU, STATE);
let mut offset = 0;
for chunk in update.chunks(2048) {
block_on(updater.write_firmware(offset, chunk, &mut dfu, chunk.len())).unwrap();
offset += chunk.len();
}
block_on(updater.mark_updated(&mut state, &mut aligned)).unwrap();
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Swap,
bootloader
.prepare_boot(
&mut MultiFlashConfig::new(&mut active, &mut state, &mut dfu),
&mut magic,
&mut page
)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(active.0[i], update[i - ACTIVE.from], "Index {}", i);
}
for i in DFU.from + 4096..DFU.to {
assert_eq!(dfu.0[i], original[i - DFU.from - 4096], "Index {}", i);
}
}
#[test]
fn test_separate_flash_dfu_page_biggest() {
const STATE: Partition = Partition::new(2048, 4096);
const ACTIVE: Partition = Partition::new(4096, 16384);
const DFU: Partition = Partition::new(0, 16384);
let mut aligned = [0; 4];
let mut active = MemFlash::<16384, 2048, 4>([0xff; 16384]);
let mut dfu = MemFlash::<16384, 4096, 8>([0xff; 16384]);
let mut state = MemFlash::<4096, 128, 4>([0xff; 4096]);
let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
for i in ACTIVE.from..ACTIVE.to {
active.0[i] = original[i - ACTIVE.from];
}
let mut updater = FirmwareUpdater::new(DFU, STATE);
let mut offset = 0;
for chunk in update.chunks(4096) {
block_on(updater.write_firmware(offset, chunk, &mut dfu, chunk.len())).unwrap();
offset += chunk.len();
}
block_on(updater.mark_updated(&mut state, &mut aligned)).unwrap();
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Swap,
bootloader
.prepare_boot(
&mut MultiFlashConfig::new(&mut active, &mut state, &mut dfu,),
&mut magic,
&mut page
)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(active.0[i], update[i - ACTIVE.from], "Index {}", i);
}
for i in DFU.from + 4096..DFU.to {
assert_eq!(dfu.0[i], original[i - DFU.from - 4096], "Index {}", i);
}
}
#[test]
#[should_panic]
fn test_range_asserts() {
const ACTIVE: Partition = Partition::new(4096, 4194304);
const DFU: Partition = Partition::new(4194304, 2 * 4194304);
const STATE: Partition = Partition::new(0, 4096);
assert_partitions(ACTIVE, DFU, STATE, 4096, 4);
}
struct MemFlash<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize>([u8; SIZE]);
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> NorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const WRITE_SIZE: usize = WRITE_SIZE;
const ERASE_SIZE: usize = ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
let from = from as usize;
let to = to as usize;
assert!(from % ERASE_SIZE == 0);
assert!(to % ERASE_SIZE == 0, "To: {}, erase size: {}", to, ERASE_SIZE);
for i in from..to {
self.0[i] = 0xFF;
}
Ok(())
}
fn write(&mut self, offset: u32, data: &[u8]) -> Result<(), Self::Error> {
assert!(data.len() % WRITE_SIZE == 0);
assert!(offset as usize % WRITE_SIZE == 0);
assert!(offset as usize + data.len() <= SIZE);
self.0[offset as usize..offset as usize + data.len()].copy_from_slice(data);
Ok(())
}
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ErrorType
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
type Error = Infallible;
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ReadNorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const READ_SIZE: usize = 4;
fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
let len = buf.len();
buf[..].copy_from_slice(&self.0[offset as usize..offset as usize + len]);
Ok(())
}
fn capacity(&self) -> usize {
SIZE
}
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> super::Flash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const BLOCK_SIZE: usize = ERASE_SIZE;
const ERASE_VALUE: u8 = 0xFF;
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncReadNorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const READ_SIZE: usize = 4;
type ReadFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn read<'a>(&'a mut self, offset: u32, buf: &'a mut [u8]) -> Self::ReadFuture<'a> {
async move {
let len = buf.len();
buf[..].copy_from_slice(&self.0[offset as usize..offset as usize + len]);
Ok(())
}
}
fn capacity(&self) -> usize {
SIZE
}
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncNorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const WRITE_SIZE: usize = WRITE_SIZE;
const ERASE_SIZE: usize = ERASE_SIZE;
type EraseFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn erase(&mut self, from: u32, to: u32) -> Self::EraseFuture<'_> {
async move {
let from = from as usize;
let to = to as usize;
assert!(from % ERASE_SIZE == 0);
assert!(to % ERASE_SIZE == 0);
for i in from..to {
self.0[i] = 0xFF;
}
Ok(())
}
}
type WriteFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn write<'a>(&'a mut self, offset: u32, data: &'a [u8]) -> Self::WriteFuture<'a> {
info!("Writing {} bytes to 0x{:x}", data.len(), offset);
async move {
assert!(data.len() % WRITE_SIZE == 0);
assert!(offset as usize % WRITE_SIZE == 0);
assert!(
offset as usize + data.len() <= SIZE,
"OFFSET: {}, LEN: {}, FLASH SIZE: {}",
offset,
data.len(),
SIZE
);
self.0[offset as usize..offset as usize + data.len()].copy_from_slice(data);
Ok(())
}
}
}
}