embassy_stm32/rcc/
bd.rs

1use core::sync::atomic::{compiler_fence, Ordering};
2
3use crate::pac::common::{Reg, RW};
4pub use crate::pac::rcc::vals::Rtcsel as RtcClockSource;
5use crate::time::Hertz;
6
7#[cfg(any(stm32f0, stm32f1, stm32f3))]
8pub const LSI_FREQ: Hertz = Hertz(40_000);
9#[cfg(not(any(stm32f0, stm32f1, stm32f3)))]
10pub const LSI_FREQ: Hertz = Hertz(32_000);
11
12#[allow(dead_code)]
13#[derive(Clone, Copy)]
14pub enum LseMode {
15    Oscillator(LseDrive),
16    Bypass,
17}
18
19#[derive(Clone, Copy)]
20pub struct LseConfig {
21    pub frequency: Hertz,
22    pub mode: LseMode,
23    /// If peripherals other than RTC/TAMP or RCC functions need the lse this bit must be set
24    #[cfg(any(rcc_l5, rcc_u5, rcc_wle, rcc_wl5, rcc_wba))]
25    pub peripherals_clocked: bool,
26}
27
28#[allow(dead_code)]
29#[derive(Default, Clone, Copy)]
30pub enum LseDrive {
31    #[cfg(not(stm32h5))] // ES0565: LSE Low drive mode is not functional
32    Low = 0,
33    MediumLow = 0x01,
34    #[default]
35    MediumHigh = 0x02,
36    High = 0x03,
37}
38
39// All families but these have the LSEDRV register
40#[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f410, rcc_l1)))]
41impl From<LseDrive> for crate::pac::rcc::vals::Lsedrv {
42    fn from(value: LseDrive) -> Self {
43        use crate::pac::rcc::vals::Lsedrv;
44
45        match value {
46            #[cfg(not(stm32h5))] // ES0565: LSE Low drive mode is not functional
47            LseDrive::Low => Lsedrv::LOW,
48            LseDrive::MediumLow => Lsedrv::MEDIUM_LOW,
49            LseDrive::MediumHigh => Lsedrv::MEDIUM_HIGH,
50            LseDrive::High => Lsedrv::HIGH,
51        }
52    }
53}
54
55#[cfg(not(any(rtc_v2l0, rtc_v2l1, stm32c0)))]
56type Bdcr = crate::pac::rcc::regs::Bdcr;
57#[cfg(any(rtc_v2l0, rtc_v2l1))]
58type Bdcr = crate::pac::rcc::regs::Csr;
59#[cfg(any(stm32c0))]
60type Bdcr = crate::pac::rcc::regs::Csr1;
61
62#[cfg(any(stm32c0))]
63fn unlock() {}
64
65#[cfg(not(any(stm32c0)))]
66fn unlock() {
67    #[cfg(any(stm32f0, stm32f1, stm32f2, stm32f3, stm32l0, stm32l1))]
68    let cr = crate::pac::PWR.cr();
69    #[cfg(not(any(stm32f0, stm32f1, stm32f2, stm32f3, stm32l0, stm32l1, stm32u5, stm32h5, stm32wba)))]
70    let cr = crate::pac::PWR.cr1();
71    #[cfg(any(stm32u5, stm32h5, stm32wba))]
72    let cr = crate::pac::PWR.dbpcr();
73
74    cr.modify(|w| w.set_dbp(true));
75    while !cr.read().dbp() {}
76}
77
78fn bdcr() -> Reg<Bdcr, RW> {
79    #[cfg(any(rtc_v2l0, rtc_v2l1))]
80    return crate::pac::RCC.csr();
81    #[cfg(not(any(rtc_v2l0, rtc_v2l1, stm32c0)))]
82    return crate::pac::RCC.bdcr();
83    #[cfg(any(stm32c0))]
84    return crate::pac::RCC.csr1();
85}
86
87#[derive(Clone, Copy)]
88pub struct LsConfig {
89    pub rtc: RtcClockSource,
90    pub lsi: bool,
91    pub lse: Option<LseConfig>,
92}
93
94impl LsConfig {
95    /// Creates an [`LsConfig`] using the LSI when possible.
96    pub const fn new() -> Self {
97        // on L5, just the fact that LSI is enabled makes things crash.
98        // TODO: investigate.
99
100        #[cfg(not(stm32l5))]
101        return Self::default_lsi();
102        #[cfg(stm32l5)]
103        return Self::off();
104    }
105
106    pub const fn default_lse() -> Self {
107        Self {
108            rtc: RtcClockSource::LSE,
109            lse: Some(LseConfig {
110                frequency: Hertz(32_768),
111                mode: LseMode::Oscillator(LseDrive::MediumHigh),
112                #[cfg(any(rcc_l5, rcc_u5, rcc_wle, rcc_wl5, rcc_wba))]
113                peripherals_clocked: false,
114            }),
115            lsi: false,
116        }
117    }
118
119    pub const fn default_lsi() -> Self {
120        Self {
121            rtc: RtcClockSource::LSI,
122            lsi: true,
123            lse: None,
124        }
125    }
126
127    pub const fn off() -> Self {
128        Self {
129            rtc: RtcClockSource::DISABLE,
130            lsi: false,
131            lse: None,
132        }
133    }
134}
135
136impl Default for LsConfig {
137    fn default() -> Self {
138        Self::new()
139    }
140}
141
142impl LsConfig {
143    pub(crate) fn init(&self) -> Option<Hertz> {
144        let rtc_clk = match self.rtc {
145            RtcClockSource::LSI => {
146                assert!(self.lsi);
147                Some(LSI_FREQ)
148            }
149            RtcClockSource::LSE => Some(self.lse.as_ref().unwrap().frequency),
150            RtcClockSource::DISABLE => None,
151            _ => todo!(),
152        };
153
154        let (lse_en, lse_byp, lse_drv) = match &self.lse {
155            Some(c) => match c.mode {
156                LseMode::Oscillator(lse_drv) => (true, false, Some(lse_drv)),
157                LseMode::Bypass => (true, true, None),
158            },
159            None => (false, false, None),
160        };
161        #[cfg(any(rcc_l5, rcc_u5, rcc_wle, rcc_wl5, rcc_wba))]
162        let lse_sysen = if let Some(lse) = self.lse {
163            Some(lse.peripherals_clocked)
164        } else {
165            None
166        };
167        #[cfg(rcc_u0)]
168        let lse_sysen = Some(lse_en);
169
170        _ = lse_drv; // not all chips have it.
171
172        // Disable backup domain write protection
173        unlock();
174
175        if self.lsi {
176            #[cfg(any(stm32u5, stm32h5, stm32wba))]
177            let csr = crate::pac::RCC.bdcr();
178            #[cfg(not(any(stm32u5, stm32h5, stm32wba, stm32c0)))]
179            let csr = crate::pac::RCC.csr();
180            #[cfg(any(stm32c0))]
181            let csr = crate::pac::RCC.csr2();
182
183            #[cfg(not(any(rcc_wb, rcc_wba)))]
184            csr.modify(|w| w.set_lsion(true));
185
186            #[cfg(any(rcc_wb, rcc_wba))]
187            csr.modify(|w| w.set_lsi1on(true));
188
189            #[cfg(not(any(rcc_wb, rcc_wba)))]
190            while !csr.read().lsirdy() {}
191
192            #[cfg(any(rcc_wb, rcc_wba))]
193            while !csr.read().lsi1rdy() {}
194        }
195
196        // backup domain configuration (LSEON, RTCEN, RTCSEL) is kept across resets.
197        // once set, changing it requires a backup domain reset.
198        // first check if the configuration matches what we want.
199
200        // check if it's already enabled and in the source we want.
201        let reg = bdcr().read();
202        let mut ok = true;
203        ok &= reg.rtcsel() == self.rtc;
204        #[cfg(not(rcc_wba))]
205        {
206            ok &= reg.rtcen() == (self.rtc != RtcClockSource::DISABLE);
207        }
208        ok &= reg.lseon() == lse_en;
209        ok &= reg.lsebyp() == lse_byp;
210        #[cfg(any(rcc_l5, rcc_u5, rcc_wle, rcc_wl5, rcc_wba, rcc_u0))]
211        if let Some(lse_sysen) = lse_sysen {
212            ok &= reg.lsesysen() == lse_sysen;
213        }
214        #[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f410, rcc_l1)))]
215        if let Some(lse_drv) = lse_drv {
216            ok &= reg.lsedrv() == lse_drv.into();
217        }
218
219        // if configuration is OK, we're done.
220        if ok {
221            trace!("BDCR ok: {:08x}", bdcr().read().0);
222            return rtc_clk;
223        }
224
225        // If not OK, reset backup domain and configure it.
226        #[cfg(not(any(rcc_l0, rcc_l0_v2, rcc_l1, stm32h5, stm32h7rs, stm32c0)))]
227        {
228            bdcr().modify(|w| w.set_bdrst(true));
229            bdcr().modify(|w| w.set_bdrst(false));
230        }
231        // H5 has a terrible, terrible errata: 'SRAM2 is erased when the backup domain is reset'
232        // pending a more sane sane way to handle this, just don't reset BD for now.
233        // This means the RTCSEL write below will have no effect, only if it has already been written
234        // after last power-on. Since it's uncommon to dynamically change RTCSEL, this is better than
235        // letting half our RAM go magically *poof*.
236        // STM32H503CB/EB/KB/RB device errata - 2.2.8 SRAM2 unduly erased upon a backup domain reset
237        // STM32H562xx/563xx/573xx device errata - 2.2.14 SRAM2 is erased when the backup domain is reset
238        //#[cfg(any(stm32h5, stm32h7rs))]
239        #[cfg(any(stm32h7rs))]
240        {
241            bdcr().modify(|w| w.set_vswrst(true));
242            bdcr().modify(|w| w.set_vswrst(false));
243        }
244        #[cfg(any(stm32c0, stm32l0))]
245        {
246            bdcr().modify(|w| w.set_rtcrst(true));
247            bdcr().modify(|w| w.set_rtcrst(false));
248        }
249
250        if lse_en {
251            bdcr().modify(|w| {
252                #[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f410, rcc_l1)))]
253                if let Some(lse_drv) = lse_drv {
254                    w.set_lsedrv(lse_drv.into());
255                }
256                w.set_lsebyp(lse_byp);
257                w.set_lseon(true);
258            });
259
260            while !bdcr().read().lserdy() {}
261
262            #[cfg(any(rcc_l5, rcc_u5, rcc_wle, rcc_wl5, rcc_wba, rcc_u0))]
263            if let Some(lse_sysen) = lse_sysen {
264                bdcr().modify(|w| {
265                    w.set_lsesysen(lse_sysen);
266                });
267
268                if lse_sysen {
269                    while !bdcr().read().lsesysrdy() {}
270                }
271            }
272        }
273
274        if self.rtc != RtcClockSource::DISABLE {
275            bdcr().modify(|w| {
276                #[cfg(any(rtc_v2h7, rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
277                assert!(!w.lsecsson(), "RTC is not compatible with LSE CSS, yet.");
278
279                #[cfg(not(rcc_wba))]
280                w.set_rtcen(true);
281                w.set_rtcsel(self.rtc);
282            });
283        }
284
285        trace!("BDCR configured: {:08x}", bdcr().read().0);
286
287        compiler_fence(Ordering::SeqCst);
288
289        rtc_clk
290    }
291}