blob: c991d4787e99ebad9619a6c58d064e821d615134 [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2017-2019 Linaro LTD
2// Copyright (c) 2017-2018 JUUL Labs
3//
4// SPDX-License-Identifier: Apache-2.0
5
David Brownde7729e2017-01-09 10:41:35 -07006//! 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 Brown2cbc4702017-07-06 14:18:58 -060011mod pdump;
12
David Brownafabfcf2019-01-02 11:30:27 -070013use crate::pdump::HexDump;
David Brown96eb0de2019-02-22 16:23:59 -070014use failure::Fail;
David Brownea25c412019-01-02 11:33:55 -070015use log::info;
16use rand::{
17 self,
18 distributions::{IndependentSample, Range},
19};
20use std::{
21 collections::HashMap,
22 fs::File,
David Brown96eb0de2019-02-22 16:23:59 -070023 io::{self, Write},
David Brownea25c412019-01-02 11:33:55 -070024 iter::Enumerate,
25 path::Path,
26 slice,
27};
David Brownde7729e2017-01-09 10:41:35 -070028
David Brown96eb0de2019-02-22 16:23:59 -070029pub type Result<T> = std::result::Result<T, FlashError>;
30
31#[derive(Fail, Debug)]
32pub enum FlashError {
33 #[fail(display = "Offset out of bounds: {}", _0)]
34 OutOfBounds(String),
35 #[fail(display = "Invalid write: {}", _0)]
36 Write(String),
37 #[fail(display = "Write failed by chance: {}", _0)]
38 SimulatedFail(String),
39 #[fail(display = "{}", _0)]
40 Io(#[cause] io::Error),
41}
42
43impl From<io::Error> for FlashError {
44 fn from(error: io::Error) -> Self {
45 FlashError::Io(error)
David Brownde7729e2017-01-09 10:41:35 -070046 }
47}
48
David Brown96eb0de2019-02-22 16:23:59 -070049// Transition from error-chain.
50macro_rules! bail {
51 ($item:expr) => (return Err($item.into());)
52}
53
Fabio Utzig1c9aea52018-11-15 10:36:07 -020054pub struct FlashPtr {
David Brownea25c412019-01-02 11:33:55 -070055 pub ptr: *mut dyn Flash,
Fabio Utzig1c9aea52018-11-15 10:36:07 -020056}
57unsafe impl Send for FlashPtr {}
58
David Brown7ddec0b2017-07-06 10:47:35 -060059pub trait Flash {
60 fn erase(&mut self, offset: usize, len: usize) -> Result<()>;
61 fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()>;
62 fn read(&self, offset: usize, data: &mut [u8]) -> Result<()>;
63
Fabio Utzigf5c895e2017-11-23 19:57:17 -020064 fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()>;
65 fn reset_bad_regions(&mut self);
66
Fabio Utzigfa137fc2017-11-23 20:01:02 -020067 fn set_verify_writes(&mut self, enable: bool);
68
David Brownea25c412019-01-02 11:33:55 -070069 fn sector_iter(&self) -> SectorIter<'_>;
David Brown7ddec0b2017-07-06 10:47:35 -060070 fn device_size(&self) -> usize;
Fabio Utzigea0290b2018-08-09 14:23:01 -030071
Fabio Utzig269d2862018-10-24 17:45:38 -030072 fn align(&self) -> usize;
Fabio Utzigea0290b2018-08-09 14:23:01 -030073 fn erased_val(&self) -> u8;
David Brown7ddec0b2017-07-06 10:47:35 -060074}
75
David Brown96eb0de2019-02-22 16:23:59 -070076fn ebounds<T: AsRef<str>>(message: T) -> FlashError {
77 FlashError::OutOfBounds(message.as_ref().to_owned())
David Brownde7729e2017-01-09 10:41:35 -070078}
79
Fabio Utzig65935d72017-07-17 15:34:36 -030080#[allow(dead_code)]
David Brown96eb0de2019-02-22 16:23:59 -070081fn ewrite<T: AsRef<str>>(message: T) -> FlashError {
82 FlashError::Write(message.as_ref().to_owned())
David Brownde7729e2017-01-09 10:41:35 -070083}
84
Fabio Utzigf5c895e2017-11-23 19:57:17 -020085#[allow(dead_code)]
David Brown96eb0de2019-02-22 16:23:59 -070086fn esimulatedwrite<T: AsRef<str>>(message: T) -> FlashError {
87 FlashError::SimulatedFail(message.as_ref().to_owned())
Fabio Utzigf5c895e2017-11-23 19:57:17 -020088}
89
David Brownde7729e2017-01-09 10:41:35 -070090/// An emulated flash device. It is represented as a block of bytes, and a list of the sector
Sam Bristowd0ca0ff2019-10-30 20:51:35 +130091/// mappings.
David Brownde7729e2017-01-09 10:41:35 -070092#[derive(Clone)]
David Brown7ddec0b2017-07-06 10:47:35 -060093pub struct SimFlash {
David Brownde7729e2017-01-09 10:41:35 -070094 data: Vec<u8>,
Marti Bolivar51d36dd2017-05-17 17:39:46 -040095 write_safe: Vec<bool>,
David Brownde7729e2017-01-09 10:41:35 -070096 sectors: Vec<usize>,
Fabio Utzigf5c895e2017-11-23 19:57:17 -020097 bad_region: Vec<(usize, usize, f32)>,
David Brown562a7a02017-01-23 11:19:03 -070098 // Alignment required for writes.
99 align: usize,
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200100 verify_writes: bool,
Fabio Utzigea0290b2018-08-09 14:23:01 -0300101 erased_val: u8,
David Brownde7729e2017-01-09 10:41:35 -0700102}
103
David Brown7ddec0b2017-07-06 10:47:35 -0600104impl SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700105 /// Given a sector size map, construct a flash device for that.
Fabio Utzigea0290b2018-08-09 14:23:01 -0300106 pub fn new(sectors: Vec<usize>, align: usize, erased_val: u8) -> SimFlash {
David Brown562a7a02017-01-23 11:19:03 -0700107 // Verify that the alignment is a positive power of two.
108 assert!(align > 0);
109 assert!(align & (align - 1) == 0);
110
David Brownde7729e2017-01-09 10:41:35 -0700111 let total = sectors.iter().sum();
David Brown7ddec0b2017-07-06 10:47:35 -0600112 SimFlash {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300113 data: vec![erased_val; total],
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400114 write_safe: vec![true; total],
David Brownde7729e2017-01-09 10:41:35 -0700115 sectors: sectors,
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200116 bad_region: Vec::new(),
David Brown562a7a02017-01-23 11:19:03 -0700117 align: align,
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200118 verify_writes: true,
Fabio Utzigea0290b2018-08-09 14:23:01 -0300119 erased_val: erased_val,
David Brownde7729e2017-01-09 10:41:35 -0700120 }
121 }
122
David Brown7ddec0b2017-07-06 10:47:35 -0600123 #[allow(dead_code)]
124 pub fn dump(&self) {
125 self.data.dump();
126 }
127
128 /// Dump this image to the given file.
129 #[allow(dead_code)]
130 pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
David Brown96eb0de2019-02-22 16:23:59 -0700131 let mut fd = File::create(path)?;
132 fd.write_all(&self.data)?;
David Brown7ddec0b2017-07-06 10:47:35 -0600133 Ok(())
134 }
135
136 // Scan the sector map, and return the base and offset within a sector for this given byte.
137 // Returns None if the value is outside of the device.
138 fn get_sector(&self, offset: usize) -> Option<(usize, usize)> {
139 let mut offset = offset;
140 for (sector, &size) in self.sectors.iter().enumerate() {
141 if offset < size {
142 return Some((sector, offset));
143 }
144 offset -= size;
145 }
146 return None;
147 }
148
149}
150
David Brown76101572019-02-28 11:29:03 -0700151pub type SimMultiFlash = HashMap<u8, SimFlash>;
Fabio Utzigafb2bc92018-11-19 16:11:52 -0200152
David Brown7ddec0b2017-07-06 10:47:35 -0600153impl Flash for SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700154 /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be
155 /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise
156 /// return an error.
David Brown7ddec0b2017-07-06 10:47:35 -0600157 fn erase(&mut self, offset: usize, len: usize) -> Result<()> {
David Brownde7729e2017-01-09 10:41:35 -0700158 let (_start, slen) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?;
159 let (end, elen) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?;
160
161 if slen != 0 {
162 bail!(ebounds("offset not at start of sector"));
163 }
164 if elen != self.sectors[end] - 1 {
165 bail!(ebounds("end not at start of sector"));
166 }
167
168 for x in &mut self.data[offset .. offset + len] {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300169 *x = self.erased_val;
David Brownde7729e2017-01-09 10:41:35 -0700170 }
171
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400172 for x in &mut self.write_safe[offset .. offset + len] {
173 *x = true;
174 }
175
David Brownde7729e2017-01-09 10:41:35 -0700176 Ok(())
177 }
178
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400179 /// We restrict to only allowing writes of values that are:
180 ///
181 /// 1. being written to for the first time
182 /// 2. being written to after being erased
183 ///
184 /// This emulates a flash device which starts out erased, with the
185 /// added restriction that repeated writes to the same location
186 /// are disallowed, even if they would be safe to do.
David Brown7ddec0b2017-07-06 10:47:35 -0600187 fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> {
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200188 for &(off, len, rate) in &self.bad_region {
189 if offset >= off && (offset + payload.len()) <= (off + len) {
190 let mut rng = rand::thread_rng();
191 let between = Range::new(0., 1.);
192 if between.ind_sample(&mut rng) < rate {
193 bail!(esimulatedwrite(
194 format!("Ignoring write to {:#x}-{:#x}", off, off + len)));
195 }
196 }
197 }
198
David Brownde7729e2017-01-09 10:41:35 -0700199 if offset + payload.len() > self.data.len() {
David Brownf253fa82017-01-23 15:43:47 -0700200 panic!("Write outside of device");
David Brownde7729e2017-01-09 10:41:35 -0700201 }
202
David Brown562a7a02017-01-23 11:19:03 -0700203 // Verify the alignment (which must be a power of two).
204 if offset & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700205 panic!("Misaligned write address");
David Brown562a7a02017-01-23 11:19:03 -0700206 }
207
208 if payload.len() & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700209 panic!("Write length not multiple of alignment");
David Brown562a7a02017-01-23 11:19:03 -0700210 }
211
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400212 for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() {
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200213 if self.verify_writes && !(*x) {
Fabio Utzig65935d72017-07-17 15:34:36 -0300214 panic!("Write to unerased location at 0x{:x}", offset + i);
Fabio Utzig19b2c1a2017-04-20 07:32:44 -0300215 }
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400216 *x = false;
David Brownde7729e2017-01-09 10:41:35 -0700217 }
218
David Brown59ae5222017-12-06 11:45:15 -0700219 let sub = &mut self.data[offset .. offset + payload.len()];
David Brownde7729e2017-01-09 10:41:35 -0700220 sub.copy_from_slice(payload);
221 Ok(())
222 }
223
224 /// Read is simple.
David Brown7ddec0b2017-07-06 10:47:35 -0600225 fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> {
David Brownde7729e2017-01-09 10:41:35 -0700226 if offset + data.len() > self.data.len() {
227 bail!(ebounds("Read outside of device"));
228 }
229
230 let sub = &self.data[offset .. offset + data.len()];
231 data.copy_from_slice(sub);
232 Ok(())
233 }
234
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200235 /// Adds a new flash bad region. Writes to this area fail with a chance
236 /// given by `rate`.
237 fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()> {
238 if rate < 0.0 || rate > 1.0 {
239 bail!(ebounds("Invalid rate"));
240 }
241
242 info!("Adding new bad region {:#x}-{:#x}", offset, offset + len);
243 self.bad_region.push((offset, len, rate));
244
245 Ok(())
246 }
247
248 fn reset_bad_regions(&mut self) {
249 self.bad_region.clear();
250 }
251
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200252 fn set_verify_writes(&mut self, enable: bool) {
253 self.verify_writes = enable;
254 }
255
David Brownde7729e2017-01-09 10:41:35 -0700256 /// An iterator over each sector in the device.
David Brownea25c412019-01-02 11:33:55 -0700257 fn sector_iter(&self) -> SectorIter<'_> {
David Brownde7729e2017-01-09 10:41:35 -0700258 SectorIter {
259 iter: self.sectors.iter().enumerate(),
260 base: 0,
261 }
262 }
263
David Brown7ddec0b2017-07-06 10:47:35 -0600264 fn device_size(&self) -> usize {
David Brownde7729e2017-01-09 10:41:35 -0700265 self.data.len()
266 }
Fabio Utzigea0290b2018-08-09 14:23:01 -0300267
Fabio Utzig269d2862018-10-24 17:45:38 -0300268 fn align(&self) -> usize {
269 self.align
270 }
271
Fabio Utzigea0290b2018-08-09 14:23:01 -0300272 fn erased_val(&self) -> u8 {
273 self.erased_val
274 }
David Brownde7729e2017-01-09 10:41:35 -0700275}
276
277/// It is possible to iterate over the sectors in the device, each element returning this.
David Brown3f687dc2017-11-06 13:41:18 -0700278#[derive(Debug, Clone)]
David Brownde7729e2017-01-09 10:41:35 -0700279pub struct Sector {
280 /// Which sector is this, starting from 0.
281 pub num: usize,
282 /// The offset, in bytes, of the start of this sector.
283 pub base: usize,
284 /// The length, in bytes, of this sector.
285 pub size: usize,
286}
287
288pub struct SectorIter<'a> {
289 iter: Enumerate<slice::Iter<'a, usize>>,
290 base: usize,
291}
292
293impl<'a> Iterator for SectorIter<'a> {
294 type Item = Sector;
295
296 fn next(&mut self) -> Option<Sector> {
297 match self.iter.next() {
298 None => None,
299 Some((num, &size)) => {
300 let base = self.base;
301 self.base += size;
302 Some(Sector {
303 num: num,
304 base: base,
305 size: size,
306 })
307 }
308 }
309 }
310}
311
312#[cfg(test)]
313mod test {
David Brown96eb0de2019-02-22 16:23:59 -0700314 use super::{Flash, FlashError, SimFlash, Result, Sector};
David Brownde7729e2017-01-09 10:41:35 -0700315
316 #[test]
317 fn test_flash() {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300318 for &erased_val in &[0, 0xff] {
319 // NXP-style, uniform sectors.
320 let mut f1 = SimFlash::new(vec![4096usize; 256], 1, erased_val);
321 test_device(&mut f1, erased_val);
David Brownde7729e2017-01-09 10:41:35 -0700322
Fabio Utzigea0290b2018-08-09 14:23:01 -0300323 // STM style, non-uniform sectors.
324 let mut f2 = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
325 128 * 1024, 128 * 1024, 128 * 1024], 1, erased_val);
326 test_device(&mut f2, erased_val);
327 }
David Brownde7729e2017-01-09 10:41:35 -0700328 }
329
David Brownea25c412019-01-02 11:33:55 -0700330 fn test_device(flash: &mut dyn Flash, erased_val: u8) {
David Brownde7729e2017-01-09 10:41:35 -0700331 let sectors: Vec<Sector> = flash.sector_iter().collect();
332
333 flash.erase(0, sectors[0].size).unwrap();
334 let flash_size = flash.device_size();
335 flash.erase(0, flash_size).unwrap();
336 assert!(flash.erase(0, sectors[0].size - 1).is_bounds());
337
338 // Verify that write and erase do something.
Fabio Utzigea0290b2018-08-09 14:23:01 -0300339 flash.write(0, &[0x55]).unwrap();
340 let mut buf = [0xAA; 4];
David Brownde7729e2017-01-09 10:41:35 -0700341 flash.read(0, &mut buf).unwrap();
Fabio Utzigea0290b2018-08-09 14:23:01 -0300342 assert_eq!(buf, [0x55, erased_val, erased_val, erased_val]);
David Brownde7729e2017-01-09 10:41:35 -0700343
344 flash.erase(0, sectors[0].size).unwrap();
345 flash.read(0, &mut buf).unwrap();
Fabio Utzigea0290b2018-08-09 14:23:01 -0300346 assert_eq!(buf, [erased_val; 4]);
David Brownde7729e2017-01-09 10:41:35 -0700347
348 // Program the first and last byte of each sector, verify that has been done, and then
349 // erase to verify the erase boundaries.
350 for sector in &sectors {
351 let byte = [(sector.num & 127) as u8];
352 flash.write(sector.base, &byte).unwrap();
353 flash.write(sector.base + sector.size - 1, &byte).unwrap();
354 }
355
356 // Verify the above
357 let mut buf = Vec::new();
358 for sector in &sectors {
359 let byte = (sector.num & 127) as u8;
360 buf.resize(sector.size, 0);
361 flash.read(sector.base, &mut buf).unwrap();
362 assert_eq!(buf.first(), Some(&byte));
363 assert_eq!(buf.last(), Some(&byte));
Fabio Utzigea0290b2018-08-09 14:23:01 -0300364 assert!(buf[1..buf.len()-1].iter().all(|&x| x == erased_val));
David Brownde7729e2017-01-09 10:41:35 -0700365 }
366 }
367
368 // Helper checks for the result type.
369 trait EChecker {
370 fn is_bounds(&self) -> bool;
371 }
372
373 impl<T> EChecker for Result<T> {
374
375 fn is_bounds(&self) -> bool {
376 match *self {
David Brown96eb0de2019-02-22 16:23:59 -0700377 Err(FlashError::OutOfBounds(_)) => true,
David Brownde7729e2017-01-09 10:41:35 -0700378 _ => false,
379 }
380 }
381 }
382}