aboutsummaryrefslogtreecommitdiff
path: root/embassy-embedded-hal/src/flash
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2023-05-26 22:31:30 +0200
committerGitHub <[email protected]>2023-05-26 22:31:30 +0200
commitef8695cecb8cd4124cf5045de7ccc0ac80c6ef4a (patch)
treee58b509c86fc7eae837bfa2e0bc6a58808321856 /embassy-embedded-hal/src/flash
parenta8b426d0fe86e6fc3d1813765946cc82e774c3d3 (diff)
parente495473fc341e1403a004901e0d0a575f33350e0 (diff)
Merge pull request #1494 from rmja/flash-partition
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.rs128
-rw-r--r--embassy-embedded-hal/src/flash/mod.rs11
-rw-r--r--embassy-embedded-hal/src/flash/partition.rs145
4 files changed, 512 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..afb0d1a15
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/mem_flash.rs
@@ -0,0 +1,128 @@
1use alloc::vec::Vec;
2
3use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
4#[cfg(feature = "nightly")]
5use embedded_storage_async::nor_flash::{NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash};
6
7extern crate alloc;
8
9pub(crate) struct MemFlash<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> {
10 pub mem: [u8; SIZE],
11 pub writes: Vec<(u32, usize)>,
12 pub erases: Vec<(u32, u32)>,
13}
14
15impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE> {
16 #[allow(unused)]
17 pub const fn new(fill: u8) -> Self {
18 Self {
19 mem: [fill; SIZE],
20 writes: Vec::new(),
21 erases: Vec::new(),
22 }
23 }
24
25 fn read(&mut self, offset: u32, bytes: &mut [u8]) {
26 let len = bytes.len();
27 bytes.copy_from_slice(&self.mem[offset as usize..offset as usize + len]);
28 }
29
30 fn write(&mut self, offset: u32, bytes: &[u8]) {
31 self.writes.push((offset, bytes.len()));
32 let offset = offset as usize;
33 assert_eq!(0, bytes.len() % WRITE_SIZE);
34 assert_eq!(0, offset % WRITE_SIZE);
35 assert!(offset + bytes.len() <= SIZE);
36
37 self.mem[offset..offset + bytes.len()].copy_from_slice(bytes);
38 }
39
40 fn erase(&mut self, from: u32, to: u32) {
41 self.erases.push((from, to));
42 let from = from as usize;
43 let to = to as usize;
44 assert_eq!(0, from % ERASE_SIZE);
45 assert_eq!(0, to % ERASE_SIZE);
46 self.mem[from..to].fill(0xff);
47 }
48}
49
50impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> Default
51 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
52{
53 fn default() -> Self {
54 Self::new(0xff)
55 }
56}
57
58impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ErrorType
59 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
60{
61 type Error = core::convert::Infallible;
62}
63
64impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ReadNorFlash
65 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
66{
67 const READ_SIZE: usize = 1;
68
69 fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
70 self.read(offset, bytes);
71 Ok(())
72 }
73
74 fn capacity(&self) -> usize {
75 SIZE
76 }
77}
78
79impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> NorFlash
80 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
81{
82 const WRITE_SIZE: usize = WRITE_SIZE;
83 const ERASE_SIZE: usize = ERASE_SIZE;
84
85 fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
86 self.write(offset, bytes);
87 Ok(())
88 }
89
90 fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
91 self.erase(from, to);
92 Ok(())
93 }
94}
95
96#[cfg(feature = "nightly")]
97impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncReadNorFlash
98 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
99{
100 const READ_SIZE: usize = 1;
101
102 async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
103 self.read(offset, bytes);
104 Ok(())
105 }
106
107 fn capacity(&self) -> usize {
108 SIZE
109 }
110}
111
112#[cfg(feature = "nightly")]
113impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncNorFlash
114 for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
115{
116 const WRITE_SIZE: usize = WRITE_SIZE;
117 const ERASE_SIZE: usize = ERASE_SIZE;
118
119 async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
120 self.write(offset, bytes);
121 Ok(())
122 }
123
124 async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
125 self.erase(from, to);
126 Ok(())
127 }
128}
diff --git a/embassy-embedded-hal/src/flash/mod.rs b/embassy-embedded-hal/src/flash/mod.rs
new file mode 100644
index 000000000..0210b198d
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/mod.rs
@@ -0,0 +1,11 @@
1//! Utilities related to flash.
2
3mod concat_flash;
4#[cfg(test)]
5pub(crate) mod mem_flash;
6#[cfg(feature = "nightly")]
7mod partition;
8
9pub use concat_flash::ConcatFlash;
10#[cfg(feature = "nightly")]
11pub 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..66d93c0ea
--- /dev/null
+++ b/embassy-embedded-hal/src/flash/partition.rs
@@ -0,0 +1,145 @@
1use embassy_sync::blocking_mutex::raw::RawMutex;
2use embassy_sync::mutex::Mutex;
3use embedded_storage::nor_flash::{ErrorType, NorFlashError, NorFlashErrorKind};
4use embedded_storage_async::nor_flash::{NorFlash, ReadNorFlash};
5
6/// A logical partition of an underlying shared flash
7///
8/// A partition holds an offset and a size of the flash,
9/// and is restricted to operate with that range.
10/// There is no guarantee that muliple partitions on the same flash
11/// operate on mutually exclusive ranges - such a separation is up to
12/// the user to guarantee.
13pub struct Partition<'a, M: RawMutex, T: NorFlash> {
14 flash: &'a Mutex<M, T>,
15 offset: u32,
16 size: u32,
17}
18
19#[derive(Debug)]
20#[cfg_attr(feature = "defmt", derive(defmt::Format))]
21pub enum Error<T> {
22 OutOfBounds,
23 Flash(T),
24}
25
26impl<'a, M: RawMutex, T: NorFlash> Partition<'a, M, T> {
27 /// Create a new partition
28 pub const fn new(flash: &'a Mutex<M, T>, offset: u32, size: u32) -> Self {
29 if offset % T::READ_SIZE as u32 != 0 || offset % T::WRITE_SIZE as u32 != 0 || offset % T::ERASE_SIZE as u32 != 0
30 {
31 panic!("Partition offset must be a multiple of read, write and erase size");
32 }
33 if size % T::READ_SIZE as u32 != 0 || size % T::WRITE_SIZE as u32 != 0 || size % T::ERASE_SIZE as u32 != 0 {
34 panic!("Partition size must be a multiple of read, write and erase size");
35 }
36 Self { flash, offset, size }
37 }
38}
39
40impl<T: NorFlashError> NorFlashError for Error<T> {
41 fn kind(&self) -> NorFlashErrorKind {
42 match self {
43 Error::OutOfBounds => NorFlashErrorKind::OutOfBounds,
44 Error::Flash(f) => f.kind(),
45 }
46 }
47}
48
49impl<M: RawMutex, T: NorFlash> ErrorType for Partition<'_, M, T> {
50 type Error = Error<T::Error>;
51}
52
53#[cfg(feature = "nightly")]
54impl<M: RawMutex, T: NorFlash> ReadNorFlash for Partition<'_, M, T> {
55 const READ_SIZE: usize = T::READ_SIZE;
56
57 async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
58 if offset + bytes.len() as u32 > self.size {
59 return Err(Error::OutOfBounds);
60 }
61
62 let mut flash = self.flash.lock().await;
63 flash.read(self.offset + offset, bytes).await.map_err(Error::Flash)
64 }
65
66 fn capacity(&self) -> usize {
67 self.size as usize
68 }
69}
70
71#[cfg(feature = "nightly")]
72impl<M: RawMutex, T: NorFlash> NorFlash for Partition<'_, M, T> {
73 const WRITE_SIZE: usize = T::WRITE_SIZE;
74 const ERASE_SIZE: usize = T::ERASE_SIZE;
75
76 async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
77 if offset + bytes.len() as u32 > self.size {
78 return Err(Error::OutOfBounds);
79 }
80
81 let mut flash = self.flash.lock().await;
82 flash.write(self.offset + offset, bytes).await.map_err(Error::Flash)
83 }
84
85 async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
86 if to > self.size {
87 return Err(Error::OutOfBounds);
88 }
89
90 let mut flash = self.flash.lock().await;
91 flash
92 .erase(self.offset + from, self.offset + to)
93 .await
94 .map_err(Error::Flash)
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use embassy_sync::blocking_mutex::raw::NoopRawMutex;
101
102 use super::*;
103 use crate::flash::mem_flash::MemFlash;
104
105 #[futures_test::test]
106 async fn can_read() {
107 let mut flash = MemFlash::<1024, 128, 4>::default();
108 flash.mem[132..132 + 8].fill(0xAA);
109
110 let flash = Mutex::<NoopRawMutex, _>::new(flash);
111 let mut partition = Partition::new(&flash, 128, 256);
112
113 let mut read_buf = [0; 8];
114 partition.read(4, &mut read_buf).await.unwrap();
115
116 assert!(read_buf.iter().position(|&x| x != 0xAA).is_none());
117 }
118
119 #[futures_test::test]
120 async fn can_write() {
121 let flash = MemFlash::<1024, 128, 4>::default();
122
123 let flash = Mutex::<NoopRawMutex, _>::new(flash);
124 let mut partition = Partition::new(&flash, 128, 256);
125
126 let write_buf = [0xAA; 8];
127 partition.write(4, &write_buf).await.unwrap();
128
129 let flash = flash.try_lock().unwrap();
130 assert!(flash.mem[132..132 + 8].iter().position(|&x| x != 0xAA).is_none());
131 }
132
133 #[futures_test::test]
134 async fn can_erase() {
135 let flash = MemFlash::<1024, 128, 4>::new(0x00);
136
137 let flash = Mutex::<NoopRawMutex, _>::new(flash);
138 let mut partition = Partition::new(&flash, 128, 256);
139
140 partition.erase(0, 128).await.unwrap();
141
142 let flash = flash.try_lock().unwrap();
143 assert!(flash.mem[128..256].iter().position(|&x| x != 0xFF).is_none());
144 }
145}