blob: c628ec19d37a2a158b267b77f150d2dc4dfa2586 [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
Fabio Utzig269d2862018-10-24 17:45:38 -030049 fn align(&self) -> usize;
Fabio Utzigea0290b2018-08-09 14:23:01 -030050 fn erased_val(&self) -> u8;
David Brown7ddec0b2017-07-06 10:47:35 -060051}
52
David Brownde7729e2017-01-09 10:41:35 -070053fn ebounds<T: AsRef<str>>(message: T) -> ErrorKind {
54 ErrorKind::OutOfBounds(message.as_ref().to_owned())
55}
56
Fabio Utzig65935d72017-07-17 15:34:36 -030057#[allow(dead_code)]
David Brownde7729e2017-01-09 10:41:35 -070058fn ewrite<T: AsRef<str>>(message: T) -> ErrorKind {
59 ErrorKind::Write(message.as_ref().to_owned())
60}
61
Fabio Utzigf5c895e2017-11-23 19:57:17 -020062#[allow(dead_code)]
63fn esimulatedwrite<T: AsRef<str>>(message: T) -> ErrorKind {
64 ErrorKind::SimulatedFail(message.as_ref().to_owned())
65}
66
David Brownde7729e2017-01-09 10:41:35 -070067/// An emulated flash device. It is represented as a block of bytes, and a list of the sector
68/// mapings.
69#[derive(Clone)]
David Brown7ddec0b2017-07-06 10:47:35 -060070pub struct SimFlash {
David Brownde7729e2017-01-09 10:41:35 -070071 data: Vec<u8>,
Marti Bolivar51d36dd2017-05-17 17:39:46 -040072 write_safe: Vec<bool>,
David Brownde7729e2017-01-09 10:41:35 -070073 sectors: Vec<usize>,
Fabio Utzigf5c895e2017-11-23 19:57:17 -020074 bad_region: Vec<(usize, usize, f32)>,
David Brown562a7a02017-01-23 11:19:03 -070075 // Alignment required for writes.
76 align: usize,
Fabio Utzigfa137fc2017-11-23 20:01:02 -020077 verify_writes: bool,
Fabio Utzigea0290b2018-08-09 14:23:01 -030078 erased_val: u8,
David Brownde7729e2017-01-09 10:41:35 -070079}
80
David Brown7ddec0b2017-07-06 10:47:35 -060081impl SimFlash {
David Brownde7729e2017-01-09 10:41:35 -070082 /// Given a sector size map, construct a flash device for that.
Fabio Utzigea0290b2018-08-09 14:23:01 -030083 pub fn new(sectors: Vec<usize>, align: usize, erased_val: u8) -> SimFlash {
David Brown562a7a02017-01-23 11:19:03 -070084 // Verify that the alignment is a positive power of two.
85 assert!(align > 0);
86 assert!(align & (align - 1) == 0);
87
David Brownde7729e2017-01-09 10:41:35 -070088 let total = sectors.iter().sum();
David Brown7ddec0b2017-07-06 10:47:35 -060089 SimFlash {
Fabio Utzigea0290b2018-08-09 14:23:01 -030090 data: vec![erased_val; total],
Marti Bolivar51d36dd2017-05-17 17:39:46 -040091 write_safe: vec![true; total],
David Brownde7729e2017-01-09 10:41:35 -070092 sectors: sectors,
Fabio Utzigf5c895e2017-11-23 19:57:17 -020093 bad_region: Vec::new(),
David Brown562a7a02017-01-23 11:19:03 -070094 align: align,
Fabio Utzigfa137fc2017-11-23 20:01:02 -020095 verify_writes: true,
Fabio Utzigea0290b2018-08-09 14:23:01 -030096 erased_val: erased_val,
David Brownde7729e2017-01-09 10:41:35 -070097 }
98 }
99
David Brown7ddec0b2017-07-06 10:47:35 -0600100 #[allow(dead_code)]
101 pub fn dump(&self) {
102 self.data.dump();
103 }
104
105 /// Dump this image to the given file.
106 #[allow(dead_code)]
107 pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
108 let mut fd = File::create(path).chain_err(|| "Unable to write image file")?;
109 fd.write_all(&self.data).chain_err(|| "Unable to write to image file")?;
110 Ok(())
111 }
112
113 // Scan the sector map, and return the base and offset within a sector for this given byte.
114 // Returns None if the value is outside of the device.
115 fn get_sector(&self, offset: usize) -> Option<(usize, usize)> {
116 let mut offset = offset;
117 for (sector, &size) in self.sectors.iter().enumerate() {
118 if offset < size {
119 return Some((sector, offset));
120 }
121 offset -= size;
122 }
123 return None;
124 }
125
126}
127
128impl Flash for SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700129 /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be
130 /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise
131 /// return an error.
David Brown7ddec0b2017-07-06 10:47:35 -0600132 fn erase(&mut self, offset: usize, len: usize) -> Result<()> {
David Brownde7729e2017-01-09 10:41:35 -0700133 let (_start, slen) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?;
134 let (end, elen) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?;
135
136 if slen != 0 {
137 bail!(ebounds("offset not at start of sector"));
138 }
139 if elen != self.sectors[end] - 1 {
140 bail!(ebounds("end not at start of sector"));
141 }
142
143 for x in &mut self.data[offset .. offset + len] {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300144 *x = self.erased_val;
David Brownde7729e2017-01-09 10:41:35 -0700145 }
146
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400147 for x in &mut self.write_safe[offset .. offset + len] {
148 *x = true;
149 }
150
David Brownde7729e2017-01-09 10:41:35 -0700151 Ok(())
152 }
153
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400154 /// We restrict to only allowing writes of values that are:
155 ///
156 /// 1. being written to for the first time
157 /// 2. being written to after being erased
158 ///
159 /// This emulates a flash device which starts out erased, with the
160 /// added restriction that repeated writes to the same location
161 /// are disallowed, even if they would be safe to do.
David Brown7ddec0b2017-07-06 10:47:35 -0600162 fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> {
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200163 for &(off, len, rate) in &self.bad_region {
164 if offset >= off && (offset + payload.len()) <= (off + len) {
165 let mut rng = rand::thread_rng();
166 let between = Range::new(0., 1.);
167 if between.ind_sample(&mut rng) < rate {
168 bail!(esimulatedwrite(
169 format!("Ignoring write to {:#x}-{:#x}", off, off + len)));
170 }
171 }
172 }
173
David Brownde7729e2017-01-09 10:41:35 -0700174 if offset + payload.len() > self.data.len() {
David Brownf253fa82017-01-23 15:43:47 -0700175 panic!("Write outside of device");
David Brownde7729e2017-01-09 10:41:35 -0700176 }
177
David Brown562a7a02017-01-23 11:19:03 -0700178 // Verify the alignment (which must be a power of two).
179 if offset & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700180 panic!("Misaligned write address");
David Brown562a7a02017-01-23 11:19:03 -0700181 }
182
183 if payload.len() & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700184 panic!("Write length not multiple of alignment");
David Brown562a7a02017-01-23 11:19:03 -0700185 }
186
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400187 for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() {
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200188 if self.verify_writes && !(*x) {
Fabio Utzig65935d72017-07-17 15:34:36 -0300189 panic!("Write to unerased location at 0x{:x}", offset + i);
Fabio Utzig19b2c1a2017-04-20 07:32:44 -0300190 }
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400191 *x = false;
David Brownde7729e2017-01-09 10:41:35 -0700192 }
193
David Brown59ae5222017-12-06 11:45:15 -0700194 let sub = &mut self.data[offset .. offset + payload.len()];
David Brownde7729e2017-01-09 10:41:35 -0700195 sub.copy_from_slice(payload);
196 Ok(())
197 }
198
199 /// Read is simple.
David Brown7ddec0b2017-07-06 10:47:35 -0600200 fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> {
David Brownde7729e2017-01-09 10:41:35 -0700201 if offset + data.len() > self.data.len() {
202 bail!(ebounds("Read outside of device"));
203 }
204
205 let sub = &self.data[offset .. offset + data.len()];
206 data.copy_from_slice(sub);
207 Ok(())
208 }
209
Fabio Utzigf5c895e2017-11-23 19:57:17 -0200210 /// Adds a new flash bad region. Writes to this area fail with a chance
211 /// given by `rate`.
212 fn add_bad_region(&mut self, offset: usize, len: usize, rate: f32) -> Result<()> {
213 if rate < 0.0 || rate > 1.0 {
214 bail!(ebounds("Invalid rate"));
215 }
216
217 info!("Adding new bad region {:#x}-{:#x}", offset, offset + len);
218 self.bad_region.push((offset, len, rate));
219
220 Ok(())
221 }
222
223 fn reset_bad_regions(&mut self) {
224 self.bad_region.clear();
225 }
226
Fabio Utzigfa137fc2017-11-23 20:01:02 -0200227 fn set_verify_writes(&mut self, enable: bool) {
228 self.verify_writes = enable;
229 }
230
David Brownde7729e2017-01-09 10:41:35 -0700231 /// An iterator over each sector in the device.
David Brown7ddec0b2017-07-06 10:47:35 -0600232 fn sector_iter(&self) -> SectorIter {
David Brownde7729e2017-01-09 10:41:35 -0700233 SectorIter {
234 iter: self.sectors.iter().enumerate(),
235 base: 0,
236 }
237 }
238
David Brown7ddec0b2017-07-06 10:47:35 -0600239 fn device_size(&self) -> usize {
David Brownde7729e2017-01-09 10:41:35 -0700240 self.data.len()
241 }
Fabio Utzigea0290b2018-08-09 14:23:01 -0300242
Fabio Utzig269d2862018-10-24 17:45:38 -0300243 fn align(&self) -> usize {
244 self.align
245 }
246
Fabio Utzigea0290b2018-08-09 14:23:01 -0300247 fn erased_val(&self) -> u8 {
248 self.erased_val
249 }
David Brownde7729e2017-01-09 10:41:35 -0700250}
251
252/// It is possible to iterate over the sectors in the device, each element returning this.
David Brown3f687dc2017-11-06 13:41:18 -0700253#[derive(Debug, Clone)]
David Brownde7729e2017-01-09 10:41:35 -0700254pub struct Sector {
255 /// Which sector is this, starting from 0.
256 pub num: usize,
257 /// The offset, in bytes, of the start of this sector.
258 pub base: usize,
259 /// The length, in bytes, of this sector.
260 pub size: usize,
261}
262
263pub struct SectorIter<'a> {
264 iter: Enumerate<slice::Iter<'a, usize>>,
265 base: usize,
266}
267
268impl<'a> Iterator for SectorIter<'a> {
269 type Item = Sector;
270
271 fn next(&mut self) -> Option<Sector> {
272 match self.iter.next() {
273 None => None,
274 Some((num, &size)) => {
275 let base = self.base;
276 self.base += size;
277 Some(Sector {
278 num: num,
279 base: base,
280 size: size,
281 })
282 }
283 }
284 }
285}
286
287#[cfg(test)]
288mod test {
David Brown7ddec0b2017-07-06 10:47:35 -0600289 use super::{Flash, SimFlash, Error, ErrorKind, Result, Sector};
David Brownde7729e2017-01-09 10:41:35 -0700290
291 #[test]
292 fn test_flash() {
Fabio Utzigea0290b2018-08-09 14:23:01 -0300293 for &erased_val in &[0, 0xff] {
294 // NXP-style, uniform sectors.
295 let mut f1 = SimFlash::new(vec![4096usize; 256], 1, erased_val);
296 test_device(&mut f1, erased_val);
David Brownde7729e2017-01-09 10:41:35 -0700297
Fabio Utzigea0290b2018-08-09 14:23:01 -0300298 // STM style, non-uniform sectors.
299 let mut f2 = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
300 128 * 1024, 128 * 1024, 128 * 1024], 1, erased_val);
301 test_device(&mut f2, erased_val);
302 }
David Brownde7729e2017-01-09 10:41:35 -0700303 }
304
Fabio Utzigea0290b2018-08-09 14:23:01 -0300305 fn test_device(flash: &mut Flash, erased_val: u8) {
David Brownde7729e2017-01-09 10:41:35 -0700306 let sectors: Vec<Sector> = flash.sector_iter().collect();
307
308 flash.erase(0, sectors[0].size).unwrap();
309 let flash_size = flash.device_size();
310 flash.erase(0, flash_size).unwrap();
311 assert!(flash.erase(0, sectors[0].size - 1).is_bounds());
312
313 // Verify that write and erase do something.
Fabio Utzigea0290b2018-08-09 14:23:01 -0300314 flash.write(0, &[0x55]).unwrap();
315 let mut buf = [0xAA; 4];
David Brownde7729e2017-01-09 10:41:35 -0700316 flash.read(0, &mut buf).unwrap();
Fabio Utzigea0290b2018-08-09 14:23:01 -0300317 assert_eq!(buf, [0x55, erased_val, erased_val, erased_val]);
David Brownde7729e2017-01-09 10:41:35 -0700318
319 flash.erase(0, sectors[0].size).unwrap();
320 flash.read(0, &mut buf).unwrap();
Fabio Utzigea0290b2018-08-09 14:23:01 -0300321 assert_eq!(buf, [erased_val; 4]);
David Brownde7729e2017-01-09 10:41:35 -0700322
323 // Program the first and last byte of each sector, verify that has been done, and then
324 // erase to verify the erase boundaries.
325 for sector in &sectors {
326 let byte = [(sector.num & 127) as u8];
327 flash.write(sector.base, &byte).unwrap();
328 flash.write(sector.base + sector.size - 1, &byte).unwrap();
329 }
330
331 // Verify the above
332 let mut buf = Vec::new();
333 for sector in &sectors {
334 let byte = (sector.num & 127) as u8;
335 buf.resize(sector.size, 0);
336 flash.read(sector.base, &mut buf).unwrap();
337 assert_eq!(buf.first(), Some(&byte));
338 assert_eq!(buf.last(), Some(&byte));
Fabio Utzigea0290b2018-08-09 14:23:01 -0300339 assert!(buf[1..buf.len()-1].iter().all(|&x| x == erased_val));
David Brownde7729e2017-01-09 10:41:35 -0700340 }
341 }
342
343 // Helper checks for the result type.
344 trait EChecker {
345 fn is_bounds(&self) -> bool;
346 }
347
348 impl<T> EChecker for Result<T> {
349
350 fn is_bounds(&self) -> bool {
351 match *self {
352 Err(Error(ErrorKind::OutOfBounds(_), _)) => true,
353 _ => false,
354 }
355 }
356 }
357}