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