Skip to main content

esp_hal/rtc_cntl/sleep/
esp32h2.rs

1use core::ops::Not;
2
3use crate::{
4    peripherals::{LP_AON, PMU},
5    rtc_cntl::{
6        Rtc,
7        rtc::{HpSysCntlReg, HpSysPower, LpSysPower},
8        sleep::{
9            SleepKind,
10            pmu_common::{SleepTimeConfig, request_sleep},
11        },
12    },
13    soc::{
14        clocks::{self, ClockTree, CpuClkConfig, HpRootClkConfig},
15        xtal32k,
16    },
17};
18
19/// Configuration for controlling the behavior during sleep modes.
20#[derive(Clone, Copy)]
21// Note: from all the fields defined in ESP-IDF's `pmu_sleep_analog_config_t`
22// the only one documented in Hardware Technical Reference Manual is `hp_sys.analog.xpd`
23// (corresponds to `PMU_HP_ACTIVE_HP_REGULATOR_XPD` in the Manual). Therefore only this
24// field is stored as bool without any nested structures.
25pub struct AnalogSleepConfig {
26    /// High-power system configuration.
27    pub regulator_xpd: bool,
28}
29
30impl AnalogSleepConfig {
31    fn defaults_deep_sleep() -> Self {
32        Self {
33            // PMU_SLEEP_ANALOG_DSLP_CONFIG_DEFAULT
34            regulator_xpd: false,
35        }
36    }
37
38    fn defaults_light_sleep() -> Self {
39        Self {
40            // PMU_SLEEP_ANALOG_LSLP_CONFIG_DEFAULT
41            regulator_xpd: true,
42        }
43    }
44
45    fn apply(&self) {
46        // based on pmu_sleep_analog_init, with undocumented registers omitted
47        PMU::regs().hp_sleep_hp_regulator0().modify(|_, w| {
48            w.hp_sleep_hp_regulator_xpd() // pmu_ll_hp_set_regulator_xpd
49                .bit(self.regulator_xpd)
50        });
51    }
52}
53
54/// Configuration for controlling the behavior of digital peripherals during
55/// sleep modes.
56#[derive(Clone, Copy)]
57// pmu_sleep_digital_config_t
58pub struct DigitalSleepConfig {
59    /// High-power system control register configuration.
60    pub syscntl: HpSysCntlReg,
61    /// ICG function control flags.
62    pub icg_func: u32,
63    /// Indicates whether deep sleep mode is requested.
64    pub deep_sleep: bool,
65}
66
67impl DigitalSleepConfig {
68    fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self {
69        Self {
70            // PMU_SLEEP_DIGITAL_LSLP_CONFIG_DEFAULT
71            syscntl: {
72                let mut cfg = HpSysCntlReg::default();
73
74                cfg.set_dig_pad_slp_sel(pd_flags.pd_top().not());
75                cfg.set_dig_pause_wdt(true);
76
77                cfg
78            },
79            // ESP-IDF ungates only the clocks that `esp_sleep_clock_config` requested. No esp-hal
80            // driver needs a digital clock during light sleep.
81            icg_func: 0,
82            deep_sleep: false,
83        }
84    }
85
86    fn defaults_deep_sleep() -> Self {
87        Self {
88            // PMU_SLEEP_DIGITAL_DSLP_CONFIG_DEFAULT
89            syscntl: {
90                let mut cfg = HpSysCntlReg::default();
91
92                cfg.set_dig_pause_wdt(true);
93
94                cfg
95            },
96            icg_func: 0,
97            deep_sleep: true,
98        }
99    }
100
101    fn apply(&self) {
102        // pmu_sleep_digital_init
103        PMU::regs().hp_sleep_sysclk().modify(|_, w| {
104            w.hp_sleep_icg_sys_clock_en().bit(self.icg_func != 0) // pmu_ll_hp_set_icg_sysclk_enable
105        });
106        PMU::regs().hp_sleep_icg_hp_func().modify(|_, w| unsafe {
107            w.hp_sleep_dig_icg_func_en().bits(self.icg_func) // pmu_ll_hp_set_icg_func
108        });
109        PMU::regs().hp_sleep_hp_sys_cntl().modify(|_, w| {
110            w.hp_sleep_dig_pause_wdt().bit(self.syscntl.dig_pause_wdt());
111            w.hp_sleep_dig_cpu_stall().set_bit();
112            if !self.deep_sleep {
113                w.hp_sleep_dig_pad_slp_sel()
114                    .bit(self.syscntl.dig_pad_slp_sel()); // pmu_ll_hp_set_dig_pad_slp_sel
115            }
116            w
117        });
118    }
119}
120
121/// Configuration for controlling the power settings of high-power and low-power
122/// systems during sleep modes.
123#[derive(Clone, Copy)]
124// pmu_sleep_power_config_t
125pub struct PowerSleepConfig {
126    /// Power configuration for the high-power system during sleep.
127    pub hp_sys: HpSysPower,
128    /// Power configuration for the low-power system when it is active.
129    pub lp_sys_active: LpSysPower,
130    /// Power configuration for the low-power system when it is in sleep mode.
131    pub lp_sys_sleep: LpSysPower,
132}
133
134impl PowerSleepConfig {
135    fn defaults(pd_flags: PowerDownFlags) -> Self {
136        let mut this = Self {
137            hp_sys: HpSysPower::default(),
138            lp_sys_active: LpSysPower::default(),
139            lp_sys_sleep: LpSysPower::default(),
140        };
141        this.apply_flags(pd_flags);
142        this
143    }
144
145    fn apply_flags(&mut self, pd_flags: PowerDownFlags) {
146        // PMU_SLEEP_POWER_CONFIG_DEFAULT
147        self.hp_sys
148            .dig_power
149            .set_vdd_spi_pd_en(pd_flags.pd_vddsdio());
150        self.hp_sys.dig_power.set_modem_pd_en(pd_flags.pd_modem());
151        self.hp_sys.dig_power.set_cpu_pd_en(pd_flags.pd_cpu());
152        self.hp_sys.dig_power.set_top_pd_en(pd_flags.pd_top());
153
154        self.hp_sys.clk.set_i2c_iso_en(true);
155        self.hp_sys.clk.set_i2c_retention(true);
156        self.hp_sys.clk.set_xpd_bbpll(false);
157
158        self.hp_sys.xtal.set_xpd_xtal(pd_flags.pd_xtal().not());
159
160        self.lp_sys_active
161            .clk_power
162            .set_xpd_xtal32k(xtal32k::use_xtal32k());
163        self.lp_sys_active.clk_power.set_xpd_fosc(true);
164
165        self.lp_sys_sleep.dig_power.set_mem_dslp(true);
166        self.lp_sys_sleep.dig_power.set_vddbat_mode(0);
167        self.lp_sys_sleep.dig_power.set_bod_source_sel(true);
168
169        self.lp_sys_sleep
170            .clk_power
171            .set_xpd_xtal32k(pd_flags.pd_xtal32k().not());
172        self.lp_sys_sleep
173            .clk_power
174            .set_xpd_fosc(pd_flags.pd_rc_fast().not());
175
176        self.lp_sys_sleep
177            .xtal
178            .set_xpd_xtal(pd_flags.pd_xtal().not());
179    }
180
181    fn apply(&self) {
182        // pmu_sleep_power_init
183        // HP SLEEP (hp_sleep_*)
184        PMU::regs()
185            .hp_sleep_dig_power()
186            .modify(|_, w| unsafe { w.bits(self.hp_sys.dig_power.0) });
187        PMU::regs()
188            .hp_sleep_hp_ck_power()
189            .modify(|_, w| unsafe { w.bits(self.hp_sys.clk.0) });
190        PMU::regs()
191            .hp_sleep_xtal()
192            .modify(|_, w| w.hp_sleep_xpd_xtal().bit(self.hp_sys.xtal.xpd_xtal()));
193
194        // LP ACTIVE (hp_sleep_lp_*)
195        PMU::regs()
196            .hp_sleep_lp_dig_power()
197            .modify(|_, w| unsafe { w.bits(self.lp_sys_active.dig_power.0) });
198        PMU::regs()
199            .hp_sleep_lp_ck_power()
200            .modify(|_, w| unsafe { w.bits(self.lp_sys_active.clk_power.0) });
201
202        // LP SLEEP (lp_sleep_*)
203        PMU::regs()
204            .lp_sleep_lp_dig_power()
205            .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.dig_power.0) });
206        PMU::regs()
207            .lp_sleep_lp_ck_power()
208            .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.clk_power.0) });
209        PMU::regs()
210            .lp_sleep_xtal()
211            .modify(|_, w| w.lp_sleep_xpd_xtal().bit(self.lp_sys_sleep.xtal.xpd_xtal()));
212    }
213}
214
215/// Parameters for high-power system configurations during sleep modes.
216#[derive(Clone, Copy)]
217// pmu_hp_param_t
218pub struct HpParam {
219    /// Number of cycles to wait for the modem to wake up.
220    pub modem_wakeup_wait_cycle: u32,
221    /// Number of cycles to wait for the analog component stabilization.
222    pub analog_wait_target_cycle: u16,
223    /// Number of cycles to wait for the digital power-down sequence.
224    pub digital_power_down_wait_cycle: u16,
225    /// Number of cycles to wait for the digital power supply to stabilize.
226    pub digital_power_supply_wait_cycle: u16,
227    /// Number of cycles to wait for the digital power-up sequence.
228    pub digital_power_up_wait_cycle: u16,
229    /// Number of cycles to wait for the PLL to stabilize.
230    pub pll_stable_wait_cycle: u16,
231    /// Number of cycles to wait for modifying the ICG control.
232    pub modify_icg_cntl_wait_cycle: u8,
233    /// Number of cycles to wait for switching the ICG control.
234    pub switch_icg_cntl_wait_cycle: u8,
235    /// Minimum sleep time measured in slow clock cycles.
236    pub min_slp_slow_clk_cycle: u8,
237}
238
239/// Parameters for low-power system configurations during sleep modes.
240#[derive(Clone, Copy)]
241// pmu_lp_param_t
242pub struct LpParam {
243    /// Number of cycles to wait for the digital power supply to stabilize.
244    pub digital_power_supply_wait_cycle: u16,
245    /// Minimum sleep time measured in slow clock cycles.
246    pub min_slp_slow_clk_cycle: u8,
247    /// Number of cycles to wait for the analog component stabilization.
248    pub analog_wait_target_cycle: u8,
249    /// Number of cycles to wait for the digital power-down sequence.
250    pub digital_power_down_wait_cycle: u8,
251    /// Number of cycles to wait for the digital power-up sequence.
252    pub digital_power_up_wait_cycle: u8,
253}
254
255/// Parameters for high-power and low-power system configurations during sleep
256/// modes.
257#[derive(Clone, Copy)]
258// pmu_hp_lp_param_t
259pub struct HpLpParam {
260    /// Union of two u16 variants
261    pub xtal_stable_wait_cycle: u16,
262}
263
264/// Configuration of parameters for sleep modes
265#[derive(Clone, Copy)]
266// pmu_sleep_param_config_t
267pub struct ParamSleepConfig {
268    /// Configuration of high-power system parameters.
269    pub hp_sys: HpParam,
270    /// Configuration of low-power system parameters.
271    pub lp_sys: LpParam,
272    /// Shared configuration parameters for high-power and low-power systems.
273    pub hp_lp: HpLpParam,
274}
275impl ParamSleepConfig {
276    const PMU_SLEEP_PARAM_CONFIG_DEFAULT: Self = Self {
277        hp_sys: HpParam {
278            min_slp_slow_clk_cycle: 10,
279            analog_wait_target_cycle: 1700,
280            digital_power_supply_wait_cycle: 32,
281            digital_power_up_wait_cycle: 32,
282            modem_wakeup_wait_cycle: 0,
283            pll_stable_wait_cycle: 2,
284
285            digital_power_down_wait_cycle: 0,
286            modify_icg_cntl_wait_cycle: 0,
287            switch_icg_cntl_wait_cycle: 0,
288        },
289        lp_sys: LpParam {
290            min_slp_slow_clk_cycle: 10,
291            analog_wait_target_cycle: 15,
292            digital_power_supply_wait_cycle: 32,
293            digital_power_up_wait_cycle: 32,
294
295            digital_power_down_wait_cycle: 0,
296        },
297        hp_lp: HpLpParam {
298            xtal_stable_wait_cycle: 30,
299        },
300    };
301
302    fn apply(&self) {
303        // pmu_sleep_param_init
304        unsafe {
305            PMU::regs().slp_wakeup_cntl3().modify(|_, w| {
306                // pmu_ll_hp_set_min_sleep_cycle
307                w.hp_min_slp_val().bits(self.hp_sys.min_slp_slow_clk_cycle);
308                // pmu_ll_lp_set_min_sleep_cycle
309                w.lp_min_slp_val().bits(self.lp_sys.min_slp_slow_clk_cycle)
310            });
311
312            PMU::regs().slp_wakeup_cntl7().modify(|_, w| {
313                w.ana_wait_target() // pmu_ll_hp_set_analog_wait_target_cycle
314                    .bits(self.hp_sys.analog_wait_target_cycle)
315            });
316
317            PMU::regs().slp_wakeup_cntl5().modify(|_, w| {
318                w.lp_ana_wait_target() // pmu_ll_lp_set_analog_wait_target_cycle
319                    .bits(self.lp_sys.analog_wait_target_cycle)
320            });
321
322            PMU::regs().power_wait_timer0().modify(|_, w| {
323                // pmu_ll_hp_set_digital_power_supply_wait_cycle
324                w.dg_hp_wait_timer()
325                    .bits(self.hp_sys.digital_power_supply_wait_cycle);
326                // pmu_ll_hp_set_digital_power_up_wait_cycle
327                w.dg_hp_powerup_timer()
328                    .bits(self.hp_sys.digital_power_up_wait_cycle)
329            });
330
331            PMU::regs().power_wait_timer1().modify(|_, w| {
332                // pmu_ll_lp_set_digital_power_supply_wait_cycle
333                w.dg_lp_wait_timer()
334                    .bits(self.lp_sys.digital_power_supply_wait_cycle);
335                // pmu_ll_lp_set_digital_power_up_wait_cycle
336                w.dg_lp_powerup_timer()
337                    .bits(self.lp_sys.digital_power_up_wait_cycle)
338            });
339
340            PMU::regs().power_ck_wait_cntl().modify(|_, w| {
341                // pmu_ll_set_xtal_stable_wait_cycle
342                w.wait_xtl_stable().bits(self.hp_lp.xtal_stable_wait_cycle);
343                // pmu_ll_set_pll_stable_wait_cycle
344                w.wait_pll_stable().bits(self.hp_sys.pll_stable_wait_cycle)
345            });
346        }
347    }
348
349    fn defaults(config: SleepTimeConfig, pd_xtal: bool) -> Self {
350        let mut param = Self::PMU_SLEEP_PARAM_CONFIG_DEFAULT;
351
352        // pmu_sleep_param_config_default
353        param.hp_sys.min_slp_slow_clk_cycle =
354            config.us_to_slowclk(machine_constants::HP_MIN_SLP_TIME_US) as u8;
355        param.hp_sys.analog_wait_target_cycle =
356            config.us_to_fastclk(machine_constants::HP_ANALOG_WAIT_TIME_US) as u16;
357        param.hp_sys.digital_power_supply_wait_cycle =
358            config.us_to_fastclk(machine_constants::HP_POWER_SUPPLY_WAIT_TIME_US) as u16;
359        param.hp_sys.digital_power_up_wait_cycle =
360            config.us_to_fastclk(machine_constants::HP_POWER_UP_WAIT_TIME_US) as u16;
361        param.hp_sys.pll_stable_wait_cycle =
362            config.us_to_fastclk(machine_constants::HP_PLL_WAIT_STABLE_TIME_US) as u16;
363
364        param.lp_sys.min_slp_slow_clk_cycle =
365            config.us_to_slowclk(machine_constants::LP_MIN_SLP_TIME_US) as u8;
366        param.lp_sys.analog_wait_target_cycle =
367            config.us_to_slowclk(machine_constants::LP_ANALOG_WAIT_TIME_US) as u8;
368        param.lp_sys.digital_power_supply_wait_cycle =
369            config.us_to_fastclk(machine_constants::LP_POWER_SUPPLY_WAIT_TIME_US) as u16;
370        param.lp_sys.digital_power_up_wait_cycle =
371            config.us_to_fastclk(machine_constants::LP_POWER_UP_WAIT_TIME_US) as u8;
372
373        // This looks different from esp-idf but it is the same:
374        // Both `xtal_stable_wait_cycle` and `xtal_stable_wait_slow_clk_cycle` are
375        // u16 variants of the same union
376        param.hp_lp.xtal_stable_wait_cycle = if pd_xtal {
377            config.us_to_slowclk(machine_constants::LP_XTAL_WAIT_STABLE_TIME_US) as u16
378        } else {
379            config.us_to_fastclk(machine_constants::HP_XTAL_WAIT_STABLE_TIME_US) as u16
380        };
381
382        param
383    }
384}
385
386impl SleepTimeConfig {
387    pub(crate) const CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ: u32 = 96;
388    pub(crate) const LIGHT_SLEEP_TIME_OVERHEAD_US: u32 = 9;
389
390    pub(crate) fn pmu_sleep_calculate_hw_wait_time(&self, pd_flags: PowerDownFlags) -> u32 {
391        let lp_clk_switch_time_us = self.slowclk_to_us(machine_constants::LP_CLK_SWITCH_CYCLE);
392        let lp_clk_power_on_wait_time_us = if pd_flags.pd_xtal() {
393            machine_constants::LP_XTAL_WAIT_STABLE_TIME_US
394        } else {
395            self.slowclk_to_us(machine_constants::LP_CLK_POWER_ON_WAIT_CYCLE)
396        };
397
398        let lp_hw_wait_time_us = machine_constants::LP_MIN_SLP_TIME_US
399            + machine_constants::LP_ANALOG_WAIT_TIME_US
400            + lp_clk_power_on_wait_time_us
401            + lp_clk_switch_time_us
402            + machine_constants::LP_POWER_SUPPLY_WAIT_TIME_US
403            + machine_constants::LP_POWER_UP_WAIT_TIME_US;
404
405        let hp_digital_power_up_wait_time_us = machine_constants::HP_POWER_SUPPLY_WAIT_TIME_US
406            + machine_constants::HP_POWER_UP_WAIT_TIME_US;
407        let hp_regdma_wait_time_us = if pd_flags.pd_top() {
408            machine_constants::HP_REGDMA_S2A_WORK_TIME_PD_TOP_US
409        } else {
410            machine_constants::HP_REGDMA_S2A_WORK_TIME_PU_TOP_US
411        };
412        let hp_clock_wait_time_us = machine_constants::HP_XTAL_WAIT_STABLE_TIME_US
413            + machine_constants::HP_PLL_WAIT_STABLE_TIME_US;
414
415        let hp_hw_wait_time_us = machine_constants::HP_ANALOG_WAIT_TIME_US
416            + hp_digital_power_up_wait_time_us
417            + hp_regdma_wait_time_us
418            + hp_clock_wait_time_us;
419
420        lp_hw_wait_time_us + hp_hw_wait_time_us
421    }
422}
423
424/// Configuration for the RTC sleep behavior.
425#[derive(Clone, Copy)]
426pub struct RtcSleepConfig {
427    /// Deep Sleep flag
428    pub deep: bool,
429    /// Powers Down flags.
430    pub pd_flags: PowerDownFlags,
431    /// Indicates whether the top power domain should remain enabled during sleep.
432    need_pd_top: bool,
433}
434
435impl Default for RtcSleepConfig {
436    fn default() -> Self {
437        // from pmu_sleep_param_config_default
438        // sleep flags will be applied by wakeup methods and apply
439
440        Self {
441            deep: false,
442            pd_flags: PowerDownFlags(0),
443            need_pd_top: false,
444        }
445    }
446}
447
448bitfield::bitfield! {
449    #[derive(Clone, Copy)]
450    /// Power domains to be powered down during sleep.
451    pub struct PowerDownFlags(u32);
452
453    /// Controls the power-down status of the top power domain.
454    pub u32, pd_top      , set_pd_top      : 0;
455    /// Controls the power-down status of the VDD_SDIO power domain.
456    pub u32, pd_vddsdio  , set_pd_vddsdio  : 1;
457    /// Controls the power-down status of the modem power domain.
458    pub u32, pd_modem    , set_pd_modem    : 2;
459    /// Controls the power-down status of the CPU power domain.
460    ///
461    /// Crate-private, because a light sleep needs CPU retention to power this domain down. A
462    /// power-down without retention loses the CPU state.
463    pub(crate) u32, pd_cpu, set_pd_cpu: 3;
464    /// Controls the power-down status of the crystal oscillator.
465    pub u32, pd_xtal     , set_pd_xtal     : 4;
466    /// Controls the power-down status of the fast RC oscillator.
467    pub u32, pd_rc_fast  , set_pd_rc_fast  : 5;
468    /// Controls the power-down status of the 32 kHz crystal oscillator.
469    pub u32, pd_xtal32k  , set_pd_xtal32k  : 6;
470}
471
472/// Constants defined in `PMU_SLEEP_MC_DEFAULT()`
473mod machine_constants {
474    pub const LP_MIN_SLP_TIME_US: u32 = 450;
475    pub const LP_ANALOG_WAIT_TIME_US: u32 = 154;
476    pub const LP_XTAL_WAIT_STABLE_TIME_US: u32 = 250;
477    pub const LP_CLK_SWITCH_CYCLE: u32 = 1;
478    pub const LP_CLK_POWER_ON_WAIT_CYCLE: u32 = 1;
479    pub const LP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2;
480    pub const LP_POWER_UP_WAIT_TIME_US: u32 = 2;
481
482    pub const HP_MIN_SLP_TIME_US: u32 = 450;
483    pub const HP_ANALOG_WAIT_TIME_US: u32 = 154;
484    pub const HP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2;
485    pub const HP_POWER_UP_WAIT_TIME_US: u32 = 2;
486    pub const HP_REGDMA_S2A_WORK_TIME_PD_TOP_US: u32 = 480;
487    pub const HP_REGDMA_S2A_WORK_TIME_PU_TOP_US: u32 = 390;
488    pub const HP_XTAL_WAIT_STABLE_TIME_US: u32 = 250;
489    pub const HP_PLL_WAIT_STABLE_TIME_US: u32 = 50;
490}
491
492impl RtcSleepConfig {
493    /// Returns whether the device is in deep sleep mode.
494    pub fn deep_slp(&self) -> bool {
495        self.deep
496    }
497
498    /// Configures the device for deep sleep mode with ultra-low power settings.
499    pub fn deep() -> Self {
500        // Set up for ultra-low power sleep. Wakeup sources may modify these settings.
501        Self {
502            deep: true,
503            ..Self::default()
504        }
505    }
506
507    pub(crate) fn is_deep_sleep(&self) -> bool {
508        self.deep
509    }
510
511    pub(crate) fn base_settings(_rtc: &Rtc<'_>) {}
512
513    /// Selects the kind of the sleep, and what the sleep powers down.
514    ///
515    /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep
516    /// powered what it needs.
517    pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) {
518        self.deep = kind == SleepKind::Deep;
519
520        let lp_slow_uses_xtal32k = cfg_select! {
521            use_xtal32k => ClockTree::with(|clocks| {
522                matches!(
523                    clocks::lp_slow_clk_config(clocks),
524                    Some(clocks::LpSlowClkConfig::Xtal32k)
525                )
526            }),
527            _ => false,
528        };
529
530        if self.deep {
531            // force-disable certain power domains
532            self.pd_flags.set_pd_top(self.need_pd_top.not());
533            self.pd_flags.set_pd_vddsdio(true);
534            self.pd_flags.set_pd_modem(true);
535            self.pd_flags.set_pd_cpu(true);
536            self.pd_flags.set_pd_xtal(true);
537            self.pd_flags.set_pd_rc_fast(true);
538            self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k);
539        } else {
540            // Light sleep: the digital and top domains stay powered (so execution
541            // resumes in place; the top domain must also stay on for any EXT1/GPIO
542            // wakeup). Power down the analog clock sources nothing needs while the
543            // core is clock-gated to cut power. Unlike the C5/C6 family, H2's
544            // light-sleep analog config does not lower the HP voltage, so this saves
545            // the oscillator current but not regulator power.
546            self.pd_flags.set_pd_xtal(true);
547            self.pd_flags.set_pd_rc_fast(true);
548            self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k);
549        }
550    }
551
552    /// Configures the wakeup and reject sources of the sleep.
553    ///
554    /// [`Self::enter_sleep`] requests the sleep after this call. The caller calls
555    /// [`SavedState::restore`] on the return value after [`Self::finish_sleep`].
556    #[crate::ram]
557    pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> SavedState {
558        let (hp_root_clk, cpu_clk) = ClockTree::with(|clocks| {
559            let old = (clocks.hp_root_clk(), clocks.cpu_clk());
560            clocks::configure_hp_root_clk(clocks, HpRootClkConfig::Xtal);
561            clocks::configure_cpu_clk(clocks, CpuClkConfig::new(0));
562            old
563        });
564
565        // misc_modules_sleep_prepare
566
567        // pmu_sleep_config_default + pmu_sleep_init
568
569        let power = PowerSleepConfig::defaults(self.pd_flags);
570        power.apply();
571
572        // Needs to happen after rtc_clk_cpu_freq_set_xtal
573        let config = if self.deep {
574            SleepTimeConfig::deep_sleep()
575        } else {
576            SleepTimeConfig::light_sleep(self.pd_flags)
577        };
578
579        let param = ParamSleepConfig::defaults(config, power.hp_sys.xtal.xpd_xtal());
580
581        if self.deep {
582            DigitalSleepConfig::defaults_deep_sleep().apply();
583            AnalogSleepConfig::defaults_deep_sleep().apply();
584        } else {
585            DigitalSleepConfig::defaults_light_sleep(self.pd_flags).apply();
586            AnalogSleepConfig::defaults_light_sleep().apply();
587        }
588
589        param.apply();
590
591        // pmu_sleep_start
592
593        // lp_aon_hal_inform_wakeup_type - tells ROM which wakeup stub to run
594        LP_AON::regs()
595            .store9()
596            .modify(|r, w| unsafe { w.bits(r.bits() & !0x01 | self.deep as u32) });
597
598        // pmu_ll_hp_set_wakeup_enable
599        PMU::regs()
600            .slp_wakeup_cntl2()
601            .write(|w| unsafe { w.bits(wakeup_mask) });
602
603        // pmu_ll_hp_set_reject_enable
604        PMU::regs().slp_wakeup_cntl1().modify(|_, w| unsafe {
605            w.slp_reject_en().bit(reject_mask != 0);
606            w.sleep_reject_ena().bits(reject_mask)
607        });
608
609        PMU::regs().int_clr().write(|w| {
610            // pmu_ll_hp_clear_wakeup_intr_status
611            w.soc_wakeup().clear_bit_by_one();
612            // pmu_ll_hp_clear_reject_intr_status
613            w.soc_sleep_reject().clear_bit_by_one()
614        });
615
616        // pmu_ll_hp_clear_reject_cause
617        PMU::regs()
618            .slp_wakeup_cntl4()
619            .write(|w| w.slp_reject_cause_clr().bit(true));
620
621        // Start entry into sleep mode
622
623        SavedState {
624            hp_root_clk,
625            cpu_clk,
626        }
627    }
628
629    /// Requests the sleep.
630    ///
631    /// The caller waits for the result of the request.
632    #[inline(always)]
633    pub(crate) fn enter_sleep(&self) -> bool {
634        request_sleep()
635    }
636
637    /// Cleans up after sleep.
638    #[inline(always)]
639    pub(crate) fn finish_sleep(&self) {
640        // Sleep loses this setting, which `rtc::init` also writes.
641        crate::soc::regi2c::I2C_BIAS_DREG_0P8.write_field(8);
642
643        // The post-wake hook of the GPIO driver releases the pads that the sleep armed. Only that
644        // driver knows which pads it prepared.
645    }
646}
647
648/// The state that [`RtcSleepConfig::start_sleep`] changes for the length of the sleep.
649#[must_use]
650pub(crate) struct SavedState {
651    hp_root_clk: Option<HpRootClkConfig>,
652    cpu_clk: Option<CpuClkConfig>,
653}
654
655impl SavedState {
656    /// Restores the state. Runs after a wakeup and after a rejected sleep.
657    pub(crate) fn restore(self) {
658        ClockTree::with(|clocks| {
659            clocks::reconfigure_pll(clocks);
660            if let Some(hp_root_clk) = self.hp_root_clk {
661                clocks::configure_hp_root_clk(clocks, hp_root_clk);
662            }
663            if let Some(cpu_clk) = self.cpu_clk {
664                clocks::configure_cpu_clk(clocks, cpu_clk);
665            }
666        });
667    }
668}