Skip to main content

esp_hal/rtc_cntl/
retention_memory.rs

1//! Memory that the hardware writes while a power domain has no power, and its one-shot install.
2
3use core::{
4    cell::UnsafeCell,
5    mem::MaybeUninit,
6    ptr::{self, NonNull},
7};
8
9use portable_atomic::{AtomicPtr, Ordering};
10use static_cell::ConstStaticCell;
11
12/// Storage for [`RetentionMemory`].
13///
14/// This storage must be placed in `#[ram(reclaimed, unstable(zeroed))]`, then a static mutable
15/// reference to [`RetentionMemory`] can be taken out of it.
16#[instability::unstable]
17pub struct RetentionStorage<const SIZE: usize> {
18    inner: ConstStaticCell<RetentionMemory<SIZE>>,
19}
20
21impl<const SIZE: usize> RetentionStorage<SIZE> {
22    /// Creates storage for the retention memory.
23    #[instability::unstable]
24    pub const fn new() -> Self {
25        Self {
26            inner: ConstStaticCell::new(RetentionMemory {
27                storage: UnsafeCell::new(MaybeUninit::uninit()),
28            }),
29        }
30    }
31
32    /// Takes the reference to the retention memory.
33    ///
34    /// Can only be called once.
35    #[instability::unstable]
36    pub fn take(&'static self) -> &'static mut RetentionMemory<SIZE> {
37        self.inner.take()
38    }
39}
40
41#[instability::unstable]
42impl<const SIZE: usize> Default for RetentionStorage<SIZE> {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48// SAFETY: ConstStaticCell is a `MaybeUninit` buffer, and an AtomicBool strapped together,
49// both are safe to be zero-initialized.
50unsafe impl<const SIZE: usize> bytemuck::Zeroable for RetentionStorage<SIZE> {}
51
52/// Memory that the hardware writes while a power domain has no power.
53///
54/// The hardware writes this memory, so the type gives no way to read or write its contents through
55/// safe Rust.
56///
57/// The memory must be in internal RAM that stays powered across light sleep. The
58/// [`#[ram(reclaimed)]`][crate::ram] attribute places a static inside the range that the
59/// retention DMA reaches, on chips that use the retention DMA.
60#[repr(align(16))]
61#[instability::unstable]
62pub struct RetentionMemory<const SIZE: usize> {
63    storage: UnsafeCell<MaybeUninit<[u8; SIZE]>>,
64}
65
66/// The reason why a driver refused the retention memory.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68#[cfg_attr(feature = "defmt", derive(defmt::Format))]
69#[instability::unstable]
70#[non_exhaustive]
71pub enum RetentionMemoryError {
72    /// The memory is not inside the range that the retention DMA reaches.
73    #[cfg(not(cpu_retention = "software"))]
74    OutOfRange,
75    /// The driver has retention memory already.
76    AlreadyInstalled,
77}
78
79#[instability::unstable]
80impl core::error::Error for RetentionMemoryError {}
81
82#[instability::unstable]
83impl core::fmt::Display for RetentionMemoryError {
84    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
85        match self {
86            #[cfg(not(cpu_retention = "software"))]
87            Self::OutOfRange => write!(
88                f,
89                "the retention DMA cannot reach the memory, place it in `#[ram(reclaimed)]`"
90            ),
91            Self::AlreadyInstalled => write!(f, "retention memory is installed already"),
92        }
93    }
94}
95
96/// Holds the [`RetentionMemory`] of one driver for the life of the program.
97#[doc(hidden)]
98#[instability::unstable]
99pub struct RetentionSlot<const SIZE: usize> {
100    memory: AtomicPtr<u8>,
101}
102
103impl<const SIZE: usize> RetentionSlot<SIZE> {
104    /// Creates a slot without memory.
105    #[instability::unstable]
106    pub const fn new() -> Self {
107        Self {
108            memory: AtomicPtr::new(ptr::null_mut()),
109        }
110    }
111
112    /// Keeps the memory for the life of the program.
113    ///
114    /// # Errors
115    ///
116    /// Returns [`RetentionMemoryError`] if the slot holds memory already, or if the memory is not
117    /// inside the range that the retention DMA reaches.
118    #[instability::unstable]
119    pub fn install(
120        &self,
121        memory: &'static mut RetentionMemory<SIZE>,
122    ) -> Result<(), RetentionMemoryError> {
123        let memory = memory.storage.get().cast::<u8>();
124
125        #[cfg(not(cpu_retention = "software"))]
126        {
127            const MEM_START: usize = property!("sleep.cpu_retention_mem_start");
128            const MEM_END: usize = property!("sleep.cpu_retention_mem_end");
129
130            let start = memory as usize;
131            if start < MEM_START || start + SIZE > MEM_END {
132                return Err(RetentionMemoryError::OutOfRange);
133            }
134        }
135
136        self.memory
137            .compare_exchange(ptr::null_mut(), memory, Ordering::AcqRel, Ordering::Acquire)
138            .map(|_| ())
139            .map_err(|_| RetentionMemoryError::AlreadyInstalled)
140    }
141
142    /// Returns the start of the memory, if the slot holds it.
143    #[instability::unstable]
144    pub fn get(&self) -> Option<NonNull<u8>> {
145        NonNull::new(self.memory.load(Ordering::Acquire))
146    }
147}
148
149#[instability::unstable]
150impl<const SIZE: usize> Default for RetentionSlot<SIZE> {
151    fn default() -> Self {
152        Self::new()
153    }
154}