Skip to main content

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