Skip to main content

esp_hal/rtc_cntl/sleep/
esp32h4.rs

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