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
//! Non-Volatile Memory Controller (NVMC, AKA internal flash) driver.

use core::{ptr, slice};

use embassy_hal_internal::{into_ref, PeripheralRef};
use embedded_storage::nor_flash::{
    ErrorType, MultiwriteNorFlash, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash,
};

use crate::peripherals::NVMC;
use crate::{pac, Peripheral};

#[cfg(not(feature = "_nrf5340-net"))]
/// Erase size of NVMC flash in bytes.
pub const PAGE_SIZE: usize = 4096;
#[cfg(feature = "_nrf5340-net")]
/// Erase size of NVMC flash in bytes.
pub const PAGE_SIZE: usize = 2048;

/// Size of NVMC flash in bytes.
pub const FLASH_SIZE: usize = crate::chip::FLASH_SIZE;

/// Error type for NVMC operations.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// Operation using a location not in flash.
    OutOfBounds,
    /// Unaligned operation or using unaligned buffers.
    Unaligned,
}

impl NorFlashError for Error {
    fn kind(&self) -> NorFlashErrorKind {
        match self {
            Self::OutOfBounds => NorFlashErrorKind::OutOfBounds,
            Self::Unaligned => NorFlashErrorKind::NotAligned,
        }
    }
}

/// Non-Volatile Memory Controller (NVMC) that implements the `embedded-storage` traits.
pub struct Nvmc<'d> {
    _p: PeripheralRef<'d, NVMC>,
}

impl<'d> Nvmc<'d> {
    /// Create Nvmc driver.
    pub fn new(_p: impl Peripheral<P = NVMC> + 'd) -> Self {
        into_ref!(_p);
        Self { _p }
    }

    fn regs() -> &'static pac::nvmc::RegisterBlock {
        unsafe { &*pac::NVMC::ptr() }
    }

    fn wait_ready(&mut self) {
        let p = Self::regs();
        while p.ready.read().ready().is_busy() {}
    }

    #[cfg(not(any(feature = "_nrf9160", feature = "_nrf5340")))]
    fn wait_ready_write(&mut self) {
        self.wait_ready();
    }

    #[cfg(any(feature = "_nrf9160", feature = "_nrf5340"))]
    fn wait_ready_write(&mut self) {
        let p = Self::regs();
        while p.readynext.read().readynext().is_busy() {}
    }

    #[cfg(not(any(feature = "_nrf9160", feature = "_nrf5340")))]
    fn erase_page(&mut self, page_addr: u32) {
        Self::regs().erasepage().write(|w| unsafe { w.bits(page_addr) });
    }

    #[cfg(any(feature = "_nrf9160", feature = "_nrf5340"))]
    fn erase_page(&mut self, page_addr: u32) {
        let first_page_word = page_addr as *mut u32;
        unsafe {
            first_page_word.write_volatile(0xFFFF_FFFF);
        }
    }

    fn enable_erase(&self) {
        #[cfg(not(feature = "_ns"))]
        Self::regs().config.write(|w| w.wen().een());
        #[cfg(feature = "_ns")]
        Self::regs().configns.write(|w| w.wen().een());
    }

    fn enable_read(&self) {
        #[cfg(not(feature = "_ns"))]
        Self::regs().config.write(|w| w.wen().ren());
        #[cfg(feature = "_ns")]
        Self::regs().configns.write(|w| w.wen().ren());
    }

    fn enable_write(&self) {
        #[cfg(not(feature = "_ns"))]
        Self::regs().config.write(|w| w.wen().wen());
        #[cfg(feature = "_ns")]
        Self::regs().configns.write(|w| w.wen().wen());
    }
}

impl<'d> MultiwriteNorFlash for Nvmc<'d> {}

impl<'d> ErrorType for Nvmc<'d> {
    type Error = Error;
}

impl<'d> ReadNorFlash for Nvmc<'d> {
    const READ_SIZE: usize = 1;

    fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
        if offset as usize >= FLASH_SIZE || offset as usize + bytes.len() > FLASH_SIZE {
            return Err(Error::OutOfBounds);
        }

        let flash_data = unsafe { slice::from_raw_parts(offset as *const u8, bytes.len()) };
        bytes.copy_from_slice(flash_data);
        Ok(())
    }

    fn capacity(&self) -> usize {
        FLASH_SIZE
    }
}

impl<'d> NorFlash for Nvmc<'d> {
    const WRITE_SIZE: usize = 4;
    const ERASE_SIZE: usize = PAGE_SIZE;

    fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
        if to < from || to as usize > FLASH_SIZE {
            return Err(Error::OutOfBounds);
        }
        if from as usize % PAGE_SIZE != 0 || to as usize % PAGE_SIZE != 0 {
            return Err(Error::Unaligned);
        }

        self.enable_erase();
        self.wait_ready();

        for page_addr in (from..to).step_by(PAGE_SIZE) {
            self.erase_page(page_addr);
            self.wait_ready();
        }

        self.enable_read();
        self.wait_ready();

        Ok(())
    }

    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        if offset as usize + bytes.len() > FLASH_SIZE {
            return Err(Error::OutOfBounds);
        }
        if offset as usize % 4 != 0 || bytes.len() as usize % 4 != 0 {
            return Err(Error::Unaligned);
        }

        self.enable_write();
        self.wait_ready();

        unsafe {
            let p_src = bytes.as_ptr() as *const u32;
            let p_dst = offset as *mut u32;
            let words = bytes.len() / 4;
            for i in 0..words {
                let w = ptr::read_unaligned(p_src.add(i));
                ptr::write_volatile(p_dst.add(i), w);
                self.wait_ready_write();
            }
        }

        self.enable_read();
        self.wait_ready();

        Ok(())
    }
}