aboutsummaryrefslogtreecommitdiff
path: root/embassy-boot/boot/src
diff options
context:
space:
mode:
authorUlf Lilleengen <[email protected]>2022-01-24 12:54:09 +0100
committerUlf Lilleengen <[email protected]>2022-02-09 10:50:29 +0100
commited2a87a262e0e8c091627c96ced981dd3a97a6a1 (patch)
treee4202eb8044b534215aa9aa68b79ab83b9e9afc4 /embassy-boot/boot/src
parentd91bd0b9a69b8411f2a1d58bfad5d4dce51e7110 (diff)
Add embassy-boot
Embassy-boot is a simple bootloader that works together with an application to provide firmware update capabilities with a minimal risk. The bootloader consists of a platform-independent part, which implements the swap algorithm, and a platform-dependent part (currently only for nRF) that provides addition functionality such as watchdog timers softdevice support.
Diffstat (limited to 'embassy-boot/boot/src')
-rw-r--r--embassy-boot/boot/src/fmt.rs225
-rw-r--r--embassy-boot/boot/src/lib.rs550
2 files changed, 775 insertions, 0 deletions
diff --git a/embassy-boot/boot/src/fmt.rs b/embassy-boot/boot/src/fmt.rs
new file mode 100644
index 000000000..066970813
--- /dev/null
+++ b/embassy-boot/boot/src/fmt.rs
@@ -0,0 +1,225 @@
1#![macro_use]
2#![allow(unused_macros)]
3
4#[cfg(all(feature = "defmt", feature = "log"))]
5compile_error!("You may not enable both `defmt` and `log` features.");
6
7macro_rules! assert {
8 ($($x:tt)*) => {
9 {
10 #[cfg(not(feature = "defmt"))]
11 ::core::assert!($($x)*);
12 #[cfg(feature = "defmt")]
13 ::defmt::assert!($($x)*);
14 }
15 };
16}
17
18macro_rules! assert_eq {
19 ($($x:tt)*) => {
20 {
21 #[cfg(not(feature = "defmt"))]
22 ::core::assert_eq!($($x)*);
23 #[cfg(feature = "defmt")]
24 ::defmt::assert_eq!($($x)*);
25 }
26 };
27}
28
29macro_rules! assert_ne {
30 ($($x:tt)*) => {
31 {
32 #[cfg(not(feature = "defmt"))]
33 ::core::assert_ne!($($x)*);
34 #[cfg(feature = "defmt")]
35 ::defmt::assert_ne!($($x)*);
36 }
37 };
38}
39
40macro_rules! debug_assert {
41 ($($x:tt)*) => {
42 {
43 #[cfg(not(feature = "defmt"))]
44 ::core::debug_assert!($($x)*);
45 #[cfg(feature = "defmt")]
46 ::defmt::debug_assert!($($x)*);
47 }
48 };
49}
50
51macro_rules! debug_assert_eq {
52 ($($x:tt)*) => {
53 {
54 #[cfg(not(feature = "defmt"))]
55 ::core::debug_assert_eq!($($x)*);
56 #[cfg(feature = "defmt")]
57 ::defmt::debug_assert_eq!($($x)*);
58 }
59 };
60}
61
62macro_rules! debug_assert_ne {
63 ($($x:tt)*) => {
64 {
65 #[cfg(not(feature = "defmt"))]
66 ::core::debug_assert_ne!($($x)*);
67 #[cfg(feature = "defmt")]
68 ::defmt::debug_assert_ne!($($x)*);
69 }
70 };
71}
72
73macro_rules! todo {
74 ($($x:tt)*) => {
75 {
76 #[cfg(not(feature = "defmt"))]
77 ::core::todo!($($x)*);
78 #[cfg(feature = "defmt")]
79 ::defmt::todo!($($x)*);
80 }
81 };
82}
83
84macro_rules! unreachable {
85 ($($x:tt)*) => {
86 {
87 #[cfg(not(feature = "defmt"))]
88 ::core::unreachable!($($x)*);
89 #[cfg(feature = "defmt")]
90 ::defmt::unreachable!($($x)*);
91 }
92 };
93}
94
95macro_rules! panic {
96 ($($x:tt)*) => {
97 {
98 #[cfg(not(feature = "defmt"))]
99 ::core::panic!($($x)*);
100 #[cfg(feature = "defmt")]
101 ::defmt::panic!($($x)*);
102 }
103 };
104}
105
106macro_rules! trace {
107 ($s:literal $(, $x:expr)* $(,)?) => {
108 {
109 #[cfg(feature = "log")]
110 ::log::trace!($s $(, $x)*);
111 #[cfg(feature = "defmt")]
112 ::defmt::trace!($s $(, $x)*);
113 #[cfg(not(any(feature = "log", feature="defmt")))]
114 let _ = ($( & $x ),*);
115 }
116 };
117}
118
119macro_rules! debug {
120 ($s:literal $(, $x:expr)* $(,)?) => {
121 {
122 #[cfg(feature = "log")]
123 ::log::debug!($s $(, $x)*);
124 #[cfg(feature = "defmt")]
125 ::defmt::debug!($s $(, $x)*);
126 #[cfg(not(any(feature = "log", feature="defmt")))]
127 let _ = ($( & $x ),*);
128 }
129 };
130}
131
132macro_rules! info {
133 ($s:literal $(, $x:expr)* $(,)?) => {
134 {
135 #[cfg(feature = "log")]
136 ::log::info!($s $(, $x)*);
137 #[cfg(feature = "defmt")]
138 ::defmt::info!($s $(, $x)*);
139 #[cfg(not(any(feature = "log", feature="defmt")))]
140 let _ = ($( & $x ),*);
141 }
142 };
143}
144
145macro_rules! warn {
146 ($s:literal $(, $x:expr)* $(,)?) => {
147 {
148 #[cfg(feature = "log")]
149 ::log::warn!($s $(, $x)*);
150 #[cfg(feature = "defmt")]
151 ::defmt::warn!($s $(, $x)*);
152 #[cfg(not(any(feature = "log", feature="defmt")))]
153 let _ = ($( & $x ),*);
154 }
155 };
156}
157
158macro_rules! error {
159 ($s:literal $(, $x:expr)* $(,)?) => {
160 {
161 #[cfg(feature = "log")]
162 ::log::error!($s $(, $x)*);
163 #[cfg(feature = "defmt")]
164 ::defmt::error!($s $(, $x)*);
165 #[cfg(not(any(feature = "log", feature="defmt")))]
166 let _ = ($( & $x ),*);
167 }
168 };
169}
170
171#[cfg(feature = "defmt")]
172macro_rules! unwrap {
173 ($($x:tt)*) => {
174 ::defmt::unwrap!($($x)*)
175 };
176}
177
178#[cfg(not(feature = "defmt"))]
179macro_rules! unwrap {
180 ($arg:expr) => {
181 match $crate::fmt::Try::into_result($arg) {
182 ::core::result::Result::Ok(t) => t,
183 ::core::result::Result::Err(e) => {
184 ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
185 }
186 }
187 };
188 ($arg:expr, $($msg:expr),+ $(,)? ) => {
189 match $crate::fmt::Try::into_result($arg) {
190 ::core::result::Result::Ok(t) => t,
191 ::core::result::Result::Err(e) => {
192 ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
193 }
194 }
195 }
196}
197
198#[derive(Debug, Copy, Clone, Eq, PartialEq)]
199pub struct NoneError;
200
201pub trait Try {
202 type Ok;
203 type Error;
204 fn into_result(self) -> Result<Self::Ok, Self::Error>;
205}
206
207impl<T> Try for Option<T> {
208 type Ok = T;
209 type Error = NoneError;
210
211 #[inline]
212 fn into_result(self) -> Result<T, NoneError> {
213 self.ok_or(NoneError)
214 }
215}
216
217impl<T, E> Try for Result<T, E> {
218 type Ok = T;
219 type Error = E;
220
221 #[inline]
222 fn into_result(self) -> Self {
223 self
224 }
225}
diff --git a/embassy-boot/boot/src/lib.rs b/embassy-boot/boot/src/lib.rs
new file mode 100644
index 000000000..909397b7b
--- /dev/null
+++ b/embassy-boot/boot/src/lib.rs
@@ -0,0 +1,550 @@
1#![feature(type_alias_impl_trait)]
2#![feature(generic_associated_types)]
3#![no_std]
4///! embassy-boot is a bootloader and firmware updater for embedded devices with flash
5///! storage implemented using embedded-storage
6///!
7///! The bootloader works in conjunction with the firmware application, and only has the
8///! ability to manage two flash banks with an active and a updatable part. It implements
9///! a swap algorithm that is power-failure safe, and allows reverting to the previous
10///! version of the firmware, should the application crash and fail to mark itself as booted.
11///!
12///! This library is intended to be used by platform-specific bootloaders, such as embassy-boot-nrf,
13///! which defines the limits and flash type for that particular platform.
14///!
15mod fmt;
16
17use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
18use embedded_storage_async::nor_flash::AsyncNorFlash;
19
20pub const BOOT_MAGIC: u32 = 0xD00DF00D;
21pub const SWAP_MAGIC: u32 = 0xF00FDAAD;
22
23#[derive(Copy, Clone, Debug)]
24#[cfg_attr(feature = "defmt", derive(defmt::Format))]
25pub struct Partition {
26 pub from: usize,
27 pub to: usize,
28}
29
30impl Partition {
31 pub const fn new(from: usize, to: usize) -> Self {
32 Self { from, to }
33 }
34 pub const fn len(&self) -> usize {
35 self.to - self.from
36 }
37}
38
39#[derive(PartialEq, Debug)]
40#[cfg_attr(feature = "defmt", derive(defmt::Format))]
41pub enum State {
42 Boot,
43 Swap,
44}
45
46#[derive(PartialEq, Debug)]
47#[cfg_attr(feature = "defmt", derive(defmt::Format))]
48pub enum BootError<E> {
49 Flash(E),
50 BadMagic,
51}
52
53impl<E> From<E> for BootError<E> {
54 fn from(error: E) -> Self {
55 BootError::Flash(error)
56 }
57}
58
59/// BootLoader works with any flash implementing embedded_storage and can also work with
60/// different page sizes.
61pub struct BootLoader<const PAGE_SIZE: usize> {
62 // Page with current state of bootloader. The state partition has the following format:
63 // | Range | Description |
64 // | 0 - 4 | Magic indicating bootloader state. BOOT_MAGIC means boot, SWAP_MAGIC means swap. |
65 // | 4 - N | Progress index used while swapping or reverting |
66 state: Partition,
67 // Location of the partition which will be booted from
68 active: Partition,
69 // Location of the partition which will be swapped in when requested
70 dfu: Partition,
71}
72
73impl<const PAGE_SIZE: usize> BootLoader<PAGE_SIZE> {
74 pub fn new(active: Partition, dfu: Partition, state: Partition) -> Self {
75 assert_eq!(active.len() % PAGE_SIZE, 0);
76 assert_eq!(dfu.len() % PAGE_SIZE, 0);
77 // DFU partition must have an extra page
78 assert!(dfu.len() - active.len() >= PAGE_SIZE);
79 // Ensure we have enough progress pages to store copy progress
80 assert!(active.len() / PAGE_SIZE >= (state.len() - 4) / PAGE_SIZE);
81 Self { active, dfu, state }
82 }
83
84 pub fn boot_address(&self) -> usize {
85 self.active.from
86 }
87
88 /// Perform necessary boot preparations like swapping images.
89 ///
90 /// The DFU partition is assumed to be 1 page bigger than the active partition for the swap
91 /// algorithm to work correctly.
92 ///
93 /// SWAPPING
94 ///
95 /// Assume a flash size of 3 pages for the active partition, and 4 pages for the DFU partition.
96 /// The swap index contains the copy progress, as to allow continuation of the copy process on
97 /// power failure. The index counter is represented within 1 or more pages (depending on total
98 /// flash size), where a page X is considered swapped if index at location (X + WRITE_SIZE)
99 /// contains a zero value. This ensures that index updates can be performed atomically and
100 /// avoid a situation where the wrong index value is set (page write size is "atomic").
101 ///
102 /// +-----------+------------+--------+--------+--------+--------+
103 /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
104 /// +-----------+------------+--------+--------+--------+--------+
105 /// | Active | 0 | 1 | 2 | 3 | - |
106 /// | DFU | 0 | 3 | 2 | 1 | X |
107 /// +-----------+-------+--------+--------+--------+--------+
108 ///
109 /// The algorithm starts by copying 'backwards', and after the first step, the layout is
110 /// as follows:
111 ///
112 /// +-----------+------------+--------+--------+--------+--------+
113 /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
114 /// +-----------+------------+--------+--------+--------+--------+
115 /// | Active | 1 | 1 | 2 | 1 | - |
116 /// | DFU | 1 | 3 | 2 | 1 | 3 |
117 /// +-----------+------------+--------+--------+--------+--------+
118 ///
119 /// The next iteration performs the same steps
120 ///
121 /// +-----------+------------+--------+--------+--------+--------+
122 /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
123 /// +-----------+------------+--------+--------+--------+--------+
124 /// | Active | 2 | 1 | 2 | 1 | - |
125 /// | DFU | 2 | 3 | 2 | 2 | 3 |
126 /// +-----------+------------+--------+--------+--------+--------+
127 ///
128 /// And again until we're done
129 ///
130 /// +-----------+------------+--------+--------+--------+--------+
131 /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
132 /// +-----------+------------+--------+--------+--------+--------+
133 /// | Active | 3 | 3 | 2 | 1 | - |
134 /// | DFU | 3 | 3 | 1 | 2 | 3 |
135 /// +-----------+------------+--------+--------+--------+--------+
136 ///
137 /// REVERTING
138 ///
139 /// The reverting algorithm uses the swap index to discover that images were swapped, but that
140 /// the application failed to mark the boot successful. In this case, the revert algorithm will
141 /// run.
142 ///
143 /// The revert index is located separately from the swap index, to ensure that revert can continue
144 /// on power failure.
145 ///
146 /// The revert algorithm works forwards, by starting copying into the 'unused' DFU page at the start.
147 ///
148 /// +-----------+--------------+--------+--------+--------+--------+
149 /// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
150 //*/
151 /// +-----------+--------------+--------+--------+--------+--------+
152 /// | Active | 3 | 1 | 2 | 1 | - |
153 /// | DFU | 3 | 3 | 1 | 2 | 3 |
154 /// +-----------+--------------+--------+--------+--------+--------+
155 ///
156 ///
157 /// +-----------+--------------+--------+--------+--------+--------+
158 /// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
159 /// +-----------+--------------+--------+--------+--------+--------+
160 /// | Active | 3 | 1 | 2 | 1 | - |
161 /// | DFU | 3 | 3 | 2 | 2 | 3 |
162 /// +-----------+--------------+--------+--------+--------+--------+
163 ///
164 /// +-----------+--------------+--------+--------+--------+--------+
165 /// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
166 /// +-----------+--------------+--------+--------+--------+--------+
167 /// | Active | 3 | 1 | 2 | 3 | - |
168 /// | DFU | 3 | 3 | 2 | 1 | 3 |
169 /// +-----------+--------------+--------+--------+--------+--------+
170 ///
171 pub fn prepare_boot<F: NorFlash + ReadNorFlash>(
172 &mut self,
173 flash: &mut F,
174 ) -> Result<State, BootError<F::Error>> {
175 // Copy contents from partition N to active
176 let state = self.read_state(flash)?;
177 match state {
178 State::Swap => {
179 //
180 // Check if we already swapped. If we're in the swap state, this means we should revert
181 // since the app has failed to mark boot as successful
182 //
183 if !self.is_swapped(flash)? {
184 trace!("Swapping");
185 self.swap(flash)?;
186 } else {
187 trace!("Reverting");
188 self.revert(flash)?;
189
190 // Overwrite magic and reset progress
191 flash.write(self.state.from as u32, &[0, 0, 0, 0])?;
192 flash.erase(self.state.from as u32, self.state.to as u32)?;
193 flash.write(self.state.from as u32, &BOOT_MAGIC.to_le_bytes())?;
194 }
195 }
196 _ => {}
197 }
198 Ok(state)
199 }
200
201 fn is_swapped<F: ReadNorFlash>(&mut self, flash: &mut F) -> Result<bool, F::Error> {
202 let page_count = self.active.len() / PAGE_SIZE;
203 let progress = self.current_progress(flash)?;
204
205 Ok(progress >= page_count * 2)
206 }
207
208 fn current_progress<F: ReadNorFlash>(&mut self, flash: &mut F) -> Result<usize, F::Error> {
209 let max_index = ((self.state.len() - 4) / 4) - 1;
210 for i in 0..max_index {
211 let mut buf: [u8; 4] = [0; 4];
212 flash.read((self.state.from + 4 + i * 4) as u32, &mut buf)?;
213 if buf == [0xFF, 0xFF, 0xFF, 0xFF] {
214 return Ok(i);
215 }
216 }
217 Ok(max_index)
218 }
219
220 fn update_progress<F: NorFlash>(&mut self, idx: usize, flash: &mut F) -> Result<(), F::Error> {
221 let w = self.state.from + 4 + idx * 4;
222 flash.write(w as u32, &[0, 0, 0, 0])?;
223 Ok(())
224 }
225
226 fn active_addr(&self, n: usize) -> usize {
227 self.active.from + n * PAGE_SIZE
228 }
229
230 fn dfu_addr(&self, n: usize) -> usize {
231 self.dfu.from + n * PAGE_SIZE
232 }
233
234 fn copy_page_once<F: NorFlash + ReadNorFlash>(
235 &mut self,
236 idx: usize,
237 from: usize,
238 to: usize,
239 flash: &mut F,
240 ) -> Result<(), F::Error> {
241 let mut buf: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
242 if self.current_progress(flash)? <= idx {
243 flash.read(from as u32, &mut buf)?;
244 flash.erase(to as u32, (to + PAGE_SIZE) as u32)?;
245 flash.write(to as u32, &buf)?;
246 self.update_progress(idx, flash)?;
247 }
248 Ok(())
249 }
250
251 fn swap<F: NorFlash + ReadNorFlash>(&mut self, flash: &mut F) -> Result<(), F::Error> {
252 let page_count = self.active.len() / PAGE_SIZE;
253 // trace!("Page count: {}", page_count);
254 for page in 0..page_count {
255 // Copy active page to the 'next' DFU page.
256 let active_page = self.active_addr(page_count - 1 - page);
257 let dfu_page = self.dfu_addr(page_count - page);
258 // info!("Copy active {} to dfu {}", active_page, dfu_page);
259 self.copy_page_once(page * 2, active_page, dfu_page, flash)?;
260
261 // Copy DFU page to the active page
262 let active_page = self.active_addr(page_count - 1 - page);
263 let dfu_page = self.dfu_addr(page_count - 1 - page);
264 //info!("Copy dfy {} to active {}", dfu_page, active_page);
265 self.copy_page_once(page * 2 + 1, dfu_page, active_page, flash)?;
266 }
267
268 Ok(())
269 }
270
271 fn revert<F: NorFlash + ReadNorFlash>(&mut self, flash: &mut F) -> Result<(), F::Error> {
272 let page_count = self.active.len() / PAGE_SIZE;
273 for page in 0..page_count {
274 // Copy the bad active page to the DFU page
275 let active_page = self.active_addr(page);
276 let dfu_page = self.dfu_addr(page);
277 self.copy_page_once(page_count * 2 + page * 2, active_page, dfu_page, flash)?;
278
279 // Copy the DFU page back to the active page
280 let active_page = self.active_addr(page);
281 let dfu_page = self.dfu_addr(page + 1);
282 self.copy_page_once(page_count * 2 + page * 2 + 1, dfu_page, active_page, flash)?;
283 }
284
285 Ok(())
286 }
287
288 fn read_state<F: ReadNorFlash>(&mut self, flash: &mut F) -> Result<State, BootError<F::Error>> {
289 let mut magic: [u8; 4] = [0; 4];
290 flash.read(self.state.from as u32, &mut magic)?;
291
292 match u32::from_le_bytes(magic) {
293 SWAP_MAGIC => Ok(State::Swap),
294 _ => Ok(State::Boot),
295 }
296 }
297}
298
299/// FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
300/// 'mess up' the internal bootloader state
301pub struct FirmwareUpdater {
302 state: Partition,
303 dfu: Partition,
304}
305
306impl FirmwareUpdater {
307 pub const fn new(dfu: Partition, state: Partition) -> Self {
308 Self { dfu, state }
309 }
310
311 /// Return the length of the DFU area
312 pub fn firmware_len(&self) -> usize {
313 self.dfu.len()
314 }
315
316 /// Instruct bootloader that DFU should commence at next boot.
317 pub async fn mark_update<F: AsyncNorFlash>(&mut self, flash: &mut F) -> Result<(), F::Error> {
318 flash.write(self.state.from as u32, &[0, 0, 0, 0]).await?;
319 flash
320 .erase(self.state.from as u32, self.state.to as u32)
321 .await?;
322 info!(
323 "Setting swap magic at {} to 0x{:x}, LE: 0x{:x}",
324 self.state.from,
325 &SWAP_MAGIC,
326 &SWAP_MAGIC.to_le_bytes()
327 );
328 flash
329 .write(self.state.from as u32, &SWAP_MAGIC.to_le_bytes())
330 .await?;
331 Ok(())
332 }
333
334 /// Mark firmware boot successfully
335 pub async fn mark_booted<F: AsyncNorFlash>(&mut self, flash: &mut F) -> Result<(), F::Error> {
336 flash.write(self.state.from as u32, &[0, 0, 0, 0]).await?;
337 flash
338 .erase(self.state.from as u32, self.state.to as u32)
339 .await?;
340 flash
341 .write(self.state.from as u32, &BOOT_MAGIC.to_le_bytes())
342 .await?;
343 Ok(())
344 }
345
346 // Write to a region of the DFU page
347 pub async fn write_firmware<F: AsyncNorFlash>(
348 &mut self,
349 offset: usize,
350 data: &[u8],
351 flash: &mut F,
352 ) -> Result<(), F::Error> {
353 info!(
354 "Writing firmware at offset 0x{:x} len {}",
355 self.dfu.from + offset,
356 data.len()
357 );
358
359 flash
360 .erase(
361 (self.dfu.from + offset) as u32,
362 (self.dfu.from + offset + data.len()) as u32,
363 )
364 .await?;
365 flash.write((self.dfu.from + offset) as u32, data).await
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use core::convert::Infallible;
373 use core::future::Future;
374 use embedded_storage_async::nor_flash::AsyncReadNorFlash;
375 use futures::executor::block_on;
376
377 const STATE: Partition = Partition::new(0, 4096);
378 const ACTIVE: Partition = Partition::new(4096, 61440);
379 const DFU: Partition = Partition::new(61440, 122880);
380
381 #[test]
382 fn test_bad_magic() {
383 let mut flash = MemFlash([0xff; 131072]);
384
385 let mut bootloader = BootLoader::<4096>::new(ACTIVE, DFU, STATE);
386
387 assert_eq!(
388 bootloader.prepare_boot(&mut flash),
389 Err(BootError::BadMagic)
390 );
391 }
392
393 #[test]
394 fn test_boot_state() {
395 let mut flash = MemFlash([0xff; 131072]);
396 flash.0[0..4].copy_from_slice(&BOOT_MAGIC.to_le_bytes());
397
398 let mut bootloader = BootLoader::<4096>::new(ACTIVE, DFU, STATE);
399
400 assert_eq!(State::Boot, bootloader.prepare_boot(&mut flash).unwrap());
401 }
402
403 #[test]
404 fn test_swap_state() {
405 env_logger::init();
406 let mut flash = MemFlash([0xff; 131072]);
407
408 let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
409 let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
410
411 for i in ACTIVE.from..ACTIVE.to {
412 flash.0[i] = original[i - ACTIVE.from];
413 }
414
415 let mut bootloader = BootLoader::<4096>::new(ACTIVE, DFU, STATE);
416 let mut updater = FirmwareUpdater::new(DFU, STATE);
417 for i in (DFU.from..DFU.to).step_by(4) {
418 let base = i - DFU.from;
419 let data: [u8; 4] = [
420 update[base],
421 update[base + 1],
422 update[base + 2],
423 update[base + 3],
424 ];
425 block_on(updater.write_firmware(i - DFU.from, &data, &mut flash)).unwrap();
426 }
427 block_on(updater.mark_update(&mut flash)).unwrap();
428
429 assert_eq!(State::Swap, bootloader.prepare_boot(&mut flash).unwrap());
430
431 for i in ACTIVE.from..ACTIVE.to {
432 assert_eq!(flash.0[i], update[i - ACTIVE.from], "Index {}", i);
433 }
434
435 // First DFU page is untouched
436 for i in DFU.from + 4096..DFU.to {
437 assert_eq!(flash.0[i], original[i - DFU.from - 4096], "Index {}", i);
438 }
439
440 // Running again should cause a revert
441 assert_eq!(State::Swap, bootloader.prepare_boot(&mut flash).unwrap());
442
443 for i in ACTIVE.from..ACTIVE.to {
444 assert_eq!(flash.0[i], original[i - ACTIVE.from], "Index {}", i);
445 }
446
447 // Last page is untouched
448 for i in DFU.from..DFU.to - 4096 {
449 assert_eq!(flash.0[i], update[i - DFU.from], "Index {}", i);
450 }
451
452 // Mark as booted
453 block_on(updater.mark_booted(&mut flash)).unwrap();
454 assert_eq!(State::Boot, bootloader.prepare_boot(&mut flash).unwrap());
455 }
456
457 struct MemFlash([u8; 131072]);
458
459 impl NorFlash for MemFlash {
460 const WRITE_SIZE: usize = 4;
461 const ERASE_SIZE: usize = 4096;
462 fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
463 let from = from as usize;
464 let to = to as usize;
465 for i in from..to {
466 self.0[i] = 0xFF;
467 self.0[i] = 0xFF;
468 self.0[i] = 0xFF;
469 self.0[i] = 0xFF;
470 }
471 Ok(())
472 }
473
474 fn write(&mut self, offset: u32, data: &[u8]) -> Result<(), Self::Error> {
475 assert!(data.len() % 4 == 0);
476 assert!(offset % 4 == 0);
477 assert!(offset as usize + data.len() < 131072);
478
479 self.0[offset as usize..offset as usize + data.len()].copy_from_slice(data);
480
481 Ok(())
482 }
483 }
484
485 impl ReadNorFlash for MemFlash {
486 const READ_SIZE: usize = 4;
487 type Error = Infallible;
488
489 fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
490 let len = buf.len();
491 buf[..].copy_from_slice(&self.0[offset as usize..offset as usize + len]);
492 Ok(())
493 }
494
495 fn capacity(&self) -> usize {
496 131072
497 }
498 }
499
500 impl AsyncReadNorFlash for MemFlash {
501 const READ_SIZE: usize = 4;
502 type Error = Infallible;
503
504 type ReadFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
505 fn read<'a>(&'a mut self, offset: usize, buf: &'a mut [u8]) -> Self::ReadFuture<'a> {
506 async move {
507 let len = buf.len();
508 buf[..].copy_from_slice(&self.0[offset as usize..offset as usize + len]);
509 Ok(())
510 }
511 }
512
513 fn capacity(&self) -> usize {
514 131072
515 }
516 }
517
518 impl AsyncNorFlash for MemFlash {
519 const WRITE_SIZE: usize = 4;
520 const ERASE_SIZE: usize = 4096;
521
522 type EraseFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
523 fn erase<'a>(&'a mut self, from: u32, to: u32) -> Self::EraseFuture<'a> {
524 async move {
525 let from = from as usize;
526 let to = to as usize;
527 for i in from..to {
528 self.0[i] = 0xFF;
529 self.0[i] = 0xFF;
530 self.0[i] = 0xFF;
531 self.0[i] = 0xFF;
532 }
533 Ok(())
534 }
535 }
536
537 type WriteFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
538 fn write<'a>(&'a mut self, offset: u32, data: &'a [u8]) -> Self::WriteFuture<'a> {
539 async move {
540 assert!(data.len() % 4 == 0);
541 assert!(offset % 4 == 0);
542 assert!(offset as usize + data.len() < 131072);
543
544 self.0[offset as usize..offset as usize + data.len()].copy_from_slice(data);
545
546 Ok(())
547 }
548 }
549 }
550}