aboutsummaryrefslogtreecommitdiff
path: root/embassy-embedded-hal/src/flash
diff options
context:
space:
mode:
authorRasmus Melchior Jacobsen <[email protected]>2023-05-26 21:40:12 +0200
committerRasmus Melchior Jacobsen <[email protected]>2023-05-26 21:40:12 +0200
commit62e799da09e144c9bd2bc3935011913e62c86d16 (patch)
treeab10c8372782bece3a48d43dd9daf00a58a6939c /embassy-embedded-hal/src/flash
parenta8b426d0fe86e6fc3d1813765946cc82e774c3d3 (diff)
Create flash partition for shared flash access
Diffstat (limited to 'embassy-embedded-hal/src/flash')
-rw-r--r--embassy-embedded-hal/src/flash/concat_flash.rs228
-rw-r--r--embassy-embedded-hal/src/flash/mem_flash.rs127
-rw-r--r--embassy-embedded-hal/src/flash/mod.rs9
-rw-r--r--embassy-embedded-hal/src/flash/partition.rs150
4 files changed, 514 insertions, 0 deletions
diff --git a/embassy-embedded-hal/src/flash/concat_flash.rs b/embassy-embedded-hal/src/flash/concat_flash.rs
new file mode 100644
index 000000000..1ea84269c
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/concat_flash.rs
@@ -0,0 +1,228 @@
1use embedded_storage::nor_flash::{ErrorType, NorFlash, NorFlashError, ReadNorFlash};
2#[cfg(feature = "nightly")]
3use embedded_storage_async::nor_flash::{NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash};
4
5/// Convenience helper for concatenating two consecutive flashes into one.
6/// This is especially useful if used with "flash regions", where one may
7/// want to concatenate multiple regions into one larger region.
8pub struct ConcatFlash<First, Second>(First, Second);
9
10impl<First, Second> ConcatFlash<First, Second> {
11 /// Create a new flash that concatenates two consecutive flashes.
12 pub fn new(first: First, second: Second) -> Self {
13 Self(first, second)
14 }
15}
16
17const fn get_read_size(first_read_size: usize, second_read_size: usize) -> usize {
18 if first_read_size != second_read_size {
19 panic!("The read size for the concatenated flashes must be the same");
20 }
21 first_read_size
22}
23
24const fn get_write_size(first_write_size: usize, second_write_size: usize) -> usize {
25 if first_write_size != second_write_size {
26 panic!("The write size for the concatenated flashes must be the same");
27 }
28 first_write_size
29}
30
31const fn get_max_erase_size(first_erase_size: usize, second_erase_size: usize) -> usize {
32 let max_erase_size = if first_erase_size > second_erase_size {
33 first_erase_size
34 } else {
35 second_erase_size
36 };
37 if max_erase_size % first_erase_size != 0 || max_erase_size % second_erase_size != 0 {
38 panic!("The erase sizes for the concatenated flashes must have have a gcd equal to the max erase size");
39 }
40 max_erase_size
41}
42
43impl<First, Second, E> ErrorType for ConcatFlash<First, Second>
44where
45 First: ErrorType<Error = E>,
46 Second: ErrorType<Error = E>,
47 E: NorFlashError,
48{
49 type Error = E;
50}
51
52impl<First, Second, E> ReadNorFlash for ConcatFlash<First, Second>
53where
54 First: ReadNorFlash<Error = E>,
55 Second: ReadNorFlash<Error = E>,
56 E: NorFlashError,
57{
58 const READ_SIZE: usize = get_read_size(First::READ_SIZE, Second::READ_SIZE);
59
60 fn read(&mut self, mut offset: u32, mut bytes: &mut [u8]) -> Result<(), E> {
61 if offset < self.0.capacity() as u32 {
62 let len = core::cmp::min(self.0.capacity() - offset as usize, bytes.len());
63 self.0.read(offset, &mut bytes[..len])?;
64 offset += len as u32;
65 bytes = &mut bytes[len..];
66 }
67
68 if !bytes.is_empty() {
69 self.1.read(offset - self.0.capacity() as u32, bytes)?;
70 }
71
72 Ok(())
73 }
74
75 fn capacity(&self) -> usize {
76 self.0.capacity() + self.1.capacity()
77 }
78}
79
80impl<First, Second, E> NorFlash for ConcatFlash<First, Second>
81where
82 First: NorFlash<Error = E>,
83 Second: NorFlash<Error = E>,
84 E: NorFlashError,
85{
86 const WRITE_SIZE: usize = get_write_size(First::WRITE_SIZE, Second::WRITE_SIZE);
87 const ERASE_SIZE: usize = get_max_erase_size(First::ERASE_SIZE, Second::ERASE_SIZE);
88
89 fn write(&mut self, mut offset: u32, mut bytes: &[u8]) -> Result<(), E> {
90 if offset < self.0.capacity() as u32 {
91 let len = core::cmp::min(self.0.capacity() - offset as usize, bytes.len());
92 self.0.write(offset, &bytes[..len])?;
93 offset += len as u32;
94 bytes = &bytes[len..];
95 }
96
97 if !bytes.is_empty() {
98 self.1.write(offset - self.0.capacity() as u32, bytes)?;
99 }
100
101 Ok(())
102 }
103
104 fn erase(&mut self, mut from: u32, to: u32) -> Result<(), E> {
105 if from < self.0.capacity() as u32 {
106 let to = core::cmp::min(self.0.capacity() as u32, to);
107 self.0.erase(from, to)?;
108 from = self.0.capacity() as u32;
109 }
110
111 if from < to {
112 self.1
113 .erase(from - self.0.capacity() as u32, to - self.0.capacity() as u32)?;
114 }
115
116 Ok(())
117 }
118}
119
120#[cfg(feature = "nightly")]
121impl<First, Second, E> AsyncReadNorFlash for ConcatFlash<First, Second>
122where
123 First: AsyncReadNorFlash<Error = E>,
124 Second: AsyncReadNorFlash<Error = E>,
125 E: NorFlashError,
126{
127 const READ_SIZE: usize = get_read_size(First::READ_SIZE, Second::READ_SIZE);
128
129 async fn read(&mut self, mut offset: u32, mut bytes: &mut [u8]) -> Result<(), E> {
130 if offset < self.0.capacity() as u32 {
131 let len = core::cmp::min(self.0.capacity() - offset as usize, bytes.len());
132 self.0.read(offset, &mut bytes[..len]).await?;
133 offset += len as u32;
134 bytes = &mut bytes[len..];
135 }
136
137 if !bytes.is_empty() {
138 self.1.read(offset - self.0.capacity() as u32, bytes).await?;
139 }
140
141 Ok(())
142 }
143
144 fn capacity(&self) -> usize {
145 self.0.capacity() + self.1.capacity()
146 }
147}
148
149#[cfg(feature = "nightly")]
150impl<First, Second, E> AsyncNorFlash for ConcatFlash<First, Second>
151where
152 First: AsyncNorFlash<Error = E>,
153 Second: AsyncNorFlash<Error = E>,
154 E: NorFlashError,
155{
156 const WRITE_SIZE: usize = get_write_size(First::WRITE_SIZE, Second::WRITE_SIZE);
157 const ERASE_SIZE: usize = get_max_erase_size(First::ERASE_SIZE, Second::ERASE_SIZE);
158
159 async fn write(&mut self, mut offset: u32, mut bytes: &[u8]) -> Result<(), E> {
160 if offset < self.0.capacity() as u32 {
161 let len = core::cmp::min(self.0.capacity() - offset as usize, bytes.len());
162 self.0.write(offset, &bytes[..len]).await?;
163 offset += len as u32;
164 bytes = &bytes[len..];
165 }
166
167 if !bytes.is_empty() {
168 self.1.write(offset - self.0.capacity() as u32, bytes).await?;
169 }
170
171 Ok(())
172 }
173
174 async fn erase(&mut self, mut from: u32, to: u32) -> Result<(), E> {
175 if from < self.0.capacity() as u32 {
176 let to = core::cmp::min(self.0.capacity() as u32, to);
177 self.0.erase(from, to).await?;
178 from = self.0.capacity() as u32;
179 }
180
181 if from < to {
182 self.1
183 .erase(from - self.0.capacity() as u32, to - self.0.capacity() as u32)
184 .await?;
185 }
186
187 Ok(())
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
194
195 use super::ConcatFlash;
196 use crate::flash::mem_flash::MemFlash;
197
198 #[test]
199 fn can_write_and_read_across_flashes() {
200 let first = MemFlash::<64, 16, 4>::default();
201 let second = MemFlash::<64, 64, 4>::default();
202 let mut f = ConcatFlash::new(first, second);
203
204 f.write(60, &[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]).unwrap();
205
206 assert_eq!(&[0x11, 0x22, 0x33, 0x44], &f.0.mem[60..]);
207 assert_eq!(&[0x55, 0x66, 0x77, 0x88], &f.1.mem[0..4]);
208
209 let mut read_buf = [0; 8];
210 f.read(60, &mut read_buf).unwrap();
211
212 assert_eq!(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], &read_buf);
213 }
214
215 #[test]
216 fn can_erase_across_flashes() {
217 let first = MemFlash::<128, 16, 4>::new(0x00);
218 let second = MemFlash::<128, 64, 4>::new(0x00);
219 let mut f = ConcatFlash::new(first, second);
220
221 f.erase(64, 192).unwrap();
222
223 assert_eq!(&[0x00; 64], &f.0.mem[0..64]);
224 assert_eq!(&[0xff; 64], &f.0.mem[64..128]);
225 assert_eq!(&[0xff; 64], &f.1.mem[0..64]);
226 assert_eq!(&[0x00; 64], &f.1.mem[64..128]);
227 }
228}
diff --git a/embassy-embedded-hal/src/flash/mem_flash.rs b/embassy-embedded-hal/src/flash/mem_flash.rs
new file mode 100644
index 000000000..4e10627df
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/mem_flash.rs
@@ -0,0 +1,127 @@
1use alloc::vec::Vec;
2
3use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
4use embedded_storage_async::nor_flash::{NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash};
5
6extern crate alloc;
7
8pub(crate) struct MemFlash<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> {
9 pub mem: [u8; SIZE],
10 pub writes: Vec<(u32, usize)>,
11 pub erases: Vec<(u32, u32)>,
12}
13
14impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE> {
15 #[allow(unused)]
16 pub const fn new(fill: u8) -> Self {
17 Self {
18 mem: [fill; SIZE],
19 writes: Vec::new(),
20 erases: Vec::new(),
21 }
22 }
23
24 fn read(&mut self, offset: u32, bytes: &mut [u8]) {
25 let len = bytes.len();
26 bytes.copy_from_slice(&self.mem[offset as usize..offset as usize + len]);
27 }
28
29 fn write(&mut self, offset: u32, bytes: &[u8]) {
30 self.writes.push((offset, bytes.len()));
31 let offset = offset as usize;
32 assert_eq!(0, bytes.len() % WRITE_SIZE);
33 assert_eq!(0, offset % WRITE_SIZE);
34 assert!(offset + bytes.len() <= SIZE);
35
36 self.mem[offset..offset + bytes.len()].copy_from_slice(bytes);
37 }
38
39 fn erase(&mut self, from: u32, to: u32) {
40 self.erases.push((from, to));
41 let from = from as usize;
42 let to = to as usize;
43 assert_eq!(0, from % ERASE_SIZE);
44 assert_eq!(0, to % ERASE_SIZE);
45 self.mem[from..to].fill(0xff);
46 }
47}
48
49impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> Default
50 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
51{
52 fn default() -> Self {
53 Self::new(0xff)
54 }
55}
56
57impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ErrorType
58 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
59{
60 type Error = core::convert::Infallible;
61}
62
63impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ReadNorFlash
64 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
65{
66 const READ_SIZE: usize = 1;
67
68 fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
69 self.read(offset, bytes);
70 Ok(())
71 }
72
73 fn capacity(&self) -> usize {
74 SIZE
75 }
76}
77
78impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> NorFlash
79 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
80{
81 const WRITE_SIZE: usize = WRITE_SIZE;
82 const ERASE_SIZE: usize = ERASE_SIZE;
83
84 fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
85 self.write(offset, bytes);
86 Ok(())
87 }
88
89 fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
90 self.erase(from, to);
91 Ok(())
92 }
93}
94
95#[cfg(feature = "nightly")]
96impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncReadNorFlash
97 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
98{
99 const READ_SIZE: usize = 1;
100
101 async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
102 self.read(offset, bytes);
103 Ok(())
104 }
105
106 fn capacity(&self) -> usize {
107 SIZE
108 }
109}
110
111#[cfg(feature = "nightly")]
112impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncNorFlash
113 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
114{
115 const WRITE_SIZE: usize = WRITE_SIZE;
116 const ERASE_SIZE: usize = ERASE_SIZE;
117
118 async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
119 self.write(offset, bytes);
120 Ok(())
121 }
122
123 async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
124 self.erase(from, to);
125 Ok(())
126 }
127}
diff --git a/embassy-embedded-hal/src/flash/mod.rs b/embassy-embedded-hal/src/flash/mod.rs
new file mode 100644
index 000000000..c80dd6aac
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/mod.rs
@@ -0,0 +1,9 @@
1//! Utilities related to flash.
2
3mod concat_flash;
4#[cfg(test)]
5pub(crate) mod mem_flash;
6mod partition;
7
8pub use concat_flash::ConcatFlash;
9pub use partition::Partition;
diff --git a/embassy-embedded-hal/src/flash/partition.rs b/embassy-embedded-hal/src/flash/partition.rs
new file mode 100644
index 000000000..084425e95
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/partition.rs
@@ -0,0 +1,150 @@
1use embassy_sync::blocking_mutex::raw::RawMutex;
2use embassy_sync::mutex::Mutex;
3use embedded_storage::nor_flash::{ErrorType, NorFlashError, NorFlashErrorKind};
4#[cfg(feature = "nightly")]
5use embedded_storage_async::nor_flash::{NorFlash, ReadNorFlash};
6
7/// A logical partition of an underlying shared flash
8///
9/// A partition holds an offset and a size of the flash,
10/// and is restricted to operate with that range.
11/// There is no guarantee that muliple partitions on the same flash
12/// operate on mutually exclusive ranges - such a separation is up to
13/// the user to guarantee.
14pub struct Partition<'a, M: RawMutex, T> {
15 flash: &'a Mutex<M, T>,
16 offset: u32,
17 size: u32,
18}
19
20#[derive(Debug)]
21#[cfg_attr(feature = "defmt", derive(defmt::Format))]
22pub enum Error<T> {
23 Partition,
24 OutOfBounds,
25 Flash(T),
26}
27
28impl<'a, M: RawMutex, T> Partition<'a, M, T> {
29 /// Create a new partition
30 pub const fn new(flash: &'a Mutex<M, T>, offset: u32, size: u32) -> Self {
31 Self { flash, offset, size }
32 }
33}
34
35impl<T: NorFlashError> NorFlashError for Error<T> {
36 fn kind(&self) -> NorFlashErrorKind {
37 match self {
38 Error::Partition => NorFlashErrorKind::Other,
39 Error::OutOfBounds => NorFlashErrorKind::OutOfBounds,
40 Error::Flash(f) => f.kind(),
41 }
42 }
43}
44
45impl<M: RawMutex, T: ErrorType> ErrorType for Partition<'_, M, T> {
46 type Error = Error<T::Error>;
47}
48
49#[cfg(feature = "nightly")]
50impl<M: RawMutex, T: ReadNorFlash> ReadNorFlash for Partition<'_, M, T> {
51 const READ_SIZE: usize = T::READ_SIZE;
52
53 async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
54 if self.offset % T::READ_SIZE as u32 != 0 || self.size % T::READ_SIZE as u32 != 0 {
55 return Err(Error::Partition);
56 }
57 if offset + bytes.len() as u32 > self.size {
58 return Err(Error::OutOfBounds);
59 }
60
61 let mut flash = self.flash.lock().await;
62 flash.read(self.offset + offset, bytes).await.map_err(Error::Flash)
63 }
64
65 fn capacity(&self) -> usize {
66 self.size as usize
67 }
68}
69
70#[cfg(feature = "nightly")]
71impl<M: RawMutex, T: NorFlash> NorFlash for Partition<'_, M, T> {
72 const WRITE_SIZE: usize = T::WRITE_SIZE;
73 const ERASE_SIZE: usize = T::ERASE_SIZE;
74
75 async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
76 if self.offset % T::WRITE_SIZE as u32 != 0 || self.size % T::WRITE_SIZE as u32 != 0 {
77 return Err(Error::Partition);
78 }
79 if offset + bytes.len() as u32 > self.size {
80 return Err(Error::OutOfBounds);
81 }
82
83 let mut flash = self.flash.lock().await;
84 flash.write(self.offset + offset, bytes).await.map_err(Error::Flash)
85 }
86
87 async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
88 if self.offset % T::ERASE_SIZE as u32 != 0 || self.size % T::ERASE_SIZE as u32 != 0 {
89 return Err(Error::Partition);
90 }
91 if to > self.size {
92 return Err(Error::OutOfBounds);
93 }
94
95 let mut flash = self.flash.lock().await;
96 flash
97 .erase(self.offset + from, self.offset + to)
98 .await
99 .map_err(Error::Flash)
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use embassy_sync::blocking_mutex::raw::NoopRawMutex;
106
107 use super::*;
108 use crate::flash::mem_flash::MemFlash;
109
110 #[futures_test::test]
111 async fn can_read() {
112 let mut flash = MemFlash::<1024, 128, 4>::default();
113 flash.mem[12..20].fill(0xAA);
114
115 let flash = Mutex::<NoopRawMutex, _>::new(flash);
116 let mut partition = Partition::new(&flash, 8, 12);
117
118 let mut read_buf = [0; 8];
119 partition.read(4, &mut read_buf).await.unwrap();
120
121 assert!(read_buf.iter().position(|&x| x != 0xAA).is_none());
122 }
123
124 #[futures_test::test]
125 async fn can_write() {
126 let flash = MemFlash::<1024, 128, 4>::default();
127
128 let flash = Mutex::<NoopRawMutex, _>::new(flash);
129 let mut partition = Partition::new(&flash, 8, 12);
130
131 let write_buf = [0xAA; 8];
132 partition.write(4, &write_buf).await.unwrap();
133
134 let flash = flash.try_lock().unwrap();
135 assert!(flash.mem[12..20].iter().position(|&x| x != 0xAA).is_none());
136 }
137
138 #[futures_test::test]
139 async fn can_erase() {
140 let flash = MemFlash::<1024, 128, 4>::new(0x00);
141
142 let flash = Mutex::<NoopRawMutex, _>::new(flash);
143 let mut partition = Partition::new(&flash, 128, 256);
144
145 partition.erase(0, 128).await.unwrap();
146
147 let flash = flash.try_lock().unwrap();
148 assert!(flash.mem[128..256].iter().position(|&x| x != 0xFF).is_none());
149 }
150}