Skip to main content

esp_hal/rtc_cntl/sleep/
esp32c5.rs

1use core::ops::Not;
2
3use crate::{
4    peripherals::{LP_AON, PMU},
5    rtc_cntl::{
6        Rtc,
7        rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower},
8        sleep::{
9            SleepKind,
10            pmu_common::{SleepTimeConfig, request_sleep},
11        },
12    },
13    soc::{
14        clocks::{self, ClockTree, HpRootClkConfig},
15        xtal32k,
16    },
17};
18
19/// Configuration for controlling the behavior during sleep modes.
20#[derive(Clone, Copy)]
21// pmu_sleep_analog_config_t
22pub struct AnalogSleepConfig {
23    /// High-power system configuration.
24    pub hp_sys: HpAnalog,
25    // pub lp_sys_active: LpAnalog, // unused
26    /// Low-power system analog configuration.
27    pub lp_sys_sleep: LpAnalog,
28}
29
30impl AnalogSleepConfig {
31    fn defaults_deep_sleep() -> Self {
32        Self {
33            // PMU_SLEEP_ANALOG_DSLP_CONFIG_DEFAULT
34            hp_sys: {
35                let mut cfg = HpAnalog::default();
36
37                cfg.bias.set_pd_cur(false);
38                cfg.bias.set_bias_sleep(false);
39                cfg.regulator0.set_xpd(false);
40                cfg.bias.set_dbg_atten(0);
41
42                cfg
43            },
44            // lp_sys_active: LpAnalog::default(),
45            lp_sys_sleep: {
46                let mut cfg = LpAnalog::default();
47
48                cfg.regulator1.set_drv_b(0);
49                cfg.bias.set_pd_cur(true);
50                cfg.bias.set_bias_sleep(true);
51                cfg.regulator0.set_slp_xpd(false);
52                cfg.regulator0.set_slp_dbias(0);
53                cfg.regulator0.set_xpd(true);
54                cfg.bias.set_dbg_atten(9); // PMU_DBG_ATTEN_DEEPSLEEP_DEFAULT
55                cfg.regulator0.set_dbias(15); // PMU_LP_DBIAS_DEEPSLEEP_0V7_DEFAULT
56
57                cfg
58            },
59        }
60    }
61
62    fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self {
63        let mut this = Self {
64            // PMU_SLEEP_ANALOG_LSLP_CONFIG_DEFAULT
65            hp_sys: {
66                let mut cfg = HpAnalog::default();
67
68                cfg.regulator1.set_drv_b(0);
69                cfg.bias.set_pd_cur(true);
70                cfg.bias.set_bias_sleep(true);
71                cfg.regulator0.set_xpd(true);
72                cfg.bias.set_dbg_atten(1); // PMU_DBG_ATTEN_LIGHTSLEEP_DEFAULT
73                cfg.regulator0.set_dbias(0); // PMU_HP_DBIAS_LIGHTSLEEP_0V6_DEFAULT
74
75                cfg
76            },
77            // lp_sys_active: LpAnalog::default(),
78            lp_sys_sleep: {
79                let mut cfg = LpAnalog::default();
80
81                cfg.regulator1.set_drv_b(0);
82                cfg.bias.set_pd_cur(true);
83                cfg.bias.set_bias_sleep(true);
84                cfg.regulator0.set_slp_xpd(false);
85                cfg.regulator0.set_slp_dbias(0);
86                cfg.regulator0.set_xpd(true);
87                cfg.bias.set_dbg_atten(1); // PMU_DBG_ATTEN_LIGHTSLEEP_DEFAULT
88                cfg.regulator0.set_dbias(15); // PMU_LP_DBIAS_LIGHTSLEEP_0V7_DEFAULT
89
90                cfg
91            },
92        };
93
94        // When XTAL or RC_FAST stays on during sleep, raise the regulator
95        // voltage back to the active-mode calibration value.
96        if !pd_flags.pd_xtal() {
97            this.hp_sys.bias.set_pd_cur(false);
98            this.hp_sys.bias.set_bias_sleep(false);
99            this.hp_sys.bias.set_dbg_atten(0);
100            this.hp_sys.regulator0.set_dbias(28); // get_act_hp_dbias() ~ HP_CALI_DBIAS
101
102            this.lp_sys_sleep.bias.set_pd_cur(false);
103            this.lp_sys_sleep.bias.set_bias_sleep(false);
104            this.lp_sys_sleep.bias.set_dbg_atten(0);
105            this.lp_sys_sleep.regulator0.set_dbias(28); // get_act_lp_dbias() ~ LP_CALI_DBIAS
106        }
107
108        this
109    }
110
111    fn apply(&self) {
112        // pmu_sleep_analog_init
113
114        // HP SLEEP (hp_sleep_*)
115        PMU::regs().hp_sleep_bias().modify(|_, w| unsafe {
116            // pmu_ll_hp_set_dbg_atten
117            w.hp_sleep_dbg_atten().bits(self.hp_sys.bias.dbg_atten());
118            // pmu_ll_hp_set_current_power_off
119            w.hp_sleep_pd_cur().bit(self.hp_sys.bias.pd_cur());
120            // pmu_ll_hp_set_bias_sleep_enable
121            w.sleep().bit(self.hp_sys.bias.bias_sleep())
122        });
123        PMU::regs().hp_sleep_hp_regulator0().modify(|_, w| unsafe {
124            // pmu_ll_hp_set_regulator_xpd
125            w.hp_sleep_hp_regulator_xpd()
126                .bit(self.hp_sys.regulator0.xpd());
127            // pmu_ll_hp_set_regulator_dbias
128            w.hp_sleep_hp_regulator_dbias()
129                .bits(self.hp_sys.regulator0.dbias())
130        });
131        PMU::regs().hp_sleep_hp_regulator1().modify(|_, w| unsafe {
132            // pmu_ll_hp_set_regulator_driver_bar
133            w.hp_sleep_hp_regulator_drv_b()
134                .bits(self.hp_sys.regulator1.drv_b())
135        });
136
137        // LP SLEEP (lp_sleep_*)
138        PMU::regs().lp_sleep_bias().modify(|_, w| unsafe {
139            // pmu_ll_lp_set_dbg_atten
140            w.lp_sleep_dbg_atten()
141                .bits(self.lp_sys_sleep.bias.dbg_atten());
142            // pmu_ll_lp_set_current_power_off
143            w.lp_sleep_pd_cur().bit(self.lp_sys_sleep.bias.pd_cur());
144            // pmu_ll_lp_set_bias_sleep_enable
145            w.sleep().bit(self.lp_sys_sleep.bias.bias_sleep())
146        });
147
148        PMU::regs().lp_sleep_lp_regulator0().modify(|_, w| unsafe {
149            // pmu_ll_lp_set_regulator_slp_xpd
150            w.lp_sleep_lp_regulator_slp_xpd()
151                .bit(self.lp_sys_sleep.regulator0.slp_xpd());
152            // pmu_ll_lp_set_regulator_xpd
153            w.lp_sleep_lp_regulator_xpd()
154                .bit(self.lp_sys_sleep.regulator0.xpd());
155            // pmu_ll_lp_set_regulator_sleep_dbias
156            w.lp_sleep_lp_regulator_slp_dbias()
157                .bits(self.lp_sys_sleep.regulator0.slp_dbias());
158            // pmu_ll_lp_set_regulator_dbias
159            w.lp_sleep_lp_regulator_dbias()
160                .bits(self.lp_sys_sleep.regulator0.dbias())
161        });
162
163        PMU::regs().lp_sleep_lp_regulator1().modify(|_, w| unsafe {
164            // pmu_ll_lp_set_regulator_driver_bar
165            w.lp_sleep_lp_regulator_drv_b()
166                .bits(self.lp_sys_sleep.regulator1.drv_b())
167        });
168    }
169}
170
171/// Configuration for controlling the behavior of digital peripherals during
172/// sleep modes.
173#[derive(Clone, Copy)]
174// pmu_sleep_digital_config_t
175pub struct DigitalSleepConfig {
176    /// High-power system control register configuration.
177    pub syscntl: HpSysCntlReg,
178}
179
180impl DigitalSleepConfig {
181    fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self {
182        Self {
183            // PMU_SLEEP_DIGITAL_LSLP_CONFIG_DEFAULT
184            syscntl: {
185                let mut cfg = HpSysCntlReg::default();
186
187                cfg.set_dig_pad_slp_sel(pd_flags.pd_top().not());
188
189                cfg
190            },
191        }
192    }
193
194    fn apply(&self) {
195        // pmu_sleep_digital_init
196        PMU::regs().hp_sleep_hp_sys_cntl().modify(|_, w| {
197            w.hp_sleep_dig_pad_slp_sel()
198                .bit(self.syscntl.dig_pad_slp_sel())
199        });
200    }
201}
202
203/// Configuration for controlling the power settings of high-power and low-power
204/// systems during sleep modes.
205#[derive(Clone, Copy)]
206// pmu_sleep_power_config_t
207pub struct PowerSleepConfig {
208    /// Power configuration for the high-power system during sleep.
209    pub hp_sys: HpSysPower,
210    /// Power configuration for the low-power system when it is active.
211    pub lp_sys_active: LpSysPower,
212    /// Power configuration for the low-power system when it is in sleep mode.
213    pub lp_sys_sleep: LpSysPower,
214}
215
216impl PowerSleepConfig {
217    fn defaults(pd_flags: PowerDownFlags) -> Self {
218        let mut this = Self {
219            hp_sys: HpSysPower::default(),
220            lp_sys_active: LpSysPower::default(),
221            lp_sys_sleep: LpSysPower::default(),
222        };
223        this.apply_flags(pd_flags);
224        this
225    }
226
227    fn apply_flags(&mut self, pd_flags: PowerDownFlags) {
228        // PMU_SLEEP_POWER_CONFIG_DEFAULT
229        self.hp_sys
230            .dig_power
231            .set_vdd_spi_pd_en(pd_flags.pd_vddsdio());
232        self.hp_sys.dig_power.set_wifi_pd_en(pd_flags.pd_modem());
233        self.hp_sys.dig_power.set_cpu_pd_en(pd_flags.pd_cpu());
234        self.hp_sys.dig_power.set_aon_pd_en(pd_flags.pd_hp_aon());
235        self.hp_sys.dig_power.set_top_pd_en(pd_flags.pd_top());
236
237        self.hp_sys.clk.set_i2c_iso_en(true);
238        self.hp_sys.clk.set_i2c_retention(true);
239
240        self.hp_sys.xtal.set_xpd_xtal(pd_flags.pd_xtal().not());
241
242        self.lp_sys_active
243            .clk_power
244            .set_xpd_xtal32k(xtal32k::use_xtal32k());
245        self.lp_sys_active.clk_power.set_xpd_rc32k(true);
246        self.lp_sys_active.clk_power.set_xpd_fosc(true);
247
248        self.lp_sys_sleep
249            .dig_power
250            .set_peri_pd_en(pd_flags.pd_lp_periph());
251        self.lp_sys_sleep.dig_power.set_mem_dslp(false);
252
253        self.lp_sys_sleep
254            .clk_power
255            .set_xpd_xtal32k(pd_flags.pd_xtal32k().not());
256        self.lp_sys_sleep
257            .clk_power
258            .set_xpd_rc32k(pd_flags.pd_rc32k().not());
259        self.lp_sys_sleep
260            .clk_power
261            .set_xpd_fosc(pd_flags.pd_rc_fast().not());
262
263        self.lp_sys_sleep
264            .xtal
265            .set_xpd_xtal(pd_flags.pd_xtal().not());
266    }
267
268    fn apply(&self) {
269        // pmu_sleep_power_init
270
271        // HP SLEEP (hp_sleep_*)
272        PMU::regs()
273            .hp_sleep_dig_power()
274            .modify(|_, w| unsafe { w.bits(self.hp_sys.dig_power.0) });
275        PMU::regs()
276            .hp_sleep_hp_ck_power()
277            .modify(|_, w| unsafe { w.bits(self.hp_sys.clk.0) });
278        PMU::regs()
279            .hp_sleep_xtal()
280            .modify(|_, w| w.hp_sleep_xpd_xtal().bit(self.hp_sys.xtal.xpd_xtal()));
281
282        // LP ACTIVE (hp_sleep_lp_*)
283        PMU::regs()
284            .hp_sleep_lp_dig_power()
285            .modify(|_, w| unsafe { w.bits(self.lp_sys_active.dig_power.0) });
286        PMU::regs()
287            .hp_sleep_lp_ck_power()
288            .modify(|_, w| unsafe { w.bits(self.lp_sys_active.clk_power.0) });
289
290        // LP SLEEP (lp_sleep_*)
291        PMU::regs()
292            .lp_sleep_lp_dig_power()
293            .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.dig_power.0) });
294        PMU::regs()
295            .lp_sleep_lp_ck_power()
296            .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.clk_power.0) });
297        PMU::regs()
298            .lp_sleep_xtal()
299            .modify(|_, w| w.lp_sleep_xpd_xtal().bit(self.lp_sys_sleep.xtal.xpd_xtal()));
300    }
301}
302
303/// Parameters for high-power system configurations during sleep modes.
304#[derive(Clone, Copy)]
305// pmu_hp_param_t
306pub struct HpParam {
307    /// Number of cycles to wait for the modem to wake up.
308    pub modem_wakeup_wait_cycle: u32,
309    /// Number of cycles to wait for the analog component stabilization.
310    pub analog_wait_target_cycle: u16,
311    /// Number of cycles to wait for the digital power-down sequence.
312    pub digital_power_down_wait_cycle: u16,
313    /// Number of cycles to wait for the digital power supply to stabilize.
314    pub digital_power_supply_wait_cycle: u16,
315    /// Number of cycles to wait for the digital power-up sequence.
316    pub digital_power_up_wait_cycle: u16,
317    /// Number of cycles to wait for the PLL to stabilize.
318    pub pll_stable_wait_cycle: u16,
319    /// Number of cycles to wait for modifying the ICG control.
320    pub modify_icg_cntl_wait_cycle: u8,
321    /// Number of cycles to wait for switching the ICG control.
322    pub switch_icg_cntl_wait_cycle: u8,
323    /// Minimum sleep time measured in slow clock cycles.
324    pub min_slp_slow_clk_cycle: u8,
325    /// Number of cycles to wait for all isolate signals to be ready.
326    pub isolate_wait_cycle: u8,
327    /// Number of cycles to wait for all reset signals to be ready.
328    pub reset_wait_cycle: u8,
329}
330
331/// Parameters for low-power system configurations during sleep modes.
332#[derive(Clone, Copy)]
333// pmu_lp_param_t
334pub struct LpParam {
335    /// Number of cycles to wait for the digital power supply to stabilize.
336    pub digital_power_supply_wait_cycle: u16,
337    /// Minimum sleep time measured in slow clock cycles.
338    pub min_slp_slow_clk_cycle: u8,
339    /// Number of cycles to wait for the analog component stabilization.
340    pub analog_wait_target_cycle: u8,
341    /// Number of cycles to wait for the digital power-down sequence.
342    pub digital_power_down_wait_cycle: u8,
343    /// Number of cycles to wait for the digital power-up sequence.
344    pub digital_power_up_wait_cycle: u8,
345    /// Number of cycles to wait for all isolate signals to be ready.
346    pub isolate_wait_cycle: u8,
347    /// Number of cycles to wait for all reset signals to be ready.
348    pub reset_wait_cycle: u8,
349}
350
351/// Parameters for high-power and low-power system configurations during sleep
352/// modes.
353#[derive(Clone, Copy)]
354// pmu_hp_lp_param_t
355pub struct HpLpParam {
356    /// Union of two u16 variants
357    pub xtal_stable_wait_cycle: u16,
358}
359
360/// Configuration of parameters for sleep modes
361#[derive(Clone, Copy)]
362// pmu_sleep_param_config_t
363pub struct ParamSleepConfig {
364    /// Configuration of high-power system parameters.
365    pub hp_sys: HpParam,
366    /// Configuration of low-power system parameters.
367    pub lp_sys: LpParam,
368    /// Shared configuration parameters for high-power and low-power systems.
369    pub hp_lp: HpLpParam,
370}
371impl ParamSleepConfig {
372    const PMU_SLEEP_PARAM_CONFIG_DEFAULT: Self = Self {
373        hp_sys: HpParam {
374            min_slp_slow_clk_cycle: 10,
375            analog_wait_target_cycle: 2419,
376            digital_power_supply_wait_cycle: 32,
377            digital_power_up_wait_cycle: 32,
378            modem_wakeup_wait_cycle: 20700,
379            pll_stable_wait_cycle: 2,
380
381            digital_power_down_wait_cycle: 0,
382            modify_icg_cntl_wait_cycle: 0,
383            switch_icg_cntl_wait_cycle: 0,
384            isolate_wait_cycle: 0,
385            reset_wait_cycle: 0,
386        },
387        lp_sys: LpParam {
388            min_slp_slow_clk_cycle: 10,
389            analog_wait_target_cycle: 23,
390            digital_power_supply_wait_cycle: 32,
391            digital_power_up_wait_cycle: 32,
392
393            digital_power_down_wait_cycle: 0,
394            isolate_wait_cycle: 0,
395            reset_wait_cycle: 0,
396        },
397        hp_lp: HpLpParam {
398            xtal_stable_wait_cycle: 30,
399        },
400    };
401
402    fn apply(&self) {
403        // pmu_sleep_param_init
404
405        PMU::regs().slp_wakeup_cntl3().modify(|_, w| unsafe {
406            // pmu_ll_hp_set_min_sleep_cycle
407            w.hp_min_slp_val().bits(self.hp_sys.min_slp_slow_clk_cycle);
408            // pmu_ll_lp_set_min_sleep_cycle
409            w.lp_min_slp_val().bits(self.lp_sys.min_slp_slow_clk_cycle)
410        });
411
412        PMU::regs().slp_wakeup_cntl7().modify(|_, w| unsafe {
413            // pmu_ll_hp_set_analog_wait_target_cycle
414            w.ana_wait_target()
415                .bits(self.hp_sys.analog_wait_target_cycle)
416        });
417
418        // From v1.2, the two low bits enable a power domain power-down that limits the inrush
419        // current.
420        let mut hp_digital_power_supply_wait_cycle = self.hp_sys.digital_power_supply_wait_cycle;
421        if crate::soc::chip_revision_above(crate::efuse::ChipRevision::from_combined(102)) {
422            hp_digital_power_supply_wait_cycle |= 0b11;
423        }
424
425        PMU::regs().power_wait_timer0().modify(|_, w| unsafe {
426            // pmu_ll_hp_set_digital_power_supply_wait_cycle
427            w.dg_hp_pd_wait_timer()
428                .bits(hp_digital_power_supply_wait_cycle);
429            // pmu_ll_hp_set_digital_power_up_wait_cycle
430            w.dg_hp_powerup_timer()
431                .bits(self.hp_sys.digital_power_up_wait_cycle)
432        });
433
434        PMU::regs().power_wait_timer1().modify(|_, w| unsafe {
435            // pmu_ll_lp_set_digital_power_supply_wait_cycle
436            w.dg_lp_pd_wait_timer()
437                .bits(self.lp_sys.digital_power_supply_wait_cycle);
438            // pmu_ll_lp_set_digital_power_up_wait_cycle
439            w.dg_lp_powerup_timer()
440                .bits(self.lp_sys.digital_power_up_wait_cycle)
441        });
442
443        // pmu_hal_hp/lp_set_control_ready_wait_cycle (new on ESP32-C5)
444        PMU::regs().power_wait_timer2().modify(|_, w| unsafe {
445            w.dg_hp_iso_wait_timer()
446                .bits(self.hp_sys.isolate_wait_cycle);
447            w.dg_hp_rst_wait_timer().bits(self.hp_sys.reset_wait_cycle);
448            w.dg_lp_iso_wait_timer()
449                .bits(self.lp_sys.isolate_wait_cycle);
450            w.dg_lp_rst_wait_timer().bits(self.lp_sys.reset_wait_cycle)
451        });
452
453        PMU::regs().slp_wakeup_cntl5().modify(|_, w| unsafe {
454            // pmu_ll_lp_set_analog_wait_target_cycle
455            w.lp_ana_wait_target()
456                .bits(self.lp_sys.analog_wait_target_cycle);
457            // pmu_ll_hp_set_modem_wakeup_wait_cycle
458            w.modem_wait_target()
459                .bits(self.hp_sys.modem_wakeup_wait_cycle)
460        });
461        PMU::regs().power_ck_wait_cntl().modify(|_, w| unsafe {
462            // pmu_ll_hp_set_xtal_stable_wait_cycle
463            w.wait_xtl_stable().bits(self.hp_lp.xtal_stable_wait_cycle);
464            // pmu_ll_hp_set_pll_stable_wait_cycle
465            w.wait_pll_stable().bits(self.hp_sys.pll_stable_wait_cycle)
466        });
467    }
468
469    fn defaults(config: SleepTimeConfig, pd_flags: PowerDownFlags, pd_xtal: bool) -> Self {
470        let mut param = Self::PMU_SLEEP_PARAM_CONFIG_DEFAULT;
471
472        // pmu_sleep_param_config_default
473        param.hp_sys.min_slp_slow_clk_cycle =
474            config.us_to_slowclk(MachineConstants::HP_MIN_SLP_TIME_US) as u8;
475        param.hp_sys.analog_wait_target_cycle =
476            config.us_to_fastclk(MachineConstants::HP_ANALOG_WAIT_TIME_US) as u16;
477        param.hp_sys.digital_power_supply_wait_cycle =
478            config.us_to_fastclk(MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US) as u16;
479        param.hp_sys.digital_power_up_wait_cycle =
480            config.us_to_fastclk(MachineConstants::HP_POWER_UP_WAIT_TIME_US) as u16;
481        param.hp_sys.pll_stable_wait_cycle =
482            config.us_to_fastclk(MachineConstants::HP_PLL_WAIT_STABLE_TIME_US) as u16;
483        param.hp_sys.isolate_wait_cycle =
484            config.us_to_fastclk(MachineConstants::HP_ISOLATE_WAIT_TIME_US) as u8;
485        param.hp_sys.reset_wait_cycle =
486            config.us_to_fastclk(MachineConstants::HP_RESET_WAIT_TIME_US) as u8;
487
488        let hw_wait_time_us = config.pmu_sleep_calculate_hw_wait_time(pd_flags);
489
490        let modem_wakeup_wait_time_us = (config.sleep_time_adjustment
491            + MachineConstants::MODEM_STATE_SKIP_TIME_US
492            + MachineConstants::HP_REGDMA_RF_ON_WORK_TIME_US)
493            .saturating_sub(hw_wait_time_us);
494        param.hp_sys.modem_wakeup_wait_cycle = config.us_to_fastclk(modem_wakeup_wait_time_us);
495
496        param.lp_sys.min_slp_slow_clk_cycle =
497            config.us_to_slowclk(MachineConstants::LP_MIN_SLP_TIME_US) as u8;
498        param.lp_sys.analog_wait_target_cycle =
499            config.us_to_slowclk(MachineConstants::LP_ANALOG_WAIT_TIME_US) as u8;
500        param.lp_sys.digital_power_supply_wait_cycle =
501            config.us_to_fastclk(MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US) as u16;
502        param.lp_sys.digital_power_up_wait_cycle =
503            config.us_to_fastclk(MachineConstants::LP_POWER_UP_WAIT_TIME_US) as u8;
504        param.lp_sys.isolate_wait_cycle =
505            config.us_to_fastclk(MachineConstants::LP_ISOLATE_WAIT_TIME_US) as u8;
506        param.lp_sys.reset_wait_cycle =
507            config.us_to_fastclk(MachineConstants::LP_RESET_WAIT_TIME_US) as u8;
508
509        // This looks different from esp-idf but it is the same:
510        // Both `xtal_stable_wait_cycle` and `xtal_stable_wait_slow_clk_cycle` are
511        // u16 variants of the same union
512        param.hp_lp.xtal_stable_wait_cycle = if pd_xtal {
513            config.us_to_slowclk(MachineConstants::LP_XTAL_WAIT_STABLE_TIME_US) as u16
514        } else {
515            config.us_to_fastclk(MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US) as u16
516        };
517
518        param
519    }
520}
521
522impl SleepTimeConfig {
523    pub(crate) const CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ: u32 = 160;
524    pub(crate) const LIGHT_SLEEP_TIME_OVERHEAD_US: u32 = 56;
525
526    pub(crate) fn pmu_sleep_calculate_hw_wait_time(&self, pd_flags: PowerDownFlags) -> u32 {
527        // LP core hardware wait time, microsecond
528        let lp_wakeup_wait_time_us = self.slowclk_to_us(MachineConstants::LP_WAKEUP_WAIT_CYCLE);
529        let lp_clk_switch_time_us = self.slowclk_to_us(MachineConstants::LP_CLK_SWITCH_CYCLE);
530        let lp_clk_power_on_wait_time_us = if pd_flags.pd_xtal() {
531            MachineConstants::LP_XTAL_WAIT_STABLE_TIME_US
532        } else {
533            self.slowclk_to_us(MachineConstants::LP_CLK_POWER_ON_WAIT_CYCLE)
534        };
535
536        // ESP32-C5 adds control (isolate + reset) wait time to both domains.
537        let lp_control_wait_time_us =
538            MachineConstants::LP_ISOLATE_WAIT_TIME_US + MachineConstants::LP_RESET_WAIT_TIME_US;
539        let lp_hw_wait_time_us = MachineConstants::LP_MIN_SLP_TIME_US
540            + MachineConstants::LP_ANALOG_WAIT_TIME_US
541            + lp_clk_power_on_wait_time_us
542            + lp_wakeup_wait_time_us
543            + lp_clk_switch_time_us
544            + MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US
545            + MachineConstants::LP_POWER_UP_WAIT_TIME_US
546            + lp_control_wait_time_us;
547
548        // HP core hardware wait time, microsecond
549        let hp_digital_power_up_wait_time_us = MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US
550            + MachineConstants::HP_POWER_UP_WAIT_TIME_US;
551        let hp_control_wait_time_us =
552            MachineConstants::HP_ISOLATE_WAIT_TIME_US + MachineConstants::HP_RESET_WAIT_TIME_US;
553        let hp_regdma_wait_time_us = u32::max(
554            MachineConstants::HP_REGDMA_S2M_WORK_TIME_US
555                + MachineConstants::HP_REGDMA_M2A_WORK_TIME_US,
556            MachineConstants::HP_REGDMA_S2A_WORK_TIME_US,
557        );
558        let hp_clock_wait_time_us = MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US
559            + MachineConstants::HP_PLL_WAIT_STABLE_TIME_US;
560
561        let hp_hw_wait_time_us = MachineConstants::HP_ANALOG_WAIT_TIME_US
562            + u32::max(
563                hp_digital_power_up_wait_time_us + hp_regdma_wait_time_us,
564                hp_clock_wait_time_us,
565            )
566            + hp_control_wait_time_us;
567
568        #[rustfmt::skip] // ASCII art
569        //  When the SOC wakeup (lp timer or GPIO wakeup) and Modem wakeup (Beacon wakeup) complete,
570        // the soc wakeup will be delayed until the RF is turned on in Modem state.
571        //
572        //              modem wakeup                      TBTT, RF on by HW
573        //                   |                                    |
574        //                  \|/                                  \|/
575        // PMU_HP_ACTIVE                                                                         /------
576        // PMU_HP_MODEM                                           /------------//////////////////
577        // PMU_HP_SLEEP   ----------------------//////////////////
578        //                  /|\                /|\ /|\          /|\           /|\              /|\
579        //                   |<- some hw wait ->|   |            |             |<- M2A switch ->|
580        //                   |  slow cycles &   | soc wakeup     |                              |
581        //                   |   FOSC cycles    |<- S2M switch ->|                              |
582        //                   |                                                                  |
583        //                   |<--      PMU guard time, also the maximum time for the SOC     -->|
584        //                   |                           wake-up delay                          |
585        //
586        const CONFIG_ESP_RADIO_ENHANCED_LIGHT_SLEEP: bool = true;
587
588        let (rf_on_protect_time_us, sync_time_us) = if CONFIG_ESP_RADIO_ENHANCED_LIGHT_SLEEP {
589            (
590                MachineConstants::HP_REGDMA_RF_ON_WORK_TIME_US,
591                MachineConstants::HP_CLOCK_DOMAIN_SYNC_TIME_US,
592            )
593        } else {
594            (0, 0)
595        };
596
597        lp_hw_wait_time_us + hp_hw_wait_time_us + sync_time_us + rf_on_protect_time_us
598    }
599}
600
601/// Configuration for the RTC sleep behavior.
602#[derive(Clone, Copy)]
603// pmu_sleep_config_t + deep sleep flag + pd flags
604pub struct RtcSleepConfig {
605    /// Deep Sleep flag
606    pub deep: bool,
607    /// Powers Down flags.
608    pub pd_flags: PowerDownFlags,
609}
610
611impl Default for RtcSleepConfig {
612    fn default() -> Self {
613        // from pmu_sleep_param_config_default
614        // sleep flags will be applied by wakeup methods and apply
615
616        Self {
617            deep: false,
618            pd_flags: PowerDownFlags(0),
619        }
620    }
621}
622
623bitfield::bitfield! {
624    #[derive(Clone, Copy)]
625    /// Power domains to be powered down during sleep.
626    pub struct PowerDownFlags(u32);
627
628    /// Controls the power-down status of the top power domain.
629    pub u32, pd_top      , set_pd_top      : 0;
630    /// Controls the power-down status of the VDD_SDIO power domain.
631    pub u32, pd_vddsdio  , set_pd_vddsdio  : 1;
632    /// Controls the power-down status of the modem power domain.
633    pub u32, pd_modem    , set_pd_modem    : 2;
634    /// Controls the power-down status of the high-performance peripheral power domain.
635    pub u32, pd_hp_periph, set_pd_hp_periph: 3;
636    /// Controls the power-down status of the CPU power domain.
637    ///
638    /// Crate-private, because a light sleep needs CPU retention to power this domain down. A
639    /// power-down without retention loses the CPU state.
640    pub(crate) u32, pd_cpu, set_pd_cpu: 4;
641    /// Controls the power-down status of the high-performance always-on domain.
642    pub u32, pd_hp_aon   , set_pd_hp_aon   : 5;
643    /// Controls the power-down status of memory group 0.
644    pub u32, pd_mem_g0   , set_pd_mem_g0   : 6;
645    /// Controls the power-down status of memory group 1.
646    pub u32, pd_mem_g1   , set_pd_mem_g1   : 7;
647    /// Controls the power-down status of memory group 2.
648    pub u32, pd_mem_g2   , set_pd_mem_g2   : 8;
649    /// Controls the power-down status of memory group 3.
650    pub u32, pd_mem_g3   , set_pd_mem_g3   : 9;
651    /// Controls the power-down status of the crystal oscillator.
652    pub u32, pd_xtal     , set_pd_xtal     : 10;
653    /// Controls the power-down status of the fast RC oscillator.
654    pub u32, pd_rc_fast  , set_pd_rc_fast  : 11;
655    /// Controls the power-down status of the 32 kHz crystal oscillator.
656    pub u32, pd_xtal32k  , set_pd_xtal32k  : 12;
657    /// Controls the power-down status of the 32 kHz RC oscillator.
658    pub u32, pd_rc32k    , set_pd_rc32k    : 13;
659    /// Controls the power-down status of the low-power peripheral domain.
660    pub u32, pd_lp_periph, set_pd_lp_periph: 14;
661}
662
663impl PowerDownFlags {
664    /// Returns whether all memory groups (G0, G1, G2, G3) are powered down.
665    pub fn pd_mem(self) -> bool {
666        self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3()
667    }
668
669    /// Sets the power-down status for all memory groups (G0, G1, G2, G3) at
670    /// once.
671    pub fn set_pd_mem(&mut self, value: bool) {
672        self.set_pd_mem_g0(value);
673        self.set_pd_mem_g1(value);
674        self.set_pd_mem_g2(value);
675        self.set_pd_mem_g3(value);
676    }
677}
678
679// Constants defined in `PMU_SLEEP_MC_DEFAULT()` (ESP32-C5 values)
680struct MachineConstants;
681impl MachineConstants {
682    const LP_MIN_SLP_TIME_US: u32 = 450;
683    const LP_WAKEUP_WAIT_CYCLE: u32 = 4;
684    const LP_ANALOG_WAIT_TIME_US: u32 = 154;
685    const LP_XTAL_WAIT_STABLE_TIME_US: u32 = 250;
686    const LP_CLK_SWITCH_CYCLE: u32 = 1;
687    const LP_CLK_POWER_ON_WAIT_CYCLE: u32 = 1;
688    const LP_ISOLATE_WAIT_TIME_US: u32 = 1;
689    const LP_RESET_WAIT_TIME_US: u32 = 1;
690    const LP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2;
691    const LP_POWER_UP_WAIT_TIME_US: u32 = 2;
692
693    const HP_MIN_SLP_TIME_US: u32 = 450;
694    const HP_CLOCK_DOMAIN_SYNC_TIME_US: u32 = 2;
695    const HP_SYSTEM_DFS_UP_WORK_TIME_US: u32 = 124;
696    const HP_ANALOG_WAIT_TIME_US: u32 = 154;
697    const HP_ISOLATE_WAIT_TIME_US: u32 = 1;
698    const HP_RESET_WAIT_TIME_US: u32 = 1;
699    const HP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2;
700    const HP_POWER_UP_WAIT_TIME_US: u32 = 2;
701    const HP_REGDMA_S2M_WORK_TIME_US: u32 = 287;
702    const HP_REGDMA_S2A_WORK_TIME_US: u32 = 720;
703    const HP_REGDMA_M2A_WORK_TIME_US: u32 = 430;
704    // Unused, but defined in esp-idf. May be needed later.
705    // const HP_REGDMA_A2S_WORK_TIME_US: u32 = 433;
706    const HP_REGDMA_RF_ON_WORK_TIME_US: u32 = 68;
707    // Unused, but defined in esp-idf. May be needed later.
708    // const HP_REGDMA_RF_OFF_WORK_TIME_US: u32 = 25;
709    const HP_XTAL_WAIT_STABLE_TIME_US: u32 = 250;
710    const HP_PLL_WAIT_STABLE_TIME_US: u32 = 50;
711
712    const MODEM_STATE_SKIP_TIME_US: u32 = Self::HP_REGDMA_M2A_WORK_TIME_US
713        + Self::HP_SYSTEM_DFS_UP_WORK_TIME_US
714        + Self::LP_MIN_SLP_TIME_US;
715}
716
717impl RtcSleepConfig {
718    /// Returns whether the device is in deep sleep mode.
719    pub fn deep_slp(&self) -> bool {
720        self.deep
721    }
722
723    /// Configures the device for deep sleep mode with ultra-low power settings.
724    pub fn deep() -> Self {
725        // Set up for ultra-low power sleep. Wakeup sources may modify these settings.
726        Self {
727            deep: true,
728            ..Self::default()
729        }
730    }
731
732    pub(crate) fn is_deep_sleep(&self) -> bool {
733        self.deep
734    }
735
736    pub(crate) fn base_settings(_rtc: &Rtc<'_>) {}
737
738    /// Selects the kind of the sleep, and what the sleep powers down.
739    ///
740    /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep
741    /// powered what it needs.
742    pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) {
743        self.deep = kind == SleepKind::Deep;
744
745        let lp_slow_uses_xtal32k = cfg_select! {
746            use_xtal32k => ClockTree::with(|clocks| {
747                matches!(
748                    clocks::lp_slow_clk_config(clocks),
749                    Some(clocks::LpSlowClkConfig::Xtal32k)
750                )
751            }),
752            _ => false,
753        };
754
755        if self.deep {
756            // force-disable certain power domains
757            self.pd_flags.set_pd_top(true);
758            self.pd_flags.set_pd_vddsdio(true);
759            self.pd_flags.set_pd_modem(true);
760            self.pd_flags.set_pd_hp_periph(true);
761            self.pd_flags.set_pd_cpu(true);
762            self.pd_flags.set_pd_mem(true);
763            self.pd_flags.set_pd_xtal(true);
764            self.pd_flags.set_pd_hp_aon(true);
765            self.pd_flags.set_pd_lp_periph(true);
766            self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k);
767            self.pd_flags.set_pd_rc32k(true);
768            self.pd_flags.set_pd_rc_fast(true);
769        } else {
770            // Light sleep: the digital domain (CPU, RAM, peripherals) stays powered
771            // and only clock-gated, so execution resumes in place. To cut power we
772            // turn off the analog clock sources that nothing needs while the core is
773            // gated. Powering down XTAL also makes the analog config drop the HP
774            // regulator to the 0.6 V light-sleep voltage instead of holding it at the
775            // active calibration voltage (see `AnalogSleepConfig::defaults_light_sleep`),
776            // which is the dominant saving.
777            self.pd_flags.set_pd_xtal(true);
778            self.pd_flags.set_pd_rc_fast(true);
779            self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k);
780        }
781    }
782
783    /// Configures the wakeup and reject sources of the sleep.
784    ///
785    /// [`Self::enter_sleep`] requests the sleep after this call. The caller calls
786    /// [`SavedState::restore`] on the return value after [`Self::finish_sleep`].
787    #[crate::ram]
788    pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> SavedState {
789        let hp_root_clk = ClockTree::with(|clocks| {
790            let old = clocks.hp_root_clk();
791            clocks::configure_hp_root_clk(clocks, HpRootClkConfig::Xtal);
792            old
793        });
794
795        // pmu_sleep_config_default + pmu_sleep_init.
796
797        let power = PowerSleepConfig::defaults(self.pd_flags);
798        power.apply();
799
800        // Needs to happen after rtc_clk_cpu_freq_set_xtal
801        let config = if self.deep {
802            SleepTimeConfig::deep_sleep()
803        } else {
804            SleepTimeConfig::light_sleep(self.pd_flags)
805        };
806
807        let mut param =
808            ParamSleepConfig::defaults(config, self.pd_flags, power.hp_sys.xtal.xpd_xtal());
809
810        if self.deep {
811            const PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US: u32 = 500;
812            param.lp_sys.analog_wait_target_cycle =
813                config.us_to_slowclk(PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US) as u8;
814
815            AnalogSleepConfig::defaults_deep_sleep().apply();
816        } else {
817            AnalogSleepConfig::defaults_light_sleep(self.pd_flags).apply();
818            DigitalSleepConfig::defaults_light_sleep(self.pd_flags).apply();
819        }
820
821        param.apply();
822
823        // like esp-idf pmu_sleep_start()
824
825        // lp_aon_hal_inform_wakeup_type - tells ROM which wakeup stub to run
826        LP_AON::regs()
827            .store8()
828            .modify(|r, w| unsafe { w.bits(r.bits() & !0x01 | self.deep as u32) });
829
830        // pmu_ll_hp_set_wakeup_enable
831        PMU::regs()
832            .slp_wakeup_cntl2()
833            .write(|w| unsafe { w.bits(wakeup_mask) });
834
835        // pmu_ll_hp_set_reject_enable
836        PMU::regs().slp_wakeup_cntl1().modify(|_, w| unsafe {
837            w.slp_reject_en().bit(reject_mask != 0);
838            w.sleep_reject_ena().bits(reject_mask)
839        });
840
841        // pmu_ll_hp_clear_reject_cause
842        PMU::regs()
843            .slp_wakeup_cntl4()
844            .write(|w| w.slp_reject_cause_clr().bit(true));
845
846        PMU::regs().int_clr().write(|w| {
847            // pmu_ll_hp_clear_sw_intr_status
848            w.sw().clear_bit_by_one();
849            // pmu_ll_hp_clear_reject_intr_status
850            w.soc_sleep_reject().clear_bit_by_one();
851            // pmu_ll_hp_clear_wakeup_intr_status
852            w.soc_wakeup().clear_bit_by_one()
853        });
854
855        // misc_modules_sleep_prepare
856
857        // Start entry into sleep mode
858
859        SavedState { hp_root_clk }
860    }
861
862    /// Requests the sleep.
863    ///
864    /// The caller waits for the result of the request.
865    #[inline(always)]
866    pub(crate) fn enter_sleep(&self) -> bool {
867        request_sleep()
868    }
869
870    /// Cleans up after sleep.
871    #[inline(always)]
872    pub(crate) fn finish_sleep(&self) {
873        super::pmu_common::wait_for_efuse_idle();
874
875        // The post-wake hook of the GPIO driver releases the pads that the sleep armed. Only that
876        // driver knows which pads it prepared.
877    }
878}
879
880/// The state that [`RtcSleepConfig::start_sleep`] changes for the length of the sleep.
881#[must_use]
882pub(crate) struct SavedState {
883    hp_root_clk: Option<HpRootClkConfig>,
884}
885
886impl SavedState {
887    /// Restores the state. Runs after a wakeup and after a rejected sleep.
888    pub(crate) fn restore(self) {
889        ClockTree::with(|clocks| {
890            clocks::reconfigure_pll(clocks);
891            if let Some(hp_root_clk) = self.hp_root_clk {
892                clocks::configure_hp_root_clk(clocks, hp_root_clk);
893            }
894        });
895    }
896}