David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 1 | //! 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 | |
David Brown | 2cbc470 | 2017-07-06 14:18:58 -0600 | [diff] [blame^] | 6 | #[macro_use] extern crate error_chain; |
| 7 | mod pdump; |
| 8 | |
David Brown | 163ab23 | 2017-01-23 15:48:35 -0700 | [diff] [blame] | 9 | use std::fs::File; |
| 10 | use std::io::Write; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 11 | use std::iter::Enumerate; |
David Brown | 163ab23 | 2017-01-23 15:48:35 -0700 | [diff] [blame] | 12 | use std::path::Path; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 13 | use std::slice; |
| 14 | use pdump::HexDump; |
| 15 | |
| 16 | error_chain! { |
| 17 | errors { |
| 18 | OutOfBounds(t: String) { |
| 19 | description("Offset is out of bounds") |
| 20 | display("Offset out of bounds: {}", t) |
| 21 | } |
| 22 | Write(t: String) { |
| 23 | description("Invalid write") |
| 24 | display("Invalid write: {}", t) |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 29 | pub trait Flash { |
| 30 | fn erase(&mut self, offset: usize, len: usize) -> Result<()>; |
| 31 | fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()>; |
| 32 | fn read(&self, offset: usize, data: &mut [u8]) -> Result<()>; |
| 33 | |
| 34 | fn sector_iter(&self) -> SectorIter; |
| 35 | fn device_size(&self) -> usize; |
| 36 | } |
| 37 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 38 | fn ebounds<T: AsRef<str>>(message: T) -> ErrorKind { |
| 39 | ErrorKind::OutOfBounds(message.as_ref().to_owned()) |
| 40 | } |
| 41 | |
| 42 | fn ewrite<T: AsRef<str>>(message: T) -> ErrorKind { |
| 43 | ErrorKind::Write(message.as_ref().to_owned()) |
| 44 | } |
| 45 | |
| 46 | /// An emulated flash device. It is represented as a block of bytes, and a list of the sector |
| 47 | /// mapings. |
| 48 | #[derive(Clone)] |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 49 | pub struct SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 50 | data: Vec<u8>, |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 51 | write_safe: Vec<bool>, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 52 | sectors: Vec<usize>, |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 53 | // Alignment required for writes. |
| 54 | align: usize, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 55 | } |
| 56 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 57 | impl SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 58 | /// Given a sector size map, construct a flash device for that. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 59 | pub fn new(sectors: Vec<usize>, align: usize) -> SimFlash { |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 60 | // Verify that the alignment is a positive power of two. |
| 61 | assert!(align > 0); |
| 62 | assert!(align & (align - 1) == 0); |
| 63 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 64 | let total = sectors.iter().sum(); |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 65 | SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 66 | data: vec![0xffu8; total], |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 67 | write_safe: vec![true; total], |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 68 | sectors: sectors, |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 69 | align: align, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 70 | } |
| 71 | } |
| 72 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 73 | #[allow(dead_code)] |
| 74 | pub fn dump(&self) { |
| 75 | self.data.dump(); |
| 76 | } |
| 77 | |
| 78 | /// Dump this image to the given file. |
| 79 | #[allow(dead_code)] |
| 80 | pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> { |
| 81 | let mut fd = File::create(path).chain_err(|| "Unable to write image file")?; |
| 82 | fd.write_all(&self.data).chain_err(|| "Unable to write to image file")?; |
| 83 | Ok(()) |
| 84 | } |
| 85 | |
| 86 | // Scan the sector map, and return the base and offset within a sector for this given byte. |
| 87 | // Returns None if the value is outside of the device. |
| 88 | fn get_sector(&self, offset: usize) -> Option<(usize, usize)> { |
| 89 | let mut offset = offset; |
| 90 | for (sector, &size) in self.sectors.iter().enumerate() { |
| 91 | if offset < size { |
| 92 | return Some((sector, offset)); |
| 93 | } |
| 94 | offset -= size; |
| 95 | } |
| 96 | return None; |
| 97 | } |
| 98 | |
| 99 | } |
| 100 | |
| 101 | impl Flash for SimFlash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 102 | /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be |
| 103 | /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise |
| 104 | /// return an error. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 105 | fn erase(&mut self, offset: usize, len: usize) -> Result<()> { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 106 | let (_start, slen) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?; |
| 107 | let (end, elen) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?; |
| 108 | |
| 109 | if slen != 0 { |
| 110 | bail!(ebounds("offset not at start of sector")); |
| 111 | } |
| 112 | if elen != self.sectors[end] - 1 { |
| 113 | bail!(ebounds("end not at start of sector")); |
| 114 | } |
| 115 | |
| 116 | for x in &mut self.data[offset .. offset + len] { |
| 117 | *x = 0xff; |
| 118 | } |
| 119 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 120 | for x in &mut self.write_safe[offset .. offset + len] { |
| 121 | *x = true; |
| 122 | } |
| 123 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 124 | Ok(()) |
| 125 | } |
| 126 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 127 | /// We restrict to only allowing writes of values that are: |
| 128 | /// |
| 129 | /// 1. being written to for the first time |
| 130 | /// 2. being written to after being erased |
| 131 | /// |
| 132 | /// This emulates a flash device which starts out erased, with the |
| 133 | /// added restriction that repeated writes to the same location |
| 134 | /// are disallowed, even if they would be safe to do. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 135 | fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 136 | if offset + payload.len() > self.data.len() { |
David Brown | f253fa8 | 2017-01-23 15:43:47 -0700 | [diff] [blame] | 137 | panic!("Write outside of device"); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 138 | } |
| 139 | |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 140 | // Verify the alignment (which must be a power of two). |
| 141 | if offset & (self.align - 1) != 0 { |
David Brown | f253fa8 | 2017-01-23 15:43:47 -0700 | [diff] [blame] | 142 | panic!("Misaligned write address"); |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 143 | } |
| 144 | |
| 145 | if payload.len() & (self.align - 1) != 0 { |
David Brown | f253fa8 | 2017-01-23 15:43:47 -0700 | [diff] [blame] | 146 | panic!("Write length not multiple of alignment"); |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 147 | } |
| 148 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 149 | for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() { |
| 150 | if !(*x) { |
Fabio Utzig | 40b4aa0 | 2017-06-28 09:16:19 -0300 | [diff] [blame] | 151 | bail!(ewrite(format!("Write to unerased location at 0x{:x}", |
| 152 | offset + i))); |
Fabio Utzig | 19b2c1a | 2017-04-20 07:32:44 -0300 | [diff] [blame] | 153 | } |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 154 | *x = false; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 155 | } |
| 156 | |
Marti Bolivar | 51d36dd | 2017-05-17 17:39:46 -0400 | [diff] [blame] | 157 | let mut sub = &mut self.data[offset .. offset + payload.len()]; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 158 | sub.copy_from_slice(payload); |
| 159 | Ok(()) |
| 160 | } |
| 161 | |
| 162 | /// Read is simple. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 163 | fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 164 | if offset + data.len() > self.data.len() { |
| 165 | bail!(ebounds("Read outside of device")); |
| 166 | } |
| 167 | |
| 168 | let sub = &self.data[offset .. offset + data.len()]; |
| 169 | data.copy_from_slice(sub); |
| 170 | Ok(()) |
| 171 | } |
| 172 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 173 | /// An iterator over each sector in the device. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 174 | fn sector_iter(&self) -> SectorIter { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 175 | SectorIter { |
| 176 | iter: self.sectors.iter().enumerate(), |
| 177 | base: 0, |
| 178 | } |
| 179 | } |
| 180 | |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 181 | fn device_size(&self) -> usize { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 182 | self.data.len() |
| 183 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 184 | } |
| 185 | |
| 186 | /// It is possible to iterate over the sectors in the device, each element returning this. |
| 187 | #[derive(Debug)] |
| 188 | pub struct Sector { |
| 189 | /// Which sector is this, starting from 0. |
| 190 | pub num: usize, |
| 191 | /// The offset, in bytes, of the start of this sector. |
| 192 | pub base: usize, |
| 193 | /// The length, in bytes, of this sector. |
| 194 | pub size: usize, |
| 195 | } |
| 196 | |
| 197 | pub struct SectorIter<'a> { |
| 198 | iter: Enumerate<slice::Iter<'a, usize>>, |
| 199 | base: usize, |
| 200 | } |
| 201 | |
| 202 | impl<'a> Iterator for SectorIter<'a> { |
| 203 | type Item = Sector; |
| 204 | |
| 205 | fn next(&mut self) -> Option<Sector> { |
| 206 | match self.iter.next() { |
| 207 | None => None, |
| 208 | Some((num, &size)) => { |
| 209 | let base = self.base; |
| 210 | self.base += size; |
| 211 | Some(Sector { |
| 212 | num: num, |
| 213 | base: base, |
| 214 | size: size, |
| 215 | }) |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | #[cfg(test)] |
| 222 | mod test { |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 223 | use super::{Flash, SimFlash, Error, ErrorKind, Result, Sector}; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 224 | |
| 225 | #[test] |
| 226 | fn test_flash() { |
| 227 | // NXP-style, uniform sectors. |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 228 | let mut f1 = SimFlash::new(vec![4096usize; 256], 1); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 229 | test_device(&mut f1); |
| 230 | |
| 231 | // STM style, non-uniform sectors |
David Brown | 7ddec0b | 2017-07-06 10:47:35 -0600 | [diff] [blame] | 232 | let mut f2 = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024, |
| 233 | 128 * 1024, 128 * 1024, 128 * 1024], 1); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 234 | test_device(&mut f2); |
| 235 | } |
| 236 | |
| 237 | fn test_device(flash: &mut Flash) { |
| 238 | let sectors: Vec<Sector> = flash.sector_iter().collect(); |
| 239 | |
| 240 | flash.erase(0, sectors[0].size).unwrap(); |
| 241 | let flash_size = flash.device_size(); |
| 242 | flash.erase(0, flash_size).unwrap(); |
| 243 | assert!(flash.erase(0, sectors[0].size - 1).is_bounds()); |
| 244 | |
| 245 | // Verify that write and erase do something. |
| 246 | flash.write(0, &[0]).unwrap(); |
| 247 | let mut buf = [0; 4]; |
| 248 | flash.read(0, &mut buf).unwrap(); |
| 249 | assert_eq!(buf, [0, 0xff, 0xff, 0xff]); |
| 250 | |
| 251 | flash.erase(0, sectors[0].size).unwrap(); |
| 252 | flash.read(0, &mut buf).unwrap(); |
| 253 | assert_eq!(buf, [0xff; 4]); |
| 254 | |
| 255 | // Program the first and last byte of each sector, verify that has been done, and then |
| 256 | // erase to verify the erase boundaries. |
| 257 | for sector in §ors { |
| 258 | let byte = [(sector.num & 127) as u8]; |
| 259 | flash.write(sector.base, &byte).unwrap(); |
| 260 | flash.write(sector.base + sector.size - 1, &byte).unwrap(); |
| 261 | } |
| 262 | |
| 263 | // Verify the above |
| 264 | let mut buf = Vec::new(); |
| 265 | for sector in §ors { |
| 266 | let byte = (sector.num & 127) as u8; |
| 267 | buf.resize(sector.size, 0); |
| 268 | flash.read(sector.base, &mut buf).unwrap(); |
| 269 | assert_eq!(buf.first(), Some(&byte)); |
| 270 | assert_eq!(buf.last(), Some(&byte)); |
| 271 | assert!(buf[1..buf.len()-1].iter().all(|&x| x == 0xff)); |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | // Helper checks for the result type. |
| 276 | trait EChecker { |
| 277 | fn is_bounds(&self) -> bool; |
| 278 | } |
| 279 | |
| 280 | impl<T> EChecker for Result<T> { |
| 281 | |
| 282 | fn is_bounds(&self) -> bool { |
| 283 | match *self { |
| 284 | Err(Error(ErrorKind::OutOfBounds(_), _)) => true, |
| 285 | _ => false, |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | } |