stm32f303xc/
flash.rs

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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Embedded Flash Memory Controller
//!
//! Used for reading, writing and erasing the flash and the option bytes.
//! Erase and write operations have hardware interrupt support, while read
//! operations use pseudo interrupts in the form of deferred calls. The
//! programming interface only allows halfword(u16) writes.
//!
//! Option bytes should be used with caution, especially those concerning
//! read and write protection. For example, erasing the option bytes
//! enables by default readout protection.

use core::cell::Cell;
use core::ops::{Index, IndexMut};
use kernel::deferred_call::{DeferredCall, DeferredCallClient};
use kernel::hil;
use kernel::utilities::cells::OptionalCell;
use kernel::utilities::cells::TakeCell;
use kernel::utilities::cells::VolatileCell;
use kernel::utilities::registers::interfaces::{ReadWriteable, Readable, Writeable};
use kernel::utilities::registers::register_bitfields;
use kernel::utilities::registers::{ReadOnly, ReadWrite, WriteOnly};
use kernel::utilities::StaticRef;
use kernel::ErrorCode;

const FLASH_BASE: StaticRef<FlashRegisters> =
    unsafe { StaticRef::new(0x40022000 as *const FlashRegisters) };

#[repr(C)]
struct FlashRegisters {
    /// Flash access control register
    /// Address offset 0x00
    pub acr: ReadWrite<u32, AccessControl::Register>,
    /// Flash key register
    /// Address offset 0x04
    pub kr: WriteOnly<u32, Key::Register>,
    /// Flash option key register
    /// Address offset 0x08
    pub okr: WriteOnly<u32, Key::Register>,
    /// Flash status register
    /// Address offset 0x0C
    pub sr: ReadWrite<u32, Status::Register>,
    /// Flash control register
    /// Address offset 0x10
    pub cr: ReadWrite<u32, Control::Register>,
    /// Flash address register
    /// Address offset 0x14
    pub ar: WriteOnly<u32, Address::Register>,
    /// Reserved
    _reserved: u32,
    /// Flash option byte register
    /// Address offset 0x1C
    pub obr: ReadOnly<u32, OptionByte::Register>,
    /// Flash write protection register
    /// Address offset 0x20
    pub wrpr: ReadOnly<u32, WriteProtect::Register>,
}

register_bitfields! [u32,
    AccessControl [
        /// Prefetch buffer status
        PRFTBS OFFSET(5) NUMBITS(1) [],
        /// Prefetch buffer enable
        PRFTBE OFFSET(4) NUMBITS(1) [],
        /// Flash half cycle access enable
        HLFCYA OFFSET(3) NUMBITS(1) [],
        /// Represents the ratio of the HCLK period to the Flash access time
        LATENCY OFFSET(0) NUMBITS(3) [
            /// If 0 < HCLK <= 24MHz
            ZeroWaitState = 0,
            /// If 24MHz < HCLK <= 48MHz
            OneWaitState = 1,
            /// If 48MHz < HCLK <= 72MHz
            TwoWaitState = 2
        ]
    ],
    Key [
        /// Flash or option byte key
        /// Represents the keys to unlock the flash or the option
        /// bytes write enable
        KEYR OFFSET(0) NUMBITS(32) []
    ],
    Status [
        /// End of operation
        /// Set by the hardware when a flash operation (programming or erase)
        /// is completed.
        EOP OFFSET(5) NUMBITS(1) [],
        /// Write protection error
        /// Set by the hardware when programming a write-protected
        /// address of the flash memory.
        WRPRTERR OFFSET(4) NUMBITS(1) [],
        /// Programming error
        /// Set by the hardware when an address to be programmed contains a
        /// value different from 0xFFFF before programming.
        /// Note that the STRT bit in Control register should be reset when
        /// the operation finishes or and error occurs.
        PGERR OFFSET(2) NUMBITS(1) [],
        /// Busy
        /// Indicates that a flash operation is in progress. This is set on
        /// the beginning of a Flash operation and reset when the operation
        /// finishes or an error occurs.
        BSY OFFSET(0) NUMBITS(1) []
    ],
    Control [
        /// Force option byte loading
        /// When set, this bit forces the option byte reloading.
        /// This generates a system reset.
        OBLLAUNCH OFFSET(13) NUMBITS(1) [],
        /// End of operation interrupt enable
        /// This enables the interrupt generation when the EOP bit in the
        /// Status register is set.
        EOPIE OFFSET(12) NUMBITS(1) [],
        /// Error interrupt enable
        /// This bit enables the interrupt generation on an errror when PGERR
        /// or WRPRTERR are set in the Status register
        ERRIE OFFSET(10) NUMBITS(1) [],
        /// Option bytes write enable
        /// When set, the option bytes can be programmed. This bit is set on
        /// on writing the correct key sequence to the OptionKey register.
        OPTWRE OFFSET(9) NUMBITS(1) [],
        /// When set, it indicates that the Flash is locked. This bit is reset
        /// by hardware after detecting the unlock sequence.
        LOCK OFFSET(7) NUMBITS(1) [],
        /// This bit triggers and ERASE operation when set. This bit is only
        /// set by software and reset when the BSY bit is reset.
        STRT OFFSET(6) NUMBITS(1) [],
        /// Option byte erase chosen
        OPTER OFFSET(5) NUMBITS(1) [],
        /// Option byte programming chosen
        OPTPG OFFSET(4) NUMBITS(1) [],
        /// Mass erase of all user pages chosen
        MER OFFSET(2) NUMBITS(1) [],
        /// Page erase chosen
        PER OFFSET(1) NUMBITS(1) [],
        /// Flash programming chosen
        PG OFFSET(0) NUMBITS(1) []
    ],
    Address [
        /// Flash address
        /// Chooses the address to program when programming is selected
        /// or a page to erase when Page Erase is selected.
        /// Note that write access to this register is blocked when the
        /// BSY bit in the Status register is set.
        FAR OFFSET(0) NUMBITS(32) []
    ],
    OptionByte [
        DATA1 OFFSET(24) NUMBITS(8) [],
        DATA0 OFFSET(16) NUMBITS(8) [],
        /// This allows the user to enable the SRAM hardware parity check.
        /// Disabled by default.
        SRAMPE OFFSET(14) NUMBITS(1) [
            /// Parity check enabled
            ENABLED = 0,
            /// Parity check diasbled
            DISABLED = 1
        ],
        /// This bit selects the analog monitoring on the VDDA power source
        VDDAMONITOR OFFSET(13) NUMBITS(1) [
            /// VDDA power supply supervisor disabled
            DISABLED = 0,
            /// VDDA power supply supervisor enabled
            ENABLED = 1
        ],
        /// Together with the BOOT0, this bit selects Boot mode from the main
        /// Flash memory, SRAM or System memory
        NBOOT1 OFFSET(12) NUMBITS(1) [],
        NRSTSTDBY OFFSET(10) NUMBITS(1) [
            /// Reset generated when entering Standby mode
            RST = 0,
            /// No reset generated
            NRST = 1
        ],
        NRSTSTOP OFFSET(9) NUMBITS(1) [
            /// Reset generated when entering Stop mode
            RST = 0,
            /// No reset generated
            NRST = 1
        ],
        /// Chooses watchdog type
        WDGSW OFFSET(8) NUMBITS(1) [
            /// Hardware watchdog
            HARDWARE = 0,
            /// Software watchdog
            SOFTWARE = 1
        ],
        /// Read protection Level status
        RDPRT OFFSET(1) NUMBITS(2) [
            /// Read protection level 0 (ST production setup)
            LVL0 = 0,
            /// Read protection level 1
            LVL1 = 1,
            /// Read protection level 2
            LVL2 = 3
        ],
        /// Option byte Load error
        /// When set, this indicates that the loaded option byte and its
        /// complement do not match. The corresponding byte and its complement
        /// are read as 0xFF in the OptionByte or WriteProtect register
        OPTERR OFFSET(1) NUMBITS(1) []
    ],
    WriteProtect [
        /// Write protect
        /// This register contains the write-protection option
        /// bytes loaded by the OBL
        WRP OFFSET(0) NUMBITS(32) []
    ]
];

const PAGE_SIZE: usize = 2048;

/// Address of the first flash page.
const PAGE_START: usize = 0x08000000;

/// Address of the first option byte.
const OPT_START: usize = 0x1FFFF800;

/// Used for unlocking the flash or the option bytes.
const KEY1: u32 = 0x45670123;
const KEY2: u32 = 0xCDEF89AB;

/// This is a wrapper around a u8 array that is sized to a single page for the
/// stm32f303xc. Users of this module must pass an object of this type to use the
/// `hil::flash::Flash` interface.
///
/// An example looks like:
///
/// ```rust
/// # extern crate stm32f303xc;
/// # use stm32f303xc::flash::StmF303Page;
/// # use kernel::static_init;
///
/// let pagebuffer = unsafe { static_init!(StmF303Page, StmF303Page::default()) };
/// ```
pub struct StmF303Page(pub [u8; PAGE_SIZE]);

impl Default for StmF303Page {
    fn default() -> Self {
        Self([0; PAGE_SIZE])
    }
}

impl StmF303Page {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl Index<usize> for StmF303Page {
    type Output = u8;

    fn index(&self, idx: usize) -> &u8 {
        &self.0[idx]
    }
}

impl IndexMut<usize> for StmF303Page {
    fn index_mut(&mut self, idx: usize) -> &mut u8 {
        &mut self.0[idx]
    }
}

impl AsMut<[u8]> for StmF303Page {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum FlashState {
    Ready,       // Entry state.
    Read,        // Read procedure.
    Write,       // Programming procedure.
    Erase,       // Erase procedure.
    WriteOption, // Option bytes programming procedure.
    EraseOption, // Option bytes erase procedure.
}

pub struct Flash {
    registers: StaticRef<FlashRegisters>,
    client: OptionalCell<&'static dyn hil::flash::Client<Flash>>,
    buffer: TakeCell<'static, StmF303Page>,
    state: Cell<FlashState>,
    write_counter: Cell<usize>,
    page_number: Cell<usize>,
    deferred_call: DeferredCall,
}

impl Flash {
    pub fn new() -> Flash {
        Flash {
            registers: FLASH_BASE,
            client: OptionalCell::empty(),
            buffer: TakeCell::empty(),
            state: Cell::new(FlashState::Ready),
            write_counter: Cell::new(0),
            page_number: Cell::new(0),
            deferred_call: DeferredCall::new(),
        }
    }

    /// Enables hardware interrupts.
    pub fn enable(&self) {
        self.registers.cr.modify(Control::EOPIE::SET);
        self.registers.cr.modify(Control::ERRIE::SET);
    }

    pub fn is_locked(&self) -> bool {
        self.registers.cr.is_set(Control::LOCK)
    }

    pub fn unlock(&self) {
        self.registers.kr.write(Key::KEYR.val(KEY1));
        self.registers.kr.write(Key::KEYR.val(KEY2));
    }

    pub fn lock(&self) {
        self.registers.cr.modify(Control::LOCK::SET);
    }

    pub fn unlock_option(&self) {
        self.registers.okr.write(Key::KEYR.val(KEY1));
        self.registers.okr.write(Key::KEYR.val(KEY2));
    }

    pub fn lock_option(&self) {
        self.registers.cr.modify(Control::OPTWRE::CLEAR);
    }

    /// Forces option byte reloading. Also generates a system reset.
    pub fn load_option(&self) {
        self.registers.cr.modify(Control::OBLLAUNCH::SET);
    }

    pub fn handle_interrupt(&self) {
        if self.registers.sr.is_set(Status::EOP) {
            // Cleared by writing a 1.
            self.registers.sr.modify(Status::EOP::SET);

            match self.state.get() {
                FlashState::Write => {
                    self.write_counter.set(self.write_counter.get() + 2);

                    if self.write_counter.get() == PAGE_SIZE {
                        self.registers.cr.modify(Control::PG::CLEAR);
                        self.state.set(FlashState::Ready);
                        self.write_counter.set(0);

                        self.client.map(|client| {
                            self.buffer.take().map(|buffer| {
                                client.write_complete(buffer, Ok(()));
                            });
                        });
                    } else {
                        self.program_halfword();
                    }
                }
                FlashState::Erase => {
                    if self.registers.cr.is_set(Control::PER) {
                        self.registers.cr.modify(Control::PER::CLEAR);
                    }

                    if self.registers.cr.is_set(Control::MER) {
                        self.registers.cr.modify(Control::MER::CLEAR);
                    }

                    self.state.set(FlashState::Ready);
                    self.client.map(|client| {
                        client.erase_complete(Ok(()));
                    });
                }
                FlashState::WriteOption => {
                    self.registers.cr.modify(Control::OPTPG::CLEAR);
                    self.state.set(FlashState::Ready);

                    self.client.map(|client| {
                        self.buffer.take().map(|buffer| {
                            client.write_complete(buffer, Ok(()));
                        });
                    });
                }
                FlashState::EraseOption => {
                    self.registers.cr.modify(Control::OPTER::CLEAR);
                    self.state.set(FlashState::Ready);

                    self.client.map(|client| {
                        client.erase_complete(Ok(()));
                    });
                }
                _ => {}
            }
        }

        if self.state.get() == FlashState::Read {
            self.state.set(FlashState::Ready);
            self.client.map(|client| {
                self.buffer.take().map(|buffer| {
                    client.read_complete(buffer, Ok(()));
                });
            });
        }

        if self.registers.sr.is_set(Status::WRPRTERR) {
            // Cleared by writing a 1.
            self.registers.sr.modify(Status::WRPRTERR::SET);

            match self.state.get() {
                FlashState::Write => {
                    self.registers.cr.modify(Control::PG::CLEAR);
                    self.client.map(|client| {
                        self.buffer.take().map(|buffer| {
                            client.write_complete(buffer, Err(hil::flash::Error::FlashError));
                        });
                    });
                }
                FlashState::Erase => {
                    self.client.map(|client| {
                        client.erase_complete(Err(hil::flash::Error::FlashError));
                    });
                }
                _ => {}
            }

            self.state.set(FlashState::Ready);
        }

        if self.registers.sr.is_set(Status::PGERR) {
            // Cleared by writing a 1.
            self.registers.sr.modify(Status::PGERR::SET);

            match self.state.get() {
                FlashState::Write => {
                    self.registers.cr.modify(Control::PG::CLEAR);
                    self.client.map(|client| {
                        self.buffer.take().map(|buffer| {
                            client.write_complete(buffer, Err(hil::flash::Error::FlashError));
                        });
                    });
                }
                FlashState::WriteOption => {
                    self.registers.cr.modify(Control::OPTPG::CLEAR);
                    self.client.map(|client| {
                        self.buffer.take().map(|buffer| {
                            client.write_complete(buffer, Err(hil::flash::Error::FlashError));
                        });
                    });
                }
                FlashState::Erase => {
                    self.client.map(|client| {
                        client.erase_complete(Err(hil::flash::Error::FlashError));
                    });
                }
                _ => {}
            }

            self.state.set(FlashState::Ready);
        }
    }

    pub fn program_halfword(&self) {
        self.buffer.take().map(|buffer| {
            let i = self.write_counter.get();

            let halfword: u16 = (buffer[i] as u16) << 0 | (buffer[i + 1] as u16) << 8;
            let page_addr = PAGE_START + self.page_number.get() * PAGE_SIZE;
            let address = page_addr + i;
            let location = unsafe { &*(address as *const VolatileCell<u16>) };
            location.set(halfword);

            self.buffer.replace(buffer);
        });
    }

    pub fn erase_page(&self, page_number: usize) -> Result<(), ErrorCode> {
        if page_number > 127 {
            return Err(ErrorCode::INVAL);
        }

        if self.is_locked() {
            self.unlock();
        }

        self.enable();
        self.state.set(FlashState::Erase);

        // Choose page erase mode.
        self.registers.cr.modify(Control::PER::SET);
        self.registers
            .ar
            .write(Address::FAR.val((PAGE_START + page_number * PAGE_SIZE) as u32));
        self.registers.cr.modify(Control::STRT::SET);

        Ok(())
    }

    pub fn erase_all(&self) -> Result<(), ErrorCode> {
        if self.is_locked() {
            self.unlock();
        }

        self.enable();
        self.state.set(FlashState::Erase);

        // Choose mass erase mode.
        self.registers.cr.modify(Control::MER::SET);
        self.registers.cr.modify(Control::STRT::SET);

        Ok(())
    }

    pub fn write_page(
        &self,
        page_number: usize,
        buffer: &'static mut StmF303Page,
    ) -> Result<(), (ErrorCode, &'static mut StmF303Page)> {
        if page_number > 127 {
            return Err((ErrorCode::INVAL, buffer));
        }

        if self.is_locked() {
            self.unlock();
        }

        self.enable();
        self.state.set(FlashState::Write);

        // Choose programming mode.
        self.registers.cr.modify(Control::PG::SET);

        self.buffer.replace(buffer);
        self.page_number.set(page_number);
        self.program_halfword();

        Ok(())
    }

    pub fn read_page(
        &self,
        page_number: usize,
        buffer: &'static mut StmF303Page,
    ) -> Result<(), (ErrorCode, &'static mut StmF303Page)> {
        if page_number > 127 {
            return Err((ErrorCode::INVAL, buffer));
        }

        let mut byte: *const u8 = (PAGE_START + page_number * PAGE_SIZE) as *const u8;
        unsafe {
            for i in 0..buffer.len() {
                buffer[i] = *byte;
                byte = byte.offset(1);
            }
        }

        self.buffer.replace(buffer);
        self.state.set(FlashState::Read);
        self.deferred_call.set();

        Ok(())
    }

    /// Allows programming the 8 option bytes:
    /// 0: RDP, 1: USER, 2: DATA0, 3:DATA1, 4. WRP0, 5: WRP1, 6.WRP2, 7. WRP3
    pub fn write_option(&self, byte_number: usize, value: u8) -> Result<(), ErrorCode> {
        if byte_number > 7 {
            return Err(ErrorCode::INVAL);
        }

        if self.is_locked() {
            self.unlock();
        }

        self.unlock_option();
        self.enable();
        self.state.set(FlashState::WriteOption);

        // Choose option byte programming mode.
        self.registers.cr.modify(Control::OPTPG::SET);

        let address = OPT_START + byte_number * 2;
        let location = unsafe { &*(address as *const VolatileCell<u16>) };
        let halfword: u16 = value as u16;
        location.set(halfword);

        Ok(())
    }

    pub fn erase_option(&self) -> Result<(), ErrorCode> {
        if self.is_locked() {
            self.unlock();
        }

        self.unlock_option();
        self.enable();
        self.state.set(FlashState::EraseOption);

        // Choose option byte erase mode.
        self.registers.cr.modify(Control::OPTER::SET);
        self.registers.cr.modify(Control::STRT::SET);

        Ok(())
    }
}

impl DeferredCallClient for Flash {
    fn register(&'static self) {
        self.deferred_call.register(self);
    }

    fn handle_deferred_call(&self) {
        self.handle_interrupt();
    }
}

impl<C: hil::flash::Client<Self>> hil::flash::HasClient<'static, C> for Flash {
    fn set_client(&self, client: &'static C) {
        self.client.set(client);
    }
}

impl hil::flash::Flash for Flash {
    type Page = StmF303Page;

    fn read_page(
        &self,
        page_number: usize,
        buf: &'static mut Self::Page,
    ) -> Result<(), (ErrorCode, &'static mut Self::Page)> {
        self.read_page(page_number, buf)
    }

    fn write_page(
        &self,
        page_number: usize,
        buf: &'static mut Self::Page,
    ) -> Result<(), (ErrorCode, &'static mut Self::Page)> {
        self.write_page(page_number, buf)
    }

    fn erase_page(&self, page_number: usize) -> Result<(), ErrorCode> {
        self.erase_page(page_number)
    }
}