David Brown | e2acfae | 2020-01-21 16:45:01 -0700 | [diff] [blame] | 1 | // Copyright (c) 2017-2019 Linaro LTD |
| 2 | // Copyright (c) 2017-2018 JUUL Labs |
| 3 | // |
| 4 | // SPDX-License-Identifier: Apache-2.0 |
| 5 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 6 | //! A flash simulator |
| 7 | //! |
| 8 | //! This module is capable of simulating the type of NOR flash commonly used in microcontrollers. |
| 9 | //! These generally can be written as individual bytes, but must be erased in larger units. |
| 10 | |
David Brown | 2cbc470 | 2017-07-06 14:18:58 -0600 | [diff] [blame] | 11 | mod pdump; |
| 12 | |
David Brown | afabfcf | 2019-01-02 11:30:27 -0700 | [diff] [blame] | 13 | use crate::pdump::HexDump; |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 14 | use log::info; |
| 15 | use rand::{ |
| 16 | self, |
David Brown | fd8b05e | 2020-07-09 15:33:49 -0600 | [diff] [blame] | 17 | distributions::Standard, |
| 18 | Rng, |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 19 | }; |
| 20 | use std::{ |
| 21 | collections::HashMap, |
| 22 | fs::File, |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 23 | io::{self, Write}, |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 24 | iter::Enumerate, |
| 25 | path::Path, |
| 26 | slice, |
| 27 | }; |
David Brown | c51949d | 2021-02-25 16:29:14 -0700 | [diff] [blame] | 28 | use thiserror::Error; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 29 | |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 30 | pub type Result<T> = std::result::Result<T, FlashError>; |
| 31 | |
David Brown | c51949d | 2021-02-25 16:29:14 -0700 | [diff] [blame] | 32 | #[derive(Error, Debug)] |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 33 | pub enum FlashError { |
David Brown | c51949d | 2021-02-25 16:29:14 -0700 | [diff] [blame] | 34 | #[error("Offset out of bounds: {0}")] |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 35 | OutOfBounds(String), |
David Brown | c51949d | 2021-02-25 16:29:14 -0700 | [diff] [blame] | 36 | #[error("Invalid write: {0}")] |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 37 | Write(String), |
David Brown | c51949d | 2021-02-25 16:29:14 -0700 | [diff] [blame] | 38 | #[error("Write failed by chance: {0}")] |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 39 | SimulatedFail(String), |
David Brown | c51949d | 2021-02-25 16:29:14 -0700 | [diff] [blame] | 40 | #[error("{0}")] |
| 41 | Io(#[from] io::Error), |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 42 | } |
| 43 | |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 44 | // Transition from error-chain. |
| 45 | macro_rules! bail { |
| 46 | ($item:expr) => (return Err($item.into());) |
| 47 | } |
| 48 | |
Fabio Utzig | 1c9aea5 | 2018-11-15 10:36:07 -0200 | [diff] [blame] | 49 | pub struct FlashPtr { |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 50 | pub ptr: *mut dyn Flash, |
Fabio Utzig | 1c9aea5 | 2018-11-15 10:36:07 -0200 | [diff] [blame] | 51 | } |
| 52 | unsafe impl Send for FlashPtr {} |
| 53 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 54 | pub trait Flash { |
| 55 | fn erase(&mut self, offset: usize, len: usize) -> Result<()>; |
| 56 | fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()>; |
| 57 | fn read(&self, offset: usize, data: &mut [u8]) -> Result<()>; |
| 58 | |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 59 | fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()>; |
| 60 | fn reset_bad_regions(&mut self); |
| 61 | |
Fabio Utzig | fa137fc | 2017-11-23 20:01:02 -0200 | [diff] [blame] | 62 | fn set_verify_writes(&mut self, enable: bool); |
| 63 | |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 64 | fn sector_iter(&self) -> SectorIter<'_>; |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 65 | fn device_size(&self) -> usize; |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 66 | |
Fabio Utzig | 269d286 | 2018-10-24 17:45:38 -0300 | [diff] [blame] | 67 | fn align(&self) -> usize; |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 68 | fn erased_val(&self) -> u8; |
Roman Okhrimenko | 13f79ed | 2021-03-11 19:05:41 +0200 | [diff] [blame] | 69 | |
| 70 | fn set_erase_by_sector(&mut self, enable: bool); |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 71 | } |
| 72 | |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 73 | fn ebounds<T: AsRef<str>>(message: T) -> FlashError { |
| 74 | FlashError::OutOfBounds(message.as_ref().to_owned()) |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 75 | } |
| 76 | |
Fabio Utzig | 65935d7 | 2017-07-17 15:34:36 -0300 | [diff] [blame] | 77 | #[allow(dead_code)] |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 78 | fn ewrite<T: AsRef<str>>(message: T) -> FlashError { |
| 79 | FlashError::Write(message.as_ref().to_owned()) |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 80 | } |
| 81 | |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 82 | #[allow(dead_code)] |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 83 | fn esimulatedwrite<T: AsRef<str>>(message: T) -> FlashError { |
| 84 | FlashError::SimulatedFail(message.as_ref().to_owned()) |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 85 | } |
| 86 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 87 | /// An emulated flash device. It is represented as a block of bytes, and a list of the sector |
Sam Bristow | d0ca0ff | 2019-10-30 20:51:35 +1300 | [diff] [blame] | 88 | /// mappings. |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 89 | #[derive(Clone)] |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 90 | pub struct SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 91 | data: Vec<u8>, |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 92 | write_safe: Vec<bool>, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 93 | sectors: Vec<usize>, |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 94 | bad_region: Vec<(usize, usize, f32)>, |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 95 | // Alignment required for writes. |
| 96 | align: usize, |
Fabio Utzig | fa137fc | 2017-11-23 20:01:02 -0200 | [diff] [blame] | 97 | verify_writes: bool, |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 98 | erased_val: u8, |
Roman Okhrimenko | 13f79ed | 2021-03-11 19:05:41 +0200 | [diff] [blame] | 99 | erase_by_sector: bool, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 100 | } |
| 101 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 102 | impl SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 103 | /// Given a sector size map, construct a flash device for that. |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 104 | pub fn new(sectors: Vec<usize>, align: usize, erased_val: u8) -> SimFlash { |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 105 | // Verify that the alignment is a positive power of two. |
| 106 | assert!(align > 0); |
| 107 | assert!(align & (align - 1) == 0); |
| 108 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 109 | let total = sectors.iter().sum(); |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 110 | SimFlash { |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 111 | data: vec![erased_val; total], |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 112 | write_safe: vec![true; total], |
David Brown | 4dfb33c | 2021-03-10 05:15:45 -0700 | [diff] [blame] | 113 | sectors, |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 114 | bad_region: Vec::new(), |
David Brown | 4dfb33c | 2021-03-10 05:15:45 -0700 | [diff] [blame] | 115 | align, |
Fabio Utzig | fa137fc | 2017-11-23 20:01:02 -0200 | [diff] [blame] | 116 | verify_writes: true, |
David Brown | 4dfb33c | 2021-03-10 05:15:45 -0700 | [diff] [blame] | 117 | erased_val, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 118 | } |
| 119 | } |
| 120 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 121 | #[allow(dead_code)] |
| 122 | pub fn dump(&self) { |
| 123 | self.data.dump(); |
| 124 | } |
| 125 | |
| 126 | /// Dump this image to the given file. |
| 127 | #[allow(dead_code)] |
| 128 | pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> { |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 129 | let mut fd = File::create(path)?; |
| 130 | fd.write_all(&self.data)?; |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 131 | Ok(()) |
| 132 | } |
| 133 | |
| 134 | // Scan the sector map, and return the base and offset within a sector for this given byte. |
| 135 | // Returns None if the value is outside of the device. |
Roman Okhrimenko | 13f79ed | 2021-03-11 19:05:41 +0200 | [diff] [blame] | 136 | fn get_sector(&self, offset: usize) -> Option<(usize, usize, usize)> { |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 137 | let mut offset = offset; |
| 138 | for (sector, &size) in self.sectors.iter().enumerate() { |
| 139 | if offset < size { |
Roman Okhrimenko | 13f79ed | 2021-03-11 19:05:41 +0200 | [diff] [blame] | 140 | return Some((sector, offset, size)); |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 141 | } |
| 142 | offset -= size; |
| 143 | } |
David Brown | c20bbb2 | 2021-03-10 05:19:14 -0700 | [diff] [blame] | 144 | None |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 145 | } |
| 146 | |
| 147 | } |
| 148 | |
David Brown | 7610157 | 2019-02-28 11:29:03 -0700 | [diff] [blame] | 149 | pub type SimMultiFlash = HashMap<u8, SimFlash>; |
Fabio Utzig | afb2bc9 | 2018-11-19 16:11:52 -0200 | [diff] [blame] | 150 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 151 | impl Flash for SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 152 | /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be |
| 153 | /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise |
| 154 | /// return an error. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 155 | fn erase(&mut self, offset: usize, len: usize) -> Result<()> { |
Roman Okhrimenko | 13f79ed | 2021-03-11 19:05:41 +0200 | [diff] [blame] | 156 | let (_start, mut slen, ssize) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?; |
| 157 | let (end, mut elen, _) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?; |
| 158 | |
| 159 | let mut offset = offset; |
| 160 | let mut len = len; |
| 161 | |
| 162 | if self.erase_by_sector { |
| 163 | // info!("erase_by_sector: {:#X}/{:#X} -> {:#X}/{:#X}", offset, len, offset - slen, ssize); |
| 164 | |
| 165 | offset = offset - slen; |
| 166 | len = ssize; |
| 167 | |
| 168 | slen = 0; |
| 169 | elen = self.sectors[end] - 1; |
| 170 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 171 | |
| 172 | if slen != 0 { |
| 173 | bail!(ebounds("offset not at start of sector")); |
| 174 | } |
| 175 | if elen != self.sectors[end] - 1 { |
| 176 | bail!(ebounds("end not at start of sector")); |
| 177 | } |
| 178 | |
| 179 | for x in &mut self.data[offset .. offset + len] { |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 180 | *x = self.erased_val; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 181 | } |
| 182 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 183 | for x in &mut self.write_safe[offset .. offset + len] { |
| 184 | *x = true; |
| 185 | } |
| 186 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 187 | Ok(()) |
| 188 | } |
| 189 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 190 | /// We restrict to only allowing writes of values that are: |
| 191 | /// |
| 192 | /// 1. being written to for the first time |
| 193 | /// 2. being written to after being erased |
| 194 | /// |
| 195 | /// This emulates a flash device which starts out erased, with the |
| 196 | /// added restriction that repeated writes to the same location |
| 197 | /// are disallowed, even if they would be safe to do. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 198 | fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> { |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 199 | for &(off, len, rate) in &self.bad_region { |
| 200 | if offset >= off && (offset + payload.len()) <= (off + len) { |
| 201 | let mut rng = rand::thread_rng(); |
David Brown | fd8b05e | 2020-07-09 15:33:49 -0600 | [diff] [blame] | 202 | let samp: f32 = rng.sample(Standard); |
| 203 | if samp < rate { |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 204 | bail!(esimulatedwrite( |
| 205 | format!("Ignoring write to {:#x}-{:#x}", off, off + len))); |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 210 | if offset + payload.len() > self.data.len() { |
David Brown | f253fa8 | 2017-01-23 15:43:47 -0700 | [diff] [blame] | 211 | panic!("Write outside of device"); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 212 | } |
| 213 | |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 214 | // Verify the alignment (which must be a power of two). |
| 215 | if offset & (self.align - 1) != 0 { |
David Brown | f253fa8 | 2017-01-23 15:43:47 -0700 | [diff] [blame] | 216 | panic!("Misaligned write address"); |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 217 | } |
| 218 | |
| 219 | if payload.len() & (self.align - 1) != 0 { |
David Brown | f253fa8 | 2017-01-23 15:43:47 -0700 | [diff] [blame] | 220 | panic!("Write length not multiple of alignment"); |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 221 | } |
| 222 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 223 | for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() { |
Fabio Utzig | fa137fc | 2017-11-23 20:01:02 -0200 | [diff] [blame] | 224 | if self.verify_writes && !(*x) { |
Fabio Utzig | 65935d7 | 2017-07-17 15:34:36 -0300 | [diff] [blame] | 225 | panic!("Write to unerased location at 0x{:x}", offset + i); |
Fabio Utzig | 19b2c1a | 2017-04-20 07:32:44 -0300 | [diff] [blame] | 226 | } |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 227 | *x = false; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 228 | } |
| 229 | |
David Brown | 59ae522 | 2017-12-06 11:45:15 -0700 | [diff] [blame] | 230 | let sub = &mut self.data[offset .. offset + payload.len()]; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 231 | sub.copy_from_slice(payload); |
| 232 | Ok(()) |
| 233 | } |
| 234 | |
| 235 | /// Read is simple. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 236 | fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 237 | if offset + data.len() > self.data.len() { |
| 238 | bail!(ebounds("Read outside of device")); |
| 239 | } |
| 240 | |
| 241 | let sub = &self.data[offset .. offset + data.len()]; |
| 242 | data.copy_from_slice(sub); |
| 243 | Ok(()) |
| 244 | } |
| 245 | |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 246 | /// Adds a new flash bad region. Writes to this area fail with a chance |
| 247 | /// given by `rate`. |
| 248 | fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()> { |
David Brown | 2547c00 | 2021-03-10 05:20:17 -0700 | [diff] [blame] | 249 | if !(0.0..=1.0).contains(&rate) { |
Fabio Utzig | f5c895e | 2017-11-23 19:57:17 -0200 | [diff] [blame] | 250 | bail!(ebounds("Invalid rate")); |
| 251 | } |
| 252 | |
| 253 | info!("Adding new bad region {:#x}-{:#x}", offset, offset + len); |
| 254 | self.bad_region.push((offset, len, rate)); |
| 255 | |
| 256 | Ok(()) |
| 257 | } |
| 258 | |
| 259 | fn reset_bad_regions(&mut self) { |
| 260 | self.bad_region.clear(); |
| 261 | } |
| 262 | |
Fabio Utzig | fa137fc | 2017-11-23 20:01:02 -0200 | [diff] [blame] | 263 | fn set_verify_writes(&mut self, enable: bool) { |
| 264 | self.verify_writes = enable; |
| 265 | } |
| 266 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 267 | /// An iterator over each sector in the device. |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 268 | fn sector_iter(&self) -> SectorIter<'_> { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 269 | SectorIter { |
| 270 | iter: self.sectors.iter().enumerate(), |
| 271 | base: 0, |
| 272 | } |
| 273 | } |
| 274 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 275 | fn device_size(&self) -> usize { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 276 | self.data.len() |
| 277 | } |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 278 | |
Fabio Utzig | 269d286 | 2018-10-24 17:45:38 -0300 | [diff] [blame] | 279 | fn align(&self) -> usize { |
| 280 | self.align |
| 281 | } |
| 282 | |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 283 | fn erased_val(&self) -> u8 { |
| 284 | self.erased_val |
| 285 | } |
Roman Okhrimenko | 13f79ed | 2021-03-11 19:05:41 +0200 | [diff] [blame] | 286 | |
| 287 | fn set_erase_by_sector(&mut self, enable: bool) { |
| 288 | self.erase_by_sector = enable; |
| 289 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 290 | } |
| 291 | |
| 292 | /// It is possible to iterate over the sectors in the device, each element returning this. |
David Brown | 3f687dc | 2017-11-06 13:41:18 -0700 | [diff] [blame] | 293 | #[derive(Debug, Clone)] |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 294 | pub struct Sector { |
| 295 | /// Which sector is this, starting from 0. |
| 296 | pub num: usize, |
| 297 | /// The offset, in bytes, of the start of this sector. |
| 298 | pub base: usize, |
| 299 | /// The length, in bytes, of this sector. |
| 300 | pub size: usize, |
| 301 | } |
| 302 | |
| 303 | pub struct SectorIter<'a> { |
| 304 | iter: Enumerate<slice::Iter<'a, usize>>, |
| 305 | base: usize, |
| 306 | } |
| 307 | |
| 308 | impl<'a> Iterator for SectorIter<'a> { |
| 309 | type Item = Sector; |
| 310 | |
| 311 | fn next(&mut self) -> Option<Sector> { |
| 312 | match self.iter.next() { |
| 313 | None => None, |
| 314 | Some((num, &size)) => { |
| 315 | let base = self.base; |
| 316 | self.base += size; |
| 317 | Some(Sector { |
David Brown | 4dfb33c | 2021-03-10 05:15:45 -0700 | [diff] [blame] | 318 | num, |
| 319 | base, |
| 320 | size, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 321 | }) |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | #[cfg(test)] |
| 328 | mod test { |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 329 | use super::{Flash, FlashError, SimFlash, Result, Sector}; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 330 | |
| 331 | #[test] |
| 332 | fn test_flash() { |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 333 | for &erased_val in &[0, 0xff] { |
| 334 | // NXP-style, uniform sectors. |
| 335 | let mut f1 = SimFlash::new(vec![4096usize; 256], 1, erased_val); |
| 336 | test_device(&mut f1, erased_val); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 337 | |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 338 | // STM style, non-uniform sectors. |
| 339 | let mut f2 = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024, |
| 340 | 128 * 1024, 128 * 1024, 128 * 1024], 1, erased_val); |
| 341 | test_device(&mut f2, erased_val); |
| 342 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 343 | } |
| 344 | |
David Brown | ea25c41 | 2019-01-02 11:33:55 -0700 | [diff] [blame] | 345 | fn test_device(flash: &mut dyn Flash, erased_val: u8) { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 346 | let sectors: Vec<Sector> = flash.sector_iter().collect(); |
| 347 | |
| 348 | flash.erase(0, sectors[0].size).unwrap(); |
| 349 | let flash_size = flash.device_size(); |
| 350 | flash.erase(0, flash_size).unwrap(); |
| 351 | assert!(flash.erase(0, sectors[0].size - 1).is_bounds()); |
| 352 | |
| 353 | // Verify that write and erase do something. |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 354 | flash.write(0, &[0x55]).unwrap(); |
| 355 | let mut buf = [0xAA; 4]; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 356 | flash.read(0, &mut buf).unwrap(); |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 357 | assert_eq!(buf, [0x55, erased_val, erased_val, erased_val]); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 358 | |
| 359 | flash.erase(0, sectors[0].size).unwrap(); |
| 360 | flash.read(0, &mut buf).unwrap(); |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 361 | assert_eq!(buf, [erased_val; 4]); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 362 | |
| 363 | // Program the first and last byte of each sector, verify that has been done, and then |
| 364 | // erase to verify the erase boundaries. |
| 365 | for sector in §ors { |
| 366 | let byte = [(sector.num & 127) as u8]; |
| 367 | flash.write(sector.base, &byte).unwrap(); |
| 368 | flash.write(sector.base + sector.size - 1, &byte).unwrap(); |
| 369 | } |
| 370 | |
| 371 | // Verify the above |
| 372 | let mut buf = Vec::new(); |
| 373 | for sector in §ors { |
| 374 | let byte = (sector.num & 127) as u8; |
| 375 | buf.resize(sector.size, 0); |
| 376 | flash.read(sector.base, &mut buf).unwrap(); |
| 377 | assert_eq!(buf.first(), Some(&byte)); |
| 378 | assert_eq!(buf.last(), Some(&byte)); |
Fabio Utzig | ea0290b | 2018-08-09 14:23:01 -0300 | [diff] [blame] | 379 | assert!(buf[1..buf.len()-1].iter().all(|&x| x == erased_val)); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 380 | } |
| 381 | } |
| 382 | |
| 383 | // Helper checks for the result type. |
| 384 | trait EChecker { |
| 385 | fn is_bounds(&self) -> bool; |
| 386 | } |
| 387 | |
| 388 | impl<T> EChecker for Result<T> { |
| 389 | |
| 390 | fn is_bounds(&self) -> bool { |
| 391 | match *self { |
David Brown | 96eb0de | 2019-02-22 16:23:59 -0700 | [diff] [blame] | 392 | Err(FlashError::OutOfBounds(_)) => true, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 393 | _ => false, |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | } |