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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#![warn(missing_docs)]
pub mod smart_eeprom;
pub use crate::pac::nvmctrl::ctrla::PRM_A;
use crate::pac::nvmctrl::ctrlb::CMD_AW;
use crate::pac::NVMCTRL;
use core::num::NonZeroU32;
use core::ops::Range;
use bitfield::bitfield;
#[inline(always)]
pub fn retrieve_flash_size() -> u32 {
static mut FLASHSIZE: Option<NonZeroU32> = None;
unsafe {
match FLASHSIZE {
Some(x) => x.into(),
None => {
let nvm = &*NVMCTRL::ptr();
let nvm_params = nvm.param.read();
if !nvm_params.psz().is_512() {
unreachable!("NVM page size is always expected to be 512 bytes");
}
let nvm_pages = nvm_params.nvmp().bits() as u32;
let flash_size = nvm_pages * 512;
FLASHSIZE = Some(NonZeroU32::new_unchecked(flash_size));
flash_size
}
}
}
}
#[inline(always)]
pub fn retrieve_bank_size() -> u32 {
retrieve_flash_size() / 2
}
pub const PAGESIZE: u32 = 512;
pub const BLOCKSIZE: u32 = 512 * 16;
pub struct Nvm {
nvm: NVMCTRL,
}
#[derive(Debug)]
pub enum PeripheralError {
NvmError,
EccSingleError,
EccDualError,
LockError,
ProgrammingError,
AddressError,
}
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
NonFlash,
Protected,
SmartEepromArea,
NoChangeBootProtection,
Peripheral(PeripheralError),
Dsu(super::dsu::Error),
Alignment,
}
#[derive(PartialEq, Debug)]
pub enum PhysicalBank {
A,
B,
}
#[derive(PartialEq, Debug)]
pub enum Bank {
Active,
Inactive,
}
impl Bank {
#[inline]
pub fn address(&self) -> u32 {
match self {
Bank::Active => 0,
Bank::Inactive => retrieve_bank_size(),
}
}
#[inline]
pub fn length(&self) -> u32 {
retrieve_bank_size()
}
}
pub type Result<T> = core::result::Result<T, Error>;
impl Nvm {
#[inline]
pub fn new(nvm: NVMCTRL) -> Self {
Self { nvm }
}
pub unsafe fn bank_swap(&mut self) -> ! {
self.command_sync(CMD_AW::BKSWRST);
unreachable!();
}
#[inline]
pub fn power_reduction_mode(&mut self, prm: PRM_A) {
self.nvm.ctrla.modify(|_, w| w.prm().variant(prm));
}
#[inline]
pub fn is_boot_protected(&self) -> bool {
!self.nvm.status.read().bpdis().bit()
}
#[inline]
pub fn first_bank(&self) -> PhysicalBank {
if self.nvm.status.read().afirst().bit() {
PhysicalBank::A
} else {
PhysicalBank::B
}
}
fn set_address(&mut self, address: u32) {
unsafe {
self.nvm
.addr
.write(|w| w.addr().bits(address & 0x00ff_ffff));
}
}
#[inline]
pub fn is_ready(&self) -> bool {
self.nvm.status.read().ready().bit()
}
fn command(&mut self, command: CMD_AW) {
self.nvm
.ctrlb
.write(|w| w.cmdex().key().cmd().variant(command));
}
fn command_sync(&mut self, command: CMD_AW) {
self.command(command);
while !self.nvm.intflag.read().done().bit() {}
self.nvm.intflag.write(|w| w.done().set_bit());
}
fn manage_error_states(&mut self) -> Result<()> {
let read_intflag = self.nvm.intflag.read();
let state = if read_intflag.addre().bit_is_set() {
Err(Error::Peripheral(PeripheralError::AddressError))
} else if read_intflag.locke().bit_is_set() {
Err(Error::Peripheral(PeripheralError::LockError))
} else if read_intflag.proge().bit_is_set() {
Err(Error::Peripheral(PeripheralError::ProgrammingError))
} else {
Ok(())
};
self.nvm.intflag.write(|w| w.addre().set_bit());
self.nvm.intflag.write(|w| w.locke().set_bit());
self.nvm.intflag.write(|w| w.proge().set_bit());
state
}
#[inline]
pub fn user_page(&self) -> Userpage {
let mut buffer = 0_u128;
let base_addr: *const u8 = 0x0080_4000 as *const u8;
for i in 0..16 {
buffer |= unsafe { core::ptr::read_volatile(base_addr.offset(i as isize)) as u128 }
<< (i * 8);
}
Userpage(buffer)
}
#[inline]
pub fn calibration_area(&self) -> CalibrationArea {
let mut buffer = 0_u64;
let base_addr: *const u8 = 0x0080_0080 as *const u8;
for i in 0..6 {
buffer |=
unsafe { core::ptr::read_volatile(base_addr.offset(i as isize)) as u64 } << (i * 8);
}
CalibrationArea(buffer)
}
#[inline]
pub fn temperatures_calibration_area(&self) -> TemperaturesCalibrationArea {
let mut buffer = 0_u128;
let base_addr: *const u8 = 0x0080_0100 as *const u8;
for i in 0..11 {
buffer |= unsafe { core::ptr::read_volatile(base_addr.offset(i as isize)) as u128 }
<< (i * 8);
}
TemperaturesCalibrationArea(buffer)
}
#[inline]
pub fn boot_protection(&mut self, protect: bool) -> Result<()> {
if self.is_boot_protected() != protect {
while !self.is_ready() {}
if !protect {
self.command_sync(CMD_AW::SBPDIS);
} else {
self.command_sync(CMD_AW::CBPDIS);
}
self.manage_error_states()
} else {
Err(Error::NoChangeBootProtection)
}
}
#[inline]
pub unsafe fn write_from_slice(
&mut self,
destination_address: u32,
source_slice: &[u32],
) -> Result<()> {
let source_address = source_slice.as_ptr() as u32;
let words = source_slice.len() as u32;
self.write(destination_address, source_address, words)
}
#[inline]
pub unsafe fn write(
&mut self,
destination_address: u32,
source_address: u32,
words: u32,
) -> Result<()> {
let step_size: u32 = core::mem::size_of::<u32>() as u32;
let length = words * step_size;
let read_addresses = source_address..(source_address + length);
let write_addresses = destination_address..(destination_address + length);
if source_address % step_size != 0 {
return Err(Error::Alignment);
}
if destination_address % step_size != 0 {
return Err(Error::Alignment);
}
if self.contains_non_flash_memory_area(&write_addresses) {
Err(Error::NonFlash)
} else if self.contains_bootprotected(&write_addresses) {
Err(Error::Protected)
} else if self.contains_smart_eeprom(&write_addresses) {
Err(Error::SmartEepromArea)
} else {
while !self.is_ready() {}
self.command_sync(CMD_AW::PBC);
let mut dirty = false;
for (destination_address, source_address) in write_addresses
.step_by(step_size as usize)
.zip(read_addresses.step_by(step_size as usize))
{
let value = core::ptr::read_volatile(source_address as *const u32);
core::ptr::write_volatile(destination_address as *mut u32, value);
dirty = true;
if destination_address % PAGESIZE >= PAGESIZE - step_size {
while !self.is_ready() {}
dirty = false;
self.command_sync(CMD_AW::WP);
}
}
while !self.is_ready() {}
if dirty {
self.command_sync(CMD_AW::WP);
}
self.manage_error_states()
}
}
#[inline]
pub unsafe fn erase(
&mut self,
address: u32,
length: u32,
granularity: EraseGranularity,
) -> Result<()> {
let flash_address = address - address % granularity.size();
let range_to_erase = flash_address..(flash_address + length * granularity.size());
if self.contains_non_flash_memory_area(&range_to_erase) {
Err(Error::NonFlash)
} else if self.contains_bootprotected(&range_to_erase) {
Err(Error::Protected)
} else if self.contains_smart_eeprom(&range_to_erase) {
Err(Error::SmartEepromArea)
} else {
for address in range_to_erase.step_by(granularity.size() as usize) {
self.set_address(address);
while !self.is_ready() {}
self.command_sync(granularity.command());
self.manage_error_states()?
}
Ok(())
}
}
fn contains_bootprotected(&self, input: &Range<u32>) -> bool {
let bootprot = self.nvm.status.read().bootprot().bits();
let bp_space = 8 * 1024 * (15 - bootprot) as u32;
let boot = &(Bank::Active.address()..(Bank::Active.address() + bp_space));
self.is_boot_protected() && range_overlap(input, boot)
}
fn contains_smart_eeprom(&self, input: &Range<u32>) -> bool {
let smart_eeprom_allocated_blocks = self.nvm.seestat.read().sblk().bits() as u32;
let smart_eeprom_end = Bank::Inactive.address() + Bank::Inactive.length();
let smart_eeprom_start = smart_eeprom_end - smart_eeprom_allocated_blocks * BLOCKSIZE;
let smart_eeprom = &(smart_eeprom_start..smart_eeprom_end);
range_overlap(input, smart_eeprom)
}
fn contains_non_flash_memory_area(&self, input: &Range<u32>) -> bool {
input.end > retrieve_flash_size()
}
#[inline]
pub fn smart_eeprom(&mut self) -> smart_eeprom::Result<'_> {
smart_eeprom::SmartEepromMode::retrieve(self)
}
}
#[derive(Copy, Clone, Debug)]
pub enum EraseGranularity {
Block,
Page,
}
impl EraseGranularity {
fn command(&self) -> CMD_AW {
match self {
EraseGranularity::Block => CMD_AW::EB,
EraseGranularity::Page => CMD_AW::EP,
}
}
fn size(&self) -> u32 {
match self {
EraseGranularity::Block => BLOCKSIZE,
EraseGranularity::Page => PAGESIZE,
}
}
}
fn range_overlap(a: &Range<u32>, b: &Range<u32>) -> bool {
a.start < b.end && b.start < a.end
}
bitfield! {
#[derive(Copy, Clone, Default)]
pub struct Userpage(u128);
impl Debug;
u32;
bod33_disable, _: 0;
bod33_level, _: 8, 1;
bod33_action, _: 10, 9;
bod33_hysteresis, _: 14, 11;
bod12_calibration_parameters, _: 25, 15;
nvm_bootloader_size, _: 29, 26;
see_sblk, _: 35, 32;
see_psz, _: 38, 36;
ram_ecc_disable, _: 39;
wdt_enable, _: 48;
wdt_always_on, _: 49;
wdt_period, _: 53, 50;
wdt_window, _: 57, 54;
wdt_ewoffset, _: 61, 58;
wdt_wen, _: 62;
nvm_locks, _: 95, 64;
user_page, _: 127, 96;
}
bitfield! {
#[derive(Copy, Clone, Default)]
pub struct CalibrationArea(u64);
impl Debug;
u32;
ac_bias, _: 1, 0;
adc0_biascomp, _: 4, 2;
adc0_biasrefbuf, _: 7, 5;
adc0_biasr2r, _: 10, 8;
adc1_biascomp, _: 18, 16;
adc1_biasrefbuf, _: 21, 19;
adc1_biasr2r, _: 24, 22;
usb_transn, _: 36, 32;
usb_transp, _: 41, 37;
usb_trim, _: 44, 42;
}
bitfield! {
#[derive(Copy, Clone, Default)]
pub struct TemperaturesCalibrationArea(u128);
impl Debug;
u32;
tli, _: 7, 0;
tld, _: 11, 8;
thi, _: 19, 12;
thd, _: 23, 20;
vpl, _: 51, 40;
vph, _: 63, 52;
vcl, _: 75, 63;
vch, _: 87, 76;
}