Skip to main content

nrf52/
nvmc.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Non-Volatile Memory Controller
6//!
7//! Used in order read and write to internal flash.
8
9use core::cell::Cell;
10use core::ops::{Index, IndexMut};
11use kernel::ErrorCode;
12use kernel::deferred_call::{DeferredCall, DeferredCallClient};
13use kernel::hil;
14use kernel::utilities::StaticRef;
15use kernel::utilities::cells::OptionalCell;
16use kernel::utilities::cells::TakeCell;
17use tock_registers_v0::interfaces::{Readable, Writeable};
18use tock_registers_v0::registers::{ReadOnly, ReadWrite};
19use tock_registers_v0::{register_bitfields, register_structs};
20
21register_structs! {
22    pub NvmcRegisters {
23        /// Ready flag
24        (0x000 => ready: ReadOnly<u32, Ready::Register>),
25        (0x004 => _reserved0),
26        /// Ready flag
27        (0x014 => ready_next: ReadOnly<u32, Ready::Register>),
28        (0x018 => _reserved1),
29        /// Configuration register
30        (0x104 => config: ReadWrite<u32, Configuration::Register>),
31        /// Register for erasing a page in Code area
32        (0x108 => erasepage: ReadWrite<u32, ErasePage::Register>),
33        /// Register for erasing all non-volatile user memory
34        (0x10C => eraseall: ReadWrite<u32, EraseAll::Register>),
35        (0x110 => _reserved2),
36        /// Register for erasing User Information Configuration Registers
37        (0x114 => eraseuicr: ReadWrite<u32, EraseUicr::Register>),
38        (0x118 => _reserved3),
39        /// Configuration register
40        (0x140 => icachecnf: ReadWrite<u32, CacheConfiguration::Register>),
41        (0x144 => _reserved4),
42        /// Configuration register
43        (0x148 => ihit: ReadWrite<u32, CacheHit::Register>),
44        /// Configuration register
45        (0x14C => imiss: ReadWrite<u32, CacheMiss::Register>),
46        (0x150 => @END),
47    }
48}
49
50register_bitfields! [u32,
51    /// Ready flag
52    Ready [
53        /// NVMC is ready or busy
54        READY OFFSET(0) NUMBITS(1) [
55            /// NVMC is busy (on-going write or erase operation)
56            BUSY = 0,
57            /// NVMC is ready
58            READY = 1
59        ]
60    ],
61    /// Configuration register
62    Configuration [
63        /// Program memory access mode. It is strongly recommended
64        /// to only activate erase and write modes when they are actively
65        /// used. Enabling write or erase will invalidate the cache and keep
66        /// it invalidated.
67        WEN OFFSET(0) NUMBITS(2) [
68            /// Read only access
69            Ren = 0,
70            /// Write Enabled
71            Wen = 1,
72            /// Erase enabled
73            Een = 2
74        ]
75    ],
76    /// Register for erasing a page in Code area
77    ErasePage [
78        /// Register for starting erase of a page in Code area
79        ERASEPAGE OFFSET(0) NUMBITS(32) []
80    ],
81    /// Register for erasing all non-volatile user memory
82    EraseAll [
83        /// Erase all non-volatile memory including UICR registers. Note
84        /// that code erase has to be enabled by CONFIG.EEN before the
85        /// UICR can be erased
86        ERASEALL OFFSET(0) NUMBITS(1) [
87            /// No operation
88            NOOPERATION = 0,
89            /// Start chip erase
90            ERASE = 1
91        ]
92    ],
93    /// Register for erasing User Information Configuration Registers
94    EraseUicr [
95        /// Register starting erase of all User Information Configuration Registers.
96        /// Note that code erase has to be enabled by CONFIG.EEN before the UICR can be erased
97        ERASEUICR OFFSET(0) NUMBITS(1) [
98            /// No operation
99            NOOPERATION = 0,
100            /// Start erase of UICR
101            ERASE = 1
102        ]
103    ],
104    /// I-Code cache configuration register
105    CacheConfiguration [
106        /// Cache enabled
107        CACHEEN OFFSET(0) NUMBITS(1) [
108            /// Disable cache. Invalidates all cache entries
109            DISABLED = 0,
110            /// Enable cache
111            ENABLED = 1
112        ],
113        /// Cache profiling enable
114        CACHEPROFEN OFFSET(8) NUMBITS(1) [
115            /// Disable cache profiling
116            DISABLED = 0,
117            /// Enable cache profiling
118            ENABLED = 1
119        ]
120    ],
121    /// I-Code cache hit counter
122    CacheHit [
123        /// Number of cache hits
124        HITS OFFSET(0) NUMBITS(32) []
125    ],
126    /// I-Code cache miss counter
127    CacheMiss [
128        /// Number of cache misses
129        MISSES OFFSET(0) NUMBITS(32) []
130    ]
131];
132
133const PAGE_SIZE: usize = 4096;
134
135/// This is a wrapper around a u8 array that is sized to a single page for the
136/// nrf. Users of this module must pass an object of this type to use the
137/// `hil::flash::Flash` interface.
138///
139/// An example looks like:
140///
141/// ```rust
142/// # extern crate nrf52;
143/// # use nrf52::nvmc::NrfPage;
144/// # use kernel::static_init;
145///
146/// let pagebuffer = unsafe { static_init!(NrfPage, NrfPage::default()) };
147/// ```
148pub struct NrfPage(pub [u8; PAGE_SIZE]);
149
150impl Default for NrfPage {
151    fn default() -> Self {
152        Self([0; PAGE_SIZE])
153    }
154}
155impl NrfPage {
156    fn len(&self) -> usize {
157        self.0.len()
158    }
159}
160
161impl Index<usize> for NrfPage {
162    type Output = u8;
163
164    fn index(&self, idx: usize) -> &u8 {
165        &self.0[idx]
166    }
167}
168
169impl IndexMut<usize> for NrfPage {
170    fn index_mut(&mut self, idx: usize) -> &mut u8 {
171        &mut self.0[idx]
172    }
173}
174
175impl AsMut<[u8]> for NrfPage {
176    fn as_mut(&mut self) -> &mut [u8] {
177        &mut self.0
178    }
179}
180
181/// FlashState is used to track the current state and command of the flash.
182#[derive(Clone, Copy, PartialEq)]
183pub enum FlashState {
184    Ready, // Flash is ready to complete a command.
185    Read,  // Performing a read operation.
186    Write, // Performing a write operation.
187    Erase, // Performing an erase operation.
188}
189
190pub struct Nvmc {
191    registers: StaticRef<NvmcRegisters>,
192    client: OptionalCell<&'static dyn hil::flash::Client<Nvmc>>,
193    buffer: TakeCell<'static, NrfPage>,
194    state: Cell<FlashState>,
195    deferred_call: DeferredCall,
196}
197
198impl Nvmc {
199    pub fn new(registers: StaticRef<NvmcRegisters>) -> Self {
200        Self {
201            registers,
202            client: OptionalCell::empty(),
203            buffer: TakeCell::empty(),
204            state: Cell::new(FlashState::Ready),
205            deferred_call: DeferredCall::new(),
206        }
207    }
208
209    /// Configure the NVMC to allow writes to flash.
210    pub fn configure_writeable(&self) {
211        self.registers.config.write(Configuration::WEN::Wen);
212    }
213
214    pub fn configure_eraseable(&self) {
215        self.registers.config.write(Configuration::WEN::Een);
216    }
217
218    pub fn erase_uicr(&self) {
219        self.registers.config.write(Configuration::WEN::Een);
220        while !self.is_ready() {}
221        self.registers
222            .erasepage
223            .write(ErasePage::ERASEPAGE.val(0x10001000));
224        while !self.is_ready() {}
225    }
226
227    /// Check if there is an ongoing operation with the NVMC peripheral.
228    pub fn is_ready(&self) -> bool {
229        self.registers.ready.is_set(Ready::READY)
230    }
231
232    pub fn handle_interrupt(&self) {
233        let state = self.state.get();
234        self.state.set(FlashState::Ready);
235
236        match state {
237            FlashState::Read => {
238                self.client.map(|client| {
239                    self.buffer.take().map(|buffer| {
240                        client.read_complete(buffer, Ok(()));
241                    });
242                });
243            }
244            FlashState::Write => {
245                self.client.map(|client| {
246                    self.buffer.take().map(|buffer| {
247                        client.write_complete(buffer, Ok(()));
248                    });
249                });
250            }
251            FlashState::Erase => {
252                self.client.map(|client| {
253                    client.erase_complete(Ok(()));
254                });
255            }
256            _ => {}
257        }
258    }
259
260    fn is_page_blank(&self, page_number: usize) -> bool {
261        let address = (page_number * PAGE_SIZE) as *const u32;
262        for i in 0..(PAGE_SIZE / 4) {
263            if unsafe { core::ptr::read(address.add(i)) } != 0xFFFFFFFF {
264                return false;
265            }
266        }
267        true
268    }
269
270    fn erase_page_helper(&self, page_number: usize) {
271        // Put the NVMC in erase mode.
272        self.registers.config.write(Configuration::WEN::Een);
273
274        // Tell the NVMC to erase the correct page by passing in the correct
275        // address.
276        self.registers
277            .erasepage
278            .write(ErasePage::ERASEPAGE.val((page_number * PAGE_SIZE) as u32));
279
280        // Make sure that the NVMC is done. The CPU should be blocked while the
281        // erase is happening, but it doesn't hurt to check too.
282        while !self.registers.ready.is_set(Ready::READY) {}
283    }
284
285    fn read_range(
286        &self,
287        page_number: usize,
288        buffer: &'static mut NrfPage,
289    ) -> Result<(), (ErrorCode, &'static mut NrfPage)> {
290        // Actually do a copy from flash into the buffer.
291        let mut byte: *const u8 = (page_number * PAGE_SIZE) as *const u8;
292        unsafe {
293            for i in 0..buffer.len() {
294                buffer[i] = *byte;
295                byte = byte.add(1);
296            }
297        }
298
299        // Hold on to the buffer for the callback.
300        self.buffer.replace(buffer);
301
302        // Mark the need for an interrupt so we can call the read done
303        // callback.
304        self.state.set(FlashState::Read);
305        self.deferred_call.set();
306
307        Ok(())
308    }
309
310    fn write_page(
311        &self,
312        page_number: usize,
313        data: &'static mut NrfPage,
314    ) -> Result<(), (ErrorCode, &'static mut NrfPage)> {
315        // Need to erase the page if the page is not filled
316        // with 0xFF.
317        if !self.is_page_blank(page_number) {
318            self.erase_page_helper(page_number);
319        }
320
321        // Put the NVMC in write mode.
322        self.registers.config.write(Configuration::WEN::Wen);
323
324        for i in (0..data.len()).step_by(4) {
325            let word: u32 = (data[i + 0] as u32) << 0
326                | (data[i + 1] as u32) << 8
327                | (data[i + 2] as u32) << 16
328                | (data[i + 3] as u32) << 24;
329
330            let address = ((page_number * PAGE_SIZE) + i) as u32;
331            let location = unsafe { &*(address as *const ReadWrite<u32>) };
332            location.set(word);
333            while !self.registers.ready.is_set(Ready::READY) {}
334        }
335
336        // Make sure that the NVMC is done. The CPU should be blocked while the
337        // write is happening, but it doesn't hurt to check too.
338        while !self.registers.ready.is_set(Ready::READY) {}
339
340        // Save the buffer so we can return it with the callback.
341        self.buffer.replace(data);
342
343        // Mark the need for an interrupt so we can call the write done
344        // callback.
345        self.state.set(FlashState::Write);
346        self.deferred_call.set();
347
348        Ok(())
349    }
350
351    fn erase_page(&self, page_number: usize) -> Result<(), ErrorCode> {
352        // Do the basic erase.
353        if !self.is_page_blank(page_number) {
354            self.erase_page_helper(page_number);
355        }
356
357        // Mark that we want to trigger a pseudo interrupt so that we can issue
358        // the callback even though the NVMC is completely blocking.
359        self.state.set(FlashState::Erase);
360        self.deferred_call.set();
361
362        Ok(())
363    }
364}
365
366impl<C: hil::flash::Client<Self>> hil::flash::HasClient<'static, C> for Nvmc {
367    fn set_client(&self, client: &'static C) {
368        self.client.set(client);
369    }
370}
371
372impl hil::flash::Flash for Nvmc {
373    type Page = NrfPage;
374
375    fn read_page(
376        &self,
377        page_number: usize,
378        buf: &'static mut Self::Page,
379    ) -> Result<(), (ErrorCode, &'static mut Self::Page)> {
380        self.read_range(page_number, buf)
381    }
382
383    fn write_page(
384        &self,
385        page_number: usize,
386        buf: &'static mut Self::Page,
387    ) -> Result<(), (ErrorCode, &'static mut Self::Page)> {
388        self.write_page(page_number, buf)
389    }
390
391    fn erase_page(&self, page_number: usize) -> Result<(), ErrorCode> {
392        self.erase_page(page_number)
393    }
394}
395
396impl DeferredCallClient for Nvmc {
397    fn handle_deferred_call(&self) {
398        self.handle_interrupt();
399    }
400
401    fn register(&'static self) {
402        self.deferred_call.register(self);
403    }
404}