1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// todo: Dual bank support.
use core;
use cfg_if::cfg_if;
use super::{Flash, FlashError, page_to_address};
use crate::{
error::{Error, Result},
pac::FLASH,
util::bounded_loop,
};
const FLASH_KEY1: u32 = 0x4567_0123;
const FLASH_KEY2: u32 = 0xCDEF_89AB;
#[derive(Clone, Copy)]
/// Cortex-M33 secure programming, or nonsecure.
pub enum Security {
NonSecure,
Secure,
}
// todo
#[derive(Clone, Copy, PartialEq)]
/// Set dual bank mode (DBANK option bit)
pub enum DualBank {
Dual,
Single,
}
#[derive(Clone, Copy)]
#[repr(u8)]
pub enum Bank {
B1 = 0,
B2 = 1,
}
/// Check and clear all non-secure error programming flags due to a previous
/// programming. If not, NSPGSERR is set.
fn clear_error_flags(regs: &FLASH, security: Security) {
match security {
Security::NonSecure => {
let sr = regs.nssr().read();
// todo: Can't find this, although it's in the RM.
// if sr.nsoptwerr().bit_is_set() {
// regs.nssr().write(|w| w.nsoptwerr().bit(true));
// }
if sr.nspgserr().bit_is_set() {
regs.nssr().write(|w| w.nspgserr().bit(true));
}
if sr.nssizerr().bit_is_set() {
regs.nssr().write(|w| w.nssizerr().bit(true));
}
if sr.nspgaerr().bit_is_set() {
regs.nssr().write(|w| w.nspgaerr().bit(true));
}
if sr.nswrperr().bit_is_set() {
regs.nssr().write(|w| w.nswrperr().bit(true));
}
if sr.nsprogerr().bit_is_set() {
regs.nssr().write(|w| w.nsprogerr().bit(true));
}
if sr.nsoperr().bit_is_set() {
regs.nssr().write(|w| w.nsoperr().bit(true));
}
}
Security::Secure => {
let sr = regs.secsr().read();
if sr.secpgserr().bit_is_set() {
regs.secsr().write(|w| w.secpgserr().bit(true));
}
if sr.secsizerr().bit_is_set() {
regs.secsr().write(|w| w.secsizerr().bit(true));
}
if sr.secpgaerr().bit_is_set() {
regs.secsr().write(|w| w.secpgaerr().bit(true));
}
if sr.secwrperr().bit_is_set() {
regs.secsr().write(|w| w.secwrperr().bit(true));
}
if sr.secprogerr().bit_is_set() {
regs.secsr().write(|w| w.secprogerr().bit(true));
}
if sr.secoperr().bit_is_set() {
regs.secsr().write(|w| w.secoperr().bit(true));
}
}
}
}
impl Flash {
/// Unlock the flash memory, allowing writes. See L4 Reference manual, section 6.3.5.
pub fn unlock(&mut self, security: Security) -> Result<()> {
match security {
Security::NonSecure => {
if self.regs.nscr().read().nslock().bit_is_clear() {
return Ok(());
}
self.regs.nskeyr().write(|w| unsafe { w.bits(FLASH_KEY1) });
self.regs.nskeyr().write(|w| unsafe { w.bits(FLASH_KEY2) });
if self.regs.nscr().read().nslock().bit_is_clear() {
Ok(())
} else {
Err(Error::FlashError(FlashError::Failure))
}
}
Security::Secure => {
if self.regs.seccr().read().seclock().bit_is_clear() {
return Ok(());
}
self.regs.seckeyr().write(|w| unsafe { w.bits(FLASH_KEY1) });
self.regs.seckeyr().write(|w| unsafe { w.bits(FLASH_KEY2) });
if self.regs.seccr().read().seclock().bit_is_clear() {
Ok(())
} else {
Err(Error::FlashError(FlashError::Failure))
}
}
}
}
/// Lock the flash memory, allowing writes.
pub fn lock(&mut self, security: Security) -> Result<()> {
match security {
Security::NonSecure => {
bounded_loop!(
self.regs.nssr().read().nsbsy().bit_is_set(),
Error::RegisterUnchanged
);
self.regs.nscr().modify(|_, w| w.nslock().bit(true));
}
Security::Secure => {
bounded_loop!(
self.regs.secsr().read().secbsy().bit_is_set(),
Error::RegisterUnchanged
);
self.regs.seccr().modify(|_, w| w.seclock().bit(true));
}
}
Ok(())
}
/// Erase an entire page. See L5 Reference manual, section 6.3.6.
/// For why this is required, reference L4 RM, section 3.3.7:
/// "Programming in a previously programmed address is not allowed except if the data to write
/// is full zero, and any attempt will set PROGERR flag in the Flash status register
/// (FLASH_SR)."
pub fn erase_page(&mut self, bank: Bank, page: usize, security: Security) -> Result<()> {
self.unlock(security)?;
match security {
Security::NonSecure => {
// 1. Check that no Flash memory operation is ongoing by checking the NSBSY bit in the Flash
// status register (FLASH_NSSR).
let sr = self.regs.nssr().read();
if sr.nsbsy().bit_is_set() {
self.lock(security)?;
return Err(Error::FlashError(FlashError::Busy));
}
// 2. Check and clear all error programming flags due to a previous programming. If not,
// NSPGSERR is set.
clear_error_flags(&self.regs, security);
// 3. In dual-bank mode (DBANK option bit is set), set the NSPER bit and select the
// non-secure page to erase (NSPNB) with the associated bank (NSBKER) in the
// FLASH_NScr(). In single-bank mode (DBANK option bit is reset), set the NSPER bit
// and select the page to erase (NSPNB). The NSBKER bit in the FLASH_NSCR must be
// kept cleared.
if self.dual_bank == DualBank::Dual {
self.regs.nscr().modify(|_, w| unsafe {
w.nsbker().bit(bank as u8 != 0);
w.nspnb().bits(page as u8);
w.nsper().bit(true)
});
} else {
self.regs.nscr().modify(|_, w| unsafe {
w.nspnb().bits(page as u8);
w.nsper().bit(true)
});
}
// 4. Set the NSSTRT bit in the FLASH_NSCR register.
self.regs.nscr().modify(|_, w| w.nsstrt().bit(true));
// 5. Wait for the NSBSY bit to be cleared in the FLASH_SR register.
bounded_loop!(
self.regs.nssr().read().nsbsy().bit_is_set(),
Error::RegisterUnchanged
);
self.regs.nscr().modify(|_, w| w.nsper().clear_bit());
}
Security::Secure => {
let sr = self.regs.secsr().read();
if sr.secbsy().bit_is_set() {
self.lock(security)?;
return Err(Error::FlashError(FlashError::Busy));
}
clear_error_flags(&self.regs, security);
if self.dual_bank == DualBank::Dual {
self.regs.seccr().modify(|_, w| unsafe {
w.secbker().bit(bank as u8 != 0);
w.secpnb().bits(page as u8);
w.secper().bit(true)
});
} else {
self.regs.seccr().modify(|_, w| unsafe {
w.secpnb().bits(page as u8);
w.secper().bit(true)
});
}
self.regs.seccr().modify(|_, w| w.secstrt().bit(true));
bounded_loop!(
self.regs.secsr().read().secbsy().bit_is_set(),
Error::RegisterUnchanged
);
self.regs.nscr().modify(|_, w| w.nsper().clear_bit());
}
}
self.lock(security)?;
Ok(())
}
/// Mass erase: L5 RM section 6.3.6
pub fn erase_bank(&mut self, bank: Bank, security: Security) -> Result<()> {
self.unlock(security)?;
match security {
Security::NonSecure => {
// To perform a bank Mass Erase, follow the procedure below:
// 1. Check that no Flash memory operation is ongoing by checking the NSBSY bit in the
// FLASH_NSSR register.
let sr = self.regs.nssr().read();
if sr.nsbsy().bit_is_set() {
self.lock(security)?;
return Err(Error::FlashError(FlashError::Busy));
}
// 2. Check and clear all error programming flags due to a previous programming. If not,
// NSPGSERR is set.
clear_error_flags(&self.regs, security);
// 3. Set the NSMER1 bit or NSMER2 (depending on the bank) in the FLASH_NSCR
// register. Both banks can be selected in the same operation, in that case it corresponds
// to a mass erase.
match bank {
Bank::B1 => self.regs.nscr().modify(|_, w| w.nsmer1().bit(true)),
Bank::B2 => self.regs.nscr().modify(|_, w| w.nsmer2().clear_bit()),
};
// 4. Set the NSSTRT bit in the FLASH_NSCR register.
self.regs.nscr().modify(|_, w| w.nsstrt().bit(true));
// 5. Wait for the NSBSY bit to be cleared in the FLASH_NSSR register.
bounded_loop!(
self.regs.nssr().read().nsbsy().bit_is_set(),
Error::RegisterUnchanged
);
// 6. The NSMER1 or NSMER2 bits can be cleared if no more non-secure bank erase is
// requested.
match bank {
Bank::B1 => self.regs.nscr().modify(|_, w| w.nsmer1().clear_bit()),
Bank::B2 => self.regs.nscr().modify(|_, w| w.nsmer2().clear_bit()),
};
}
Security::Secure => {
let sr = self.regs.secsr().read();
if sr.secbsy().bit_is_set() {
self.lock(security)?;
return Err(Error::FlashError(FlashError::Busy));
}
clear_error_flags(&self.regs, security);
match bank {
Bank::B1 => self.regs.seccr().modify(|_, w| w.secmer1().bit(true)),
Bank::B2 => self.regs.seccr().modify(|_, w| w.secmer2().clear_bit()),
};
self.regs.seccr().modify(|_, w| w.secstrt().bit(true));
bounded_loop!(
self.regs.secsr().read().secbsy().bit_is_set(),
Error::RegisterUnchanged
);
match bank {
Bank::B1 => self.regs.seccr().modify(|_, w| w.secmer1().clear_bit()),
Bank::B2 => self.regs.seccr().modify(|_, w| w.secmer2().clear_bit()),
};
}
}
self.lock(security)?;
Ok(())
}
/// Write the contents of a page. Must be erased first. See L5 RM, section 6.3.7.
pub fn write_page(
&mut self,
bank: Bank,
page: usize,
data: &[u8],
security: Security,
) -> Result<()> {
// todo: Consider a u8-based approach.
// todo: DRY from `erase_page`.
// The Flash memory programming sequence in standard mode is as follows:
// 1. Check that no Flash main memory operation is ongoing by checking the NBBSY bit in the
// Flash status register (FLASH_SR).
self.unlock(security)?;
match security {
Security::NonSecure => {
let sr = self.regs.nssr().read();
if sr.nsbsy().bit_is_set() {
self.lock(security)?;
return Err(Error::FlashError(FlashError::Busy));
}
// 2. Check and clear all error programming flags due to a previous programming. If not,
// NSPGSERR is set.
clear_error_flags(&self.regs, security);
// 3. Set the NSPG bit in tFLASH_NSCR register
self.regs.nscr().modify(|_, w| w.nspg().bit(true));
// todo: You have 3x DRY here re teh writing. Put that in a fn?
// 4. Perform the data write operation at the desired memory address, inside main memory
// block or OTP area. Only double word can be programmed.
let mut address = page_to_address(self.dual_bank, bank, page) as *mut u32;
// Map our 8-bit data input API to the 64-bit write API.
// "The Flash memory is programmed 72 bits at a time (64 bits + 8 bits ECC)."
for chunk in data.chunks(8) {
// 8 bytes is 64 bits. (Double word)
// Pad to 64 bits if required, ie on the last word.
let mut padded = [0xff; 8];
let (word1, word2) = if chunk.len() < 8 {
// 0xff due to the default value of erased pages.
padded[0..chunk.len()].clone_from_slice(&chunk);
(
u32::from_le_bytes(padded[0..4].try_into().unwrap()),
u32::from_le_bytes(padded[4..8].try_into().unwrap()),
)
} else {
(
u32::from_le_bytes(chunk[0..4].try_into().unwrap()),
u32::from_le_bytes(chunk[4..8].try_into().unwrap()),
)
};
// 5. Wait until the BSY bit is cleared in the FLASH_NSSR register.
bounded_loop!(
self.regs.nssr().read().nsbsy().bit_is_set(),
Error::RegisterUnchanged
);
// 6. Check that NSEOP flag is set in the FLASH_NSSR register (meaning that the programming
// operation has succeed), and clear it by software.
if self.regs.nssr().read().nseop().bit_is_set() {
self.regs.nssr().modify(|_, w| w.nseop().bit(true));
}
}
// 7. Clear the NSPG bit in the FLASH_CR register if there no more programming request
// anymore.
self.regs.nscr().modify(|_, w| w.nspg().clear_bit());
}
Security::Secure => {
// Process here is monstly the same, but sub in sec registers and fields.
let sr = self.regs.secsr().read();
if sr.secbsy().bit_is_set() {
self.lock(security)?;
return Err(Error::FlashError(FlashError::Busy));
}
clear_error_flags(&self.regs, security);
self.regs.seccr().modify(|_, w| w.secpg().bit(true));
let mut address = page_to_address(self.dual_bank, bank, page) as *mut u32;
// todo: No need to repeat this section.
for chunk in data.chunks(8) {
// 8 bytes is 64 bits. (Double word)
// Pad to 64 bits if required, ie on the last word.
let mut padded = [0xff; 8];
let (word1, word2) = if chunk.len() < 8 {
// 0xff due to the default value of erased pages.
padded[0..chunk.len()].clone_from_slice(&chunk);
(
u32::from_le_bytes(padded[0..4].try_into().unwrap()),
u32::from_le_bytes(padded[4..8].try_into().unwrap()),
)
} else {
(
u32::from_le_bytes(chunk[0..4].try_into().unwrap()),
u32::from_le_bytes(chunk[4..8].try_into().unwrap()),
)
};
unsafe {
// Write a first word in an address aligned with double wor
core::ptr::write_volatile(address, word1);
address = address.add(1);
// Write the second word
core::ptr::write_volatile(address, word2);
address = address.add(1);
}
bounded_loop!(
self.regs.secsr().read().secbsy().bit_is_set(),
Error::RegisterUnchanged
);
if self.regs.secsr().read().seceop().bit_is_set() {
self.regs.secsr().modify(|_, w| w.seceop().bit(true)); // clear
}
}
self.regs.seccr().modify(|_, w| w.secpg().clear_bit());
}
}
self.lock(security)?;
Ok(())
}
/// Erase a page, then write to it.
pub fn erase_write_page(
&mut self,
bank: Bank,
page: usize,
data: &[u8],
security: Security,
) -> Result<()> {
self.erase_page(bank, page, security)?;
self.write_page(bank, page, data, security)?;
Ok(())
}
}