Skip to main content

esp_hal/rtc_cntl/sleep/
esp32c6.rs

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