blob: 9523a4f4ddaa17b31b49e90e9bf10a043c963a0b [file] [log] [blame]
David Brownde7729e2017-01-09 10:41:35 -07001//! A flash simulator
2//!
3//! This module is capable of simulating the type of NOR flash commonly used in microcontrollers.
4//! These generally can be written as individual bytes, but must be erased in larger units.
5
Fabio Utzigf5c895e2017-11-23 19:57:17 -02006#[macro_use] extern crate log;
David Brown2cbc4702017-07-06 14:18:58 -06007#[macro_use] extern crate error_chain;
Fabio Utzigf5c895e2017-11-23 19:57:17 -02008extern crate rand;
David Brown2cbc4702017-07-06 14:18:58 -06009mod pdump;
10
Fabio Utzigf5c895e2017-11-23 19:57:17 -020011use rand::distributions::{IndependentSample, Range};
David Brown163ab232017-01-23 15:48:35 -070012use std::fs::File;
13use std::io::Write;
David Brownde7729e2017-01-09 10:41:35 -070014use std::iter::Enumerate;
David Brown163ab232017-01-23 15:48:35 -070015use std::path::Path;
David Brownde7729e2017-01-09 10:41:35 -070016use std::slice;
17use pdump::HexDump;
18
19error_chain! {
20 errors {
21 OutOfBounds(t: String) {
22 description("Offset is out of bounds")
23 display("Offset out of bounds: {}", t)
24 }
25 Write(t: String) {
26 description("Invalid write")
27 display("Invalid write: {}", t)
28 }
Fabio Utzigf5c895e2017-11-23 19:57:17 -020029 SimulatedFail(t: String) {
30 description("Write failed by chance")
31 display("Failed write: {}", t)
32 }
David Brownde7729e2017-01-09 10:41:35 -070033 }
34}
35
David Brown7ddec0b2017-07-06 10:47:35 -060036pub trait Flash {
37 fn erase(&mut self, offset: usize, len: usize) -> Result<()>;
38 fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()>;
39 fn read(&self, offset: usize, data: &mut [u8]) -> Result<()>;
40
Fabio Utzigf5c895e2017-11-23 19:57:17 -020041 fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()>;
42 fn reset_bad_regions(&mut self);
43
Fabio Utzigfa137fc2017-11-23 20:01:02 -020044 fn set_verify_writes(&mut self, enable: bool);
45
David Brown7ddec0b2017-07-06 10:47:35 -060046 fn sector_iter(&self) -> SectorIter;
47 fn device_size(&self) -> usize;
Fabio Utzigea0290b2018-08-09 14:23:01 -030048
49 fn erased_val(&self) -> u8;
David Brown7ddec0b2017-07-06 10:47:35 -060050}
51
David Brownde7729e2017-01-09 10:41:35 -070052fn ebounds<T: AsRef<str>>(message: T) -> ErrorKind {
53 ErrorKind::OutOfBounds(message.as_ref().to_owned())
54}
55
Fabio Utzig65935d72017-07-17 15:34:36 -030056#[allow(dead_code)]
David Brownde7729e2017-01-09 10:41:35 -070057fn ewrite<T: AsRef<str>>(message: T) -> ErrorKind {
58 ErrorKind::Write(message.as_ref().to_owned())
59}
60
Fabio Utzigf5c895e2017-11-23 19:57:17 -020061#[allow(dead_code)]
62fn esimulatedwrite<T: AsRef<str>>(message: T) -> ErrorKind {
63 ErrorKind::SimulatedFail(message.as_ref().to_owned())
64}
65
David Brownde7729e2017-01-09 10:41:35 -070066/// An emulated flash device. It is represented as a block of bytes, and a list of the sector
67/// mapings.
68#[derive(Clone)]
David Brown7ddec0b2017-07-06 10:47:35 -060069pub struct SimFlash {
David Brownde7729e2017-01-09 10:41:35 -070070 data: Vec<u8>,
Marti Bolivar51d36dd2017-05-17 17:39:46 -040071 write_safe: Vec<bool>,
David Brownde7729e2017-01-09 10:41:35 -070072 sectors: Vec<usize>,
Fabio Utzigf5c895e2017-11-23 19:57:17 -020073 bad_region: Vec<(usize, usize, f32)>,
David Brown562a7a02017-01-23 11:19:03 -070074 // Alignment required for writes.
75 align: usize,
Fabio Utzigfa137fc2017-11-23 20:01:02 -020076 verify_writes: bool,
Fabio Utzigea0290b2018-08-09 14:23:01 -030077 erased_val: u8,
David Brownde7729e2017-01-09 10:41:35 -070078}
79
David Brown7ddec0b2017-07-06 10:47:35 -060080impl SimFlash {
David Brownde7729e2017-01-09 10:41:35 -070081 /// Given a sector size map, construct a flash device for that.
Fabio Utzigea0290b2018-08-09 14:23:01 -030082 pub fn new(sectors: Vec<usize>, align: usize, erased_val: u8) -> SimFlash {
David Brown562a7a02017-01-23 11:19:03 -070083 // Verify that the alignment is a positive power of two.
84 assert!(align > 0);
85 assert!(align & (align - 1) == 0);
86
David Brownde7729e2017-01-09 10:41:35 -070087 let total = sectors.iter().sum();
David Brown7ddec0b2017-07-06 10:47:35 -060088 SimFlash {
Fabio Utzigea0290b2018-08-09 14:23:01 -030089 data: vec![erased_val; total],
Marti Bolivar51d36dd2017-05-17 17:39:46 -040090 write_safe: vec![true; total],
David Brownde7729e2017-01-09 10:41:35 -070091 sectors: sectors,
Fabio Utzigf5c895e2017-11-23 19:57:17 -020092 bad_region: Vec::new(),
David Brown562a7a02017-01-23 11:19:03 -070093 align: align,
Fabio Utzigfa137fc2017-11-23 20:01:02 -020094 verify_writes: true,
Fabio Utzigea0290b2018-08-09 14:23:01 -030095 erased_val: erased_val,
David Brownde7729e2017-01-09 10:41:35 -070096 }
97 }
98
David Brown7ddec0b2017-07-06 10:47:35 -060099 #[allow(dead_code)]
100 pub fn dump(&self) {
101 self.data.dump();
102 }
103
104 /// Dump this image to the given file.
105 #[allow(dead_code)]
106 pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
107 let mut fd = File::create(path).chain_err(|| "Unable to write image file")?;
108 fd.write_all(&self.data).chain_err(|| "Unable to write to image file")?;
109 Ok(())
110 }
111
112 // Scan the sector map, and return the base and offset within a sector for this given byte.
113 // Returns None if the value is outside of the device.
114 fn get_sector(&self, offset: usize) -> Option<(usize, usize)> {
115 let mut offset = offset;
116 for (sector, &size) in self.sectors.iter().enumerate() {
117 if offset < size {
118 return Some((sector, offset));
119 }
120 offset -= size;
121 }
122 return None;
123 }
124
125}
126
127impl Flash for SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700128 /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be
129 /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise
130 /// return an error.
David Brown7ddec0b2017-07-06 10:47:35 -0600131 fn erase(&mut self, offset: usize, len: usize) -> Result<()> {
David Brownde7729e2017-01-09 10:41:35 -0700132 let (_start, slen) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?;
133 let (end, elen) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?;
134
135 if slen != 0 {
136 bail!(ebounds("offset not at start of sector"));
137 }
138 if elen != self.sectors[end] - 1 {
139 bail!(ebounds("end not at start of sector"));
140 }
141
142 for x in &mut self.data[offset .. offset + len] {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300143 *x = self.erased_val;
David Brownde7729e2017-01-09 10:41:35 -0700144 }
145
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400146 for x in &mut self.write_safe[offset .. offset + len] {
147 *x = true;
148 }
149
David Brownde7729e2017-01-09 10:41:35 -0700150 Ok(())
151 }
152
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400153 /// We restrict to only allowing writes of values that are:
154 ///
155 /// 1. being written to for the first time
156 /// 2. being written to after being erased
157 ///
158 /// This emulates a flash device which starts out erased, with the
159 /// added restriction that repeated writes to the same location
160 /// are disallowed, even if they would be safe to do.
David Brown7ddec0b2017-07-06 10:47:35 -0600161 fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> {
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200162 for &(off, len, rate) in &self.bad_region {
163 if offset >= off && (offset + payload.len()) <= (off + len) {
164 let mut rng = rand::thread_rng();
165 let between = Range::new(0., 1.);
166 if between.ind_sample(&mut rng) < rate {
167 bail!(esimulatedwrite(
168 format!("Ignoring write to {:#x}-{:#x}", off, off + len)));
169 }
170 }
171 }
172
David Brownde7729e2017-01-09 10:41:35 -0700173 if offset + payload.len() > self.data.len() {
David Brownf253fa82017-01-23 15:43:47 -0700174 panic!("Write outside of device");
David Brownde7729e2017-01-09 10:41:35 -0700175 }
176
David Brown562a7a02017-01-23 11:19:03 -0700177 // Verify the alignment (which must be a power of two).
178 if offset & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700179 panic!("Misaligned write address");
David Brown562a7a02017-01-23 11:19:03 -0700180 }
181
182 if payload.len() & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700183 panic!("Write length not multiple of alignment");
David Brown562a7a02017-01-23 11:19:03 -0700184 }
185
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400186 for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() {
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200187 if self.verify_writes && !(*x) {
Fabio Utzig65935d72017-07-17 15:34:36 -0300188 panic!("Write to unerased location at 0x{:x}", offset + i);
Fabio Utzig19b2c1a2017-04-20 07:32:44 -0300189 }
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400190 *x = false;
David Brownde7729e2017-01-09 10:41:35 -0700191 }
192
David Brown59ae5222017-12-06 11:45:15 -0700193 let sub = &mut self.data[offset .. offset + payload.len()];
David Brownde7729e2017-01-09 10:41:35 -0700194 sub.copy_from_slice(payload);
195 Ok(())
196 }
197
198 /// Read is simple.
David Brown7ddec0b2017-07-06 10:47:35 -0600199 fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> {
David Brownde7729e2017-01-09 10:41:35 -0700200 if offset + data.len() > self.data.len() {
201 bail!(ebounds("Read outside of device"));
202 }
203
204 let sub = &self.data[offset .. offset + data.len()];
205 data.copy_from_slice(sub);
206 Ok(())
207 }
208
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200209 /// Adds a new flash bad region. Writes to this area fail with a chance
210 /// given by `rate`.
211 fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()> {
212 if rate < 0.0 || rate > 1.0 {
213 bail!(ebounds("Invalid rate"));
214 }
215
216 info!("Adding new bad region {:#x}-{:#x}", offset, offset + len);
217 self.bad_region.push((offset, len, rate));
218
219 Ok(())
220 }
221
222 fn reset_bad_regions(&mut self) {
223 self.bad_region.clear();
224 }
225
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200226 fn set_verify_writes(&mut self, enable: bool) {
227 self.verify_writes = enable;
228 }
229
David Brownde7729e2017-01-09 10:41:35 -0700230 /// An iterator over each sector in the device.
David Brown7ddec0b2017-07-06 10:47:35 -0600231 fn sector_iter(&self) -> SectorIter {
David Brownde7729e2017-01-09 10:41:35 -0700232 SectorIter {
233 iter: self.sectors.iter().enumerate(),
234 base: 0,
235 }
236 }
237
David Brown7ddec0b2017-07-06 10:47:35 -0600238 fn device_size(&self) -> usize {
David Brownde7729e2017-01-09 10:41:35 -0700239 self.data.len()
240 }
Fabio Utzigea0290b2018-08-09 14:23:01 -0300241
242 fn erased_val(&self) -> u8 {
243 self.erased_val
244 }
David Brownde7729e2017-01-09 10:41:35 -0700245}
246
247/// It is possible to iterate over the sectors in the device, each element returning this.
David Brown3f687dc2017-11-06 13:41:18 -0700248#[derive(Debug, Clone)]
David Brownde7729e2017-01-09 10:41:35 -0700249pub struct Sector {
250 /// Which sector is this, starting from 0.
251 pub num: usize,
252 /// The offset, in bytes, of the start of this sector.
253 pub base: usize,
254 /// The length, in bytes, of this sector.
255 pub size: usize,
256}
257
258pub struct SectorIter<'a> {
259 iter: Enumerate<slice::Iter<'a, usize>>,
260 base: usize,
261}
262
263impl<'a> Iterator for SectorIter<'a> {
264 type Item = Sector;
265
266 fn next(&mut self) -> Option<Sector> {
267 match self.iter.next() {
268 None => None,
269 Some((num, &size)) => {
270 let base = self.base;
271 self.base += size;
272 Some(Sector {
273 num: num,
274 base: base,
275 size: size,
276 })
277 }
278 }
279 }
280}
281
282#[cfg(test)]
283mod test {
David Brown7ddec0b2017-07-06 10:47:35 -0600284 use super::{Flash, SimFlash, Error, ErrorKind, Result, Sector};
David Brownde7729e2017-01-09 10:41:35 -0700285
286 #[test]
287 fn test_flash() {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300288 for &erased_val in &[0, 0xff] {
289 // NXP-style, uniform sectors.
290 let mut f1 = SimFlash::new(vec![4096usize; 256], 1, erased_val);
291 test_device(&mut f1, erased_val);
David Brownde7729e2017-01-09 10:41:35 -0700292
Fabio Utzigea0290b2018-08-09 14:23:01 -0300293 // STM style, non-uniform sectors.
294 let mut f2 = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
295 128 * 1024, 128 * 1024, 128 * 1024], 1, erased_val);
296 test_device(&mut f2, erased_val);
297 }
David Brownde7729e2017-01-09 10:41:35 -0700298 }
299
Fabio Utzigea0290b2018-08-09 14:23:01 -0300300 fn test_device(flash: &mut Flash, erased_val: u8) {
David Brownde7729e2017-01-09 10:41:35 -0700301 let sectors: Vec<Sector> = flash.sector_iter().collect();
302
303 flash.erase(0, sectors[0].size).unwrap();
304 let flash_size = flash.device_size();
305 flash.erase(0, flash_size).unwrap();
306 assert!(flash.erase(0, sectors[0].size - 1).is_bounds());
307
308 // Verify that write and erase do something.
Fabio Utzigea0290b2018-08-09 14:23:01 -0300309 flash.write(0, &[0x55]).unwrap();
310 let mut buf = [0xAA; 4];
David Brownde7729e2017-01-09 10:41:35 -0700311 flash.read(0, &mut buf).unwrap();
Fabio Utzigea0290b2018-08-09 14:23:01 -0300312 assert_eq!(buf, [0x55, erased_val, erased_val, erased_val]);
David Brownde7729e2017-01-09 10:41:35 -0700313
314 flash.erase(0, sectors[0].size).unwrap();
315 flash.read(0, &mut buf).unwrap();
Fabio Utzigea0290b2018-08-09 14:23:01 -0300316 assert_eq!(buf, [erased_val; 4]);
David Brownde7729e2017-01-09 10:41:35 -0700317
318 // Program the first and last byte of each sector, verify that has been done, and then
319 // erase to verify the erase boundaries.
320 for sector in &sectors {
321 let byte = [(sector.num & 127) as u8];
322 flash.write(sector.base, &byte).unwrap();
323 flash.write(sector.base + sector.size - 1, &byte).unwrap();
324 }
325
326 // Verify the above
327 let mut buf = Vec::new();
328 for sector in &sectors {
329 let byte = (sector.num & 127) as u8;
330 buf.resize(sector.size, 0);
331 flash.read(sector.base, &mut buf).unwrap();
332 assert_eq!(buf.first(), Some(&byte));
333 assert_eq!(buf.last(), Some(&byte));
Fabio Utzigea0290b2018-08-09 14:23:01 -0300334 assert!(buf[1..buf.len()-1].iter().all(|&x| x == erased_val));
David Brownde7729e2017-01-09 10:41:35 -0700335 }
336 }
337
338 // Helper checks for the result type.
339 trait EChecker {
340 fn is_bounds(&self) -> bool;
341 }
342
343 impl<T> EChecker for Result<T> {
344
345 fn is_bounds(&self) -> bool {
346 match *self {
347 Err(Error(ErrorKind::OutOfBounds(_), _)) => true,
348 _ => false,
349 }
350 }
351 }
352}