Skip to main content

esp_hal/rtc_cntl/sleep/
esp32s31.rs

1//! Light- and deep-sleep support for the ESP32-S31.
2use core::ops::Not;
3
4use crate::{
5    peripherals::{LP_SYS as LP_AON, PMU},
6    rtc_cntl::{
7        Rtc,
8        rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower},
9        sleep::{
10            SleepKind,
11            pmu_common::{SleepTimeConfig, request_sleep},
12        },
13    },
14    soc::{
15        clocks::{self, ClockTree, CpuRootClkConfig},
16        xtal32k,
17    },
18};
19
20const HP_CALI_DBIAS: u8 = 26;
21const LP_CALI_DBIAS: u8 = 26;
22
23/// Configuration for controlling analog behavior during sleep.
24#[derive(Clone, Copy)]
25pub struct AnalogSleepConfig {
26    /// High-power system analog configuration.
27    pub hp_sys: HpAnalog,
28    /// Low-power system analog configuration.
29    pub lp_sys_sleep: LpAnalog,
30}
31
32impl AnalogSleepConfig {
33    fn defaults_deep_sleep() -> Self {
34        // PMU_SLEEP_ANALOG_DSLP_CONFIG_DEFAULT
35        Self {
36            hp_sys: {
37                let mut cfg = HpAnalog::default();
38                cfg.bias.set_pd_cur(true);
39                cfg.bias.set_bias_sleep(true);
40                cfg.regulator0.set_xpd(false);
41                cfg.bias.set_dbg_atten(0);
42                cfg
43            },
44            lp_sys_sleep: {
45                let mut cfg = LpAnalog::default();
46                cfg.regulator1.set_drv_b(0);
47                cfg.bias.set_pd_cur(true);
48                cfg.bias.set_bias_sleep(true);
49                cfg.regulator0.set_slp_xpd(false);
50                cfg.regulator0.set_slp_dbias(0);
51                cfg.regulator0.set_xpd(true);
52                cfg.bias.set_dbg_atten(12);
53                cfg.regulator0.set_dbias(23);
54                cfg
55            },
56        }
57    }
58
59    fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self {
60        let mut this = Self {
61            hp_sys: {
62                let mut cfg = HpAnalog::default();
63                cfg.regulator1.set_drv_b(0);
64                cfg.bias.set_pd_cur(true);
65                cfg.bias.set_bias_sleep(true);
66                cfg.regulator0.set_xpd(true);
67                cfg.bias.set_dbg_atten(0);
68                cfg.regulator0.set_dbias(1);
69                cfg
70            },
71            lp_sys_sleep: {
72                let mut cfg = LpAnalog::default();
73                cfg.regulator1.set_drv_b(0);
74                cfg.bias.set_pd_cur(true);
75                cfg.bias.set_bias_sleep(true);
76                cfg.regulator0.set_slp_xpd(false);
77                cfg.regulator0.set_slp_dbias(0);
78                cfg.regulator0.set_xpd(true);
79                cfg.bias.set_dbg_atten(0);
80                cfg.regulator0.set_dbias(12);
81                cfg
82            },
83        };
84
85        // Without the reference current, PSRAM loses its data and its mode register settings in
86        // light sleep.
87        // See <https://github.com/espressif/esp-idf/blob/383dda6c182/components/esp_hw_support/port/esp32s31/pmu_sleep.c#L223-L229>.
88        if !pd_flags.pd_xtal() || !crate::psram::psram_range().is_empty() {
89            this.hp_sys.bias.set_pd_cur(false);
90            this.lp_sys_sleep.bias.set_pd_cur(false);
91        }
92
93        if !pd_flags.pd_xtal() || !pd_flags.pd_rc_fast() {
94            this.hp_sys.bias.set_dbg_atten(0);
95            this.hp_sys.regulator0.set_dbias(HP_CALI_DBIAS);
96            this.lp_sys_sleep.bias.set_dbg_atten(0);
97            this.lp_sys_sleep.regulator0.set_dbias(LP_CALI_DBIAS);
98        }
99
100        this
101    }
102
103    fn apply(&self) {
104        // pmu_sleep_analog_init
105        PMU::regs().hp_sleep_bias().modify(|_, w| unsafe {
106            w.hp_sleep_dbg_atten().bits(self.hp_sys.bias.dbg_atten());
107            w.hp_sleep_pd_cur().bit(self.hp_sys.bias.pd_cur());
108            w.sleep().bit(self.hp_sys.bias.bias_sleep())
109        });
110        PMU::regs().hp_sleep_hp_regulator0().modify(|_, w| unsafe {
111            w.hp_sleep_hp_regulator_slp_mem_xpd()
112                .bit(self.hp_sys.regulator0.slp_mem_xpd());
113            w.hp_sleep_hp_regulator_slp_logic_xpd()
114                .bit(self.hp_sys.regulator0.slp_logic_xpd());
115            w.hp_sleep_hp_regulator_xpd()
116                .bit(self.hp_sys.regulator0.xpd());
117            w.hp_sleep_hp_regulator_slp_logic_dbias()
118                .bits(self.hp_sys.regulator0.slp_logic_dbias());
119            w.hp_sleep_hp_regulator_dbias()
120                .bits(self.hp_sys.regulator0.dbias())
121        });
122        PMU::regs().hp_sleep_hp_regulator1().modify(|_, w| unsafe {
123            w.hp_sleep_hp_regulator_drv_b()
124                .bits(self.hp_sys.regulator1.drv_b())
125        });
126
127        PMU::regs().lp_sleep_bias().modify(|_, w| unsafe {
128            w.lp_sleep_dbg_atten()
129                .bits(self.lp_sys_sleep.bias.dbg_atten());
130            w.lp_sleep_pd_cur().bit(self.lp_sys_sleep.bias.pd_cur());
131            w.sleep().bit(self.lp_sys_sleep.bias.bias_sleep())
132        });
133        PMU::regs().lp_sleep_lp_regulator0().modify(|_, w| unsafe {
134            w.lp_sleep_lp_regulator_slp_xpd()
135                .bit(self.lp_sys_sleep.regulator0.slp_xpd());
136            w.lp_sleep_lp_regulator_xpd()
137                .bit(self.lp_sys_sleep.regulator0.xpd());
138            w.lp_sleep_lp_regulator_slp_dbias()
139                .bits(self.lp_sys_sleep.regulator0.slp_dbias());
140            w.lp_sleep_lp_regulator_dbias()
141                .bits(self.lp_sys_sleep.regulator0.dbias())
142        });
143        PMU::regs().lp_sleep_lp_regulator1().modify(|_, w| unsafe {
144            w.lp_sleep_lp_regulator_drv_b()
145                .bits(self.lp_sys_sleep.regulator1.drv_b())
146        });
147    }
148}
149
150/// Configuration for digital peripherals during sleep.
151#[derive(Clone, Copy)]
152pub struct DigitalSleepConfig {
153    /// High-power system control register configuration.
154    pub syscntl: HpSysCntlReg,
155}
156
157impl DigitalSleepConfig {
158    fn defaults_deep_sleep(pd_flags: PowerDownFlags) -> Self {
159        let mut syscntl = HpSysCntlReg::default();
160        syscntl.set_dig_pad_slp_sel(false);
161        syscntl.set_lp_pad_hold_all(true);
162        syscntl.set_hp_pad_hold_all(true);
163        syscntl.set_dig_pause_wdt(true);
164        syscntl.set_c_channel(!pd_flags.pd_top());
165        Self { syscntl }
166    }
167
168    fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self {
169        let mut syscntl = HpSysCntlReg::default();
170        syscntl.set_dig_pad_slp_sel(!pd_flags.pd_top());
171        syscntl.set_lp_pad_hold_all(pd_flags.pd_top());
172        syscntl.set_hp_pad_hold_all(pd_flags.pd_top());
173        syscntl.set_dig_pause_wdt(true);
174        syscntl.set_c_channel(!pd_flags.pd_top());
175        Self { syscntl }
176    }
177
178    fn apply(&self) {
179        PMU::regs().hp_sleep_hp_sys_cntl().modify(|_, w| {
180            w.hp_sleep_c_channel().bit(self.syscntl.c_channel());
181            w.hp_sleep_dig_pad_slp_sel()
182                .bit(self.syscntl.dig_pad_slp_sel());
183            w.hp_sleep_lp_pad_hold_all()
184                .bit(self.syscntl.lp_pad_hold_all());
185            w.hp_sleep_hp_pad_hold_all()
186                .bit(self.syscntl.hp_pad_hold_all());
187            w.hp_sleep_dig_pause_wdt().bit(self.syscntl.dig_pause_wdt());
188            w.hp_sleep_dig_cpu_stall().bit(true)
189        });
190    }
191}
192
193/// Configuration of HP and LP power domains during sleep.
194#[derive(Clone, Copy)]
195pub struct PowerSleepConfig {
196    /// Power configuration for the high-power system during sleep.
197    pub hp_sys: HpSysPower,
198    /// Power configuration for the low-power system when it is active.
199    pub lp_sys_active: LpSysPower,
200    /// Power configuration for the low-power system when it is in sleep mode.
201    pub lp_sys_sleep: LpSysPower,
202}
203
204impl PowerSleepConfig {
205    fn defaults(pd_flags: PowerDownFlags) -> Self {
206        let mut this = Self {
207            hp_sys: HpSysPower::default(),
208            lp_sys_active: LpSysPower::default(),
209            lp_sys_sleep: LpSysPower::default(),
210        };
211        this.apply_flags(pd_flags);
212        this
213    }
214
215    fn apply_flags(&mut self, pd_flags: PowerDownFlags) {
216        // PMU_SLEEP_POWER_CONFIG_DEFAULT
217        self.hp_sys
218            .dig_power
219            .set_vdd_spi_pd_en(pd_flags.pd_vddsdio());
220        self.hp_sys
221            .dig_power
222            .set_hp_alive_pd_en(pd_flags.pd_mem() || pd_flags.pd_hp_aon());
223        self.hp_sys
224            .dig_power
225            .set_modem_top_pd_en(pd_flags.pd_modem());
226        self.hp_sys.dig_power.set_hp_cnnt_pd_en(pd_flags.pd_modem());
227        self.hp_sys.dig_power.set_hp_cpu_pd_en(pd_flags.pd_cpu());
228        self.hp_sys.dig_power.set_modem_pwr_pd_en(pd_flags.pd_mem());
229        self.hp_sys.dig_power.set_top_pd_en(pd_flags.pd_top());
230
231        self.hp_sys.clk.set_i2c_iso_en(true);
232        self.hp_sys.clk.set_i2c_retention(true);
233
234        self.hp_sys.xtal.set_xpd_xtal(pd_flags.pd_xtal().not());
235
236        self.lp_sys_active
237            .clk_power
238            .set_xpd_xtal32k(pd_flags.pd_xtal32k().not());
239        self.lp_sys_active
240            .clk_power
241            .set_xpd_rc32k(pd_flags.pd_rc32k().not());
242        self.lp_sys_active.clk_power.set_xpd_fosc(true);
243
244        self.lp_sys_sleep
245            .dig_power
246            .set_peri_pd_en(pd_flags.pd_lp_periph());
247
248        self.lp_sys_sleep
249            .clk_power
250            .set_xpd_xtal32k(pd_flags.pd_xtal32k().not());
251        self.lp_sys_sleep
252            .clk_power
253            .set_xpd_rc32k(pd_flags.pd_rc32k().not());
254        self.lp_sys_sleep
255            .clk_power
256            .set_xpd_fosc(pd_flags.pd_rc_fast().not());
257
258        self.lp_sys_sleep
259            .xtal
260            .set_xpd_xtal(pd_flags.pd_xtal().not());
261    }
262
263    fn apply(&self, dslp: bool) {
264        // pmu_sleep_power_init
265        PMU::regs()
266            .hp_sleep_dig_power()
267            .modify(|_, w| unsafe { w.bits(self.hp_sys.dig_power.0) });
268        PMU::regs()
269            .hp_sleep_hp_ck_power()
270            .modify(|_, w| unsafe { w.bits(self.hp_sys.clk.0) });
271        PMU::regs()
272            .hp_sleep_xtal()
273            .modify(|_, w| w.hp_sleep_xpd_xtal().bit(self.hp_sys.xtal.xpd_xtal()));
274
275        set_memory_power_on_mask(!dslp);
276
277        PMU::regs()
278            .hp_sleep_lp_dig_power()
279            .modify(|_, w| unsafe { w.bits(self.lp_sys_active.dig_power.0) });
280        PMU::regs()
281            .hp_sleep_lp_ck_power()
282            .modify(|_, w| unsafe { w.bits(self.lp_sys_active.clk_power.0) });
283
284        PMU::regs()
285            .lp_sleep_lp_dig_power()
286            .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.dig_power.0) });
287        PMU::regs()
288            .lp_sleep_lp_ck_power()
289            .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.clk_power.0) });
290        PMU::regs()
291            .lp_sleep_xtal()
292            .modify(|_, w| w.lp_sleep_xpd_xtal().bit(self.lp_sys_sleep.xtal.xpd_xtal()));
293    }
294}
295
296fn set_memory_power_on_mask(keep_on: bool) {
297    // pmu_ll_hp_set_memory_power_on_mask: 0 in deep sleep, 0xf in light sleep.
298    let mask = if keep_on { 0x1f } else { 0 };
299    PMU::regs().power_pd_mem_mask().modify(|_, w| unsafe {
300        w.pd_hp_mem0_mask().bits(mask);
301        w.pd_hp_mem1_mask().bits(mask);
302        w.pd_hp_mem2_mask().bits(mask)
303    });
304    PMU::regs().power_pd_mem_cntl().modify(|r, w| unsafe {
305        let mut pu = r.force_hp_mem_pu().bits();
306        if keep_on {
307            pu |= 1 << 3;
308        } else {
309            pu &= !(1 << 3);
310        }
311        w.force_hp_mem_pu().bits(pu)
312    });
313}
314
315/// High-power system sleep timing parameters.
316#[derive(Clone, Copy, Default)]
317pub struct HpParam {
318    analog_wait_target_cycle: u16,
319    digital_power_supply_wait_cycle: u16,
320    digital_power_up_wait_cycle: u16,
321    pll_stable_wait_cycle: u16,
322    modem_wakeup_wait_cycle: u32,
323    isolate_wait_cycle: u8,
324    reset_wait_cycle: u8,
325    min_slp_slow_clk_cycle: u8,
326}
327
328/// Low-power system sleep timing parameters.
329#[derive(Clone, Copy, Default)]
330pub struct LpParam {
331    digital_power_supply_wait_cycle: u16,
332    min_slp_slow_clk_cycle: u8,
333    analog_wait_target_cycle: u8,
334    digital_power_up_wait_cycle: u8,
335    isolate_wait_cycle: u8,
336    reset_wait_cycle: u8,
337}
338
339/// Shared HP/LP sleep timing parameters.
340#[derive(Clone, Copy, Default)]
341pub struct HpLpParam {
342    xtal_stable_wait_cycle: u16,
343}
344
345/// Sleep timing parameter configuration.
346#[derive(Clone, Copy)]
347pub struct ParamSleepConfig {
348    hp_sys: HpParam,
349    lp_sys: LpParam,
350    hp_lp: HpLpParam,
351}
352
353impl ParamSleepConfig {
354    fn apply(&self) {
355        // pmu_sleep_param_init
356        PMU::regs().slp_wakeup_cntl3().modify(|_, w| unsafe {
357            w.hp_min_slp_val().bits(self.hp_sys.min_slp_slow_clk_cycle);
358            w.lp_min_slp_val().bits(self.lp_sys.min_slp_slow_clk_cycle)
359        });
360
361        PMU::regs().slp_wakeup_cntl7().modify(|_, w| unsafe {
362            w.ana_wait_target()
363                .bits(self.hp_sys.analog_wait_target_cycle)
364        });
365
366        PMU::regs().power_wait_timer0().modify(|_, w| unsafe {
367            w.dg_hp_pd_wait_timer()
368                .bits(self.hp_sys.digital_power_supply_wait_cycle);
369            w.dg_hp_powerup_timer()
370                .bits(self.hp_sys.digital_power_up_wait_cycle)
371        });
372
373        PMU::regs().power_wait_timer1().modify(|_, w| unsafe {
374            w.dg_lp_pd_wait_timer()
375                .bits(self.lp_sys.digital_power_supply_wait_cycle);
376            w.dg_lp_powerup_timer()
377                .bits(self.lp_sys.digital_power_up_wait_cycle)
378        });
379
380        PMU::regs().power_wait_timer2().modify(|_, w| unsafe {
381            w.dg_hp_iso_wait_timer()
382                .bits(self.hp_sys.isolate_wait_cycle);
383            w.dg_hp_rst_wait_timer().bits(self.hp_sys.reset_wait_cycle);
384            w.dg_lp_iso_wait_timer()
385                .bits(self.lp_sys.isolate_wait_cycle);
386            w.dg_lp_rst_wait_timer().bits(self.lp_sys.reset_wait_cycle)
387        });
388
389        PMU::regs().slp_wakeup_cntl5().modify(|_, w| unsafe {
390            w.lp_ana_wait_target()
391                .bits(self.lp_sys.analog_wait_target_cycle);
392            w.modem_wait_target()
393                .bits(self.hp_sys.modem_wakeup_wait_cycle)
394        });
395
396        PMU::regs().power_ck_wait_cntl().modify(|_, w| unsafe {
397            w.pmu_wait_xtl_stable()
398                .bits(self.hp_lp.xtal_stable_wait_cycle);
399            w.pmu_wait_pll_stable()
400                .bits(self.hp_sys.pll_stable_wait_cycle)
401        });
402    }
403
404    fn defaults(config: SleepTimeConfig, pd_flags: PowerDownFlags, xpd_xtal: bool) -> Self {
405        let hw_wait_time_us = config.pmu_sleep_calculate_hw_wait_time(pd_flags);
406        let modem_wakeup_wait_time_us = (config.sleep_time_adjustment
407            + MachineConstants::MODEM_STATE_SKIP_TIME_US
408            + MachineConstants::HP_REGDMA_RF_ON_WORK_TIME_US)
409            .saturating_sub(hw_wait_time_us);
410
411        let hp_sys = HpParam {
412            min_slp_slow_clk_cycle: config.us_to_slowclk(MachineConstants::HP_MIN_SLP_TIME_US)
413                as u8,
414            analog_wait_target_cycle: config.us_to_fastclk(MachineConstants::HP_ANALOG_WAIT_TIME_US)
415                as u16,
416            digital_power_supply_wait_cycle: config
417                .us_to_fastclk(MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US)
418                as u16,
419            digital_power_up_wait_cycle: config
420                .us_to_fastclk(MachineConstants::HP_POWER_UP_WAIT_TIME_US)
421                as u16,
422            pll_stable_wait_cycle: config
423                .us_to_fastclk(MachineConstants::HP_PLL_WAIT_STABLE_TIME_US)
424                as u16,
425            modem_wakeup_wait_cycle: config.us_to_fastclk(modem_wakeup_wait_time_us),
426            isolate_wait_cycle: config.us_to_fastclk(MachineConstants::HP_ISOLATE_WAIT_TIME_US)
427                as u8,
428            reset_wait_cycle: config.us_to_fastclk(MachineConstants::HP_RESET_WAIT_TIME_US) as u8,
429        };
430
431        let lp_sys = LpParam {
432            min_slp_slow_clk_cycle: config.us_to_slowclk(MachineConstants::LP_MIN_SLP_TIME_US)
433                as u8,
434            analog_wait_target_cycle: config.us_to_slowclk(MachineConstants::LP_ANALOG_WAIT_TIME_US)
435                as u8,
436            digital_power_supply_wait_cycle: config
437                .us_to_fastclk(MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US)
438                as u16,
439            digital_power_up_wait_cycle: config
440                .us_to_fastclk(MachineConstants::LP_POWER_UP_WAIT_TIME_US)
441                as u8,
442            isolate_wait_cycle: config.us_to_fastclk(MachineConstants::LP_ISOLATE_WAIT_TIME_US)
443                as u8,
444            reset_wait_cycle: config.us_to_fastclk(MachineConstants::LP_RESET_WAIT_TIME_US) as u8,
445        };
446
447        let xtal_stable_wait_cycle = if xpd_xtal {
448            config.us_to_slowclk(MachineConstants::LP_XTAL_WAIT_STABLE_TIME_US) as u16
449        } else {
450            config.us_to_fastclk(MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US) as u16
451        };
452
453        Self {
454            hp_sys,
455            lp_sys,
456            hp_lp: HpLpParam {
457                xtal_stable_wait_cycle,
458            },
459        }
460    }
461}
462
463impl SleepTimeConfig {
464    pub(crate) const CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ: u32 = 160;
465    pub(crate) const LIGHT_SLEEP_TIME_OVERHEAD_US: u32 = 780;
466
467    pub(crate) fn pmu_sleep_calculate_hw_wait_time(&self, pd_flags: PowerDownFlags) -> u32 {
468        let lp_wakeup_wait_time_us = self.slowclk_to_us(MachineConstants::LP_WAKEUP_WAIT_CYCLE);
469        let lp_clk_switch_time_us = self.slowclk_to_us(MachineConstants::LP_CLK_SWITCH_CYCLE);
470        let lp_clk_power_on_wait_time_us =
471            self.slowclk_to_us(MachineConstants::LP_CLK_POWER_ON_WAIT_CYCLE);
472        let lp_control_wait_time_us =
473            MachineConstants::LP_ISOLATE_WAIT_TIME_US + MachineConstants::LP_RESET_WAIT_TIME_US;
474
475        let lp_hw_wait_time_us = MachineConstants::LP_MIN_SLP_TIME_US
476            + MachineConstants::LP_ANALOG_WAIT_TIME_US
477            + lp_clk_power_on_wait_time_us
478            + lp_wakeup_wait_time_us
479            + lp_clk_switch_time_us
480            + MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US
481            + MachineConstants::LP_POWER_UP_WAIT_TIME_US
482            + lp_control_wait_time_us;
483
484        let hp_digital_power_up_wait_time_us = MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US
485            + MachineConstants::HP_POWER_UP_WAIT_TIME_US;
486        let hp_control_wait_time_us =
487            MachineConstants::HP_ISOLATE_WAIT_TIME_US + MachineConstants::HP_RESET_WAIT_TIME_US;
488        // The sleep backs up no register with REGDMA, so the wake needs no restore time.
489        let hp_regdma_wait_time_us = 0;
490        let hp_clock_wait_time_us = if pd_flags.pd_xtal() {
491            MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US
492                + MachineConstants::HP_PLL_WAIT_STABLE_TIME_US
493        } else {
494            MachineConstants::HP_PLL_WAIT_STABLE_TIME_US
495        };
496
497        let hp_hw_wait_time_us = MachineConstants::HP_ANALOG_WAIT_TIME_US
498            + hp_digital_power_up_wait_time_us
499            + hp_regdma_wait_time_us
500            + hp_clock_wait_time_us
501            + hp_control_wait_time_us;
502
503        lp_hw_wait_time_us + hp_hw_wait_time_us
504    }
505}
506
507/// Configuration for the RTC sleep behavior.
508#[derive(Clone, Copy)]
509pub struct RtcSleepConfig {
510    /// Deep sleep flag.
511    pub deep: bool,
512    /// Power-down flags.
513    pub pd_flags: PowerDownFlags,
514}
515
516impl Default for RtcSleepConfig {
517    fn default() -> Self {
518        Self {
519            deep: false,
520            pd_flags: PowerDownFlags(0),
521        }
522    }
523}
524
525bitfield::bitfield! {
526    #[derive(Clone, Copy)]
527    /// Power domains to be powered down during sleep.
528    pub struct PowerDownFlags(u32);
529
530    /// Controls the power-down status of the top power domain.
531    pub u32, pd_top      , set_pd_top      : 0;
532    /// Controls the power-down status of the VDD_SDIO power domain.
533    pub u32, pd_vddsdio  , set_pd_vddsdio  : 1;
534    /// Controls the power-down status of the modem / connectivity power domain.
535    pub u32, pd_modem    , set_pd_modem    : 2;
536    /// Controls the power-down status of the high-performance peripheral power domain.
537    pub u32, pd_hp_periph, set_pd_hp_periph: 3;
538    /// Controls the power-down status of the CPU power domain.
539    ///
540    /// Crate-private, because a light sleep needs CPU retention to power this domain down. A
541    /// power-down without retention loses the CPU state.
542    pub(crate) u32, pd_cpu, set_pd_cpu: 4;
543    /// Controls the power-down status of the high-performance always-on domain.
544    pub u32, pd_hp_aon   , set_pd_hp_aon   : 5;
545    /// Controls the power-down status of memory group 0.
546    pub u32, pd_mem_g0   , set_pd_mem_g0   : 6;
547    /// Controls the power-down status of memory group 1.
548    pub u32, pd_mem_g1   , set_pd_mem_g1   : 7;
549    /// Controls the power-down status of memory group 2.
550    pub u32, pd_mem_g2   , set_pd_mem_g2   : 8;
551    /// Controls the power-down status of memory group 3.
552    pub u32, pd_mem_g3   , set_pd_mem_g3   : 9;
553    /// Controls the power-down status of the crystal oscillator.
554    pub u32, pd_xtal     , set_pd_xtal     : 10;
555    /// Controls the power-down status of the fast RC oscillator.
556    pub u32, pd_rc_fast  , set_pd_rc_fast  : 11;
557    /// Controls the power-down status of the 32 kHz crystal oscillator.
558    pub u32, pd_xtal32k  , set_pd_xtal32k  : 12;
559    /// Controls the power-down status of the 32 kHz RC oscillator.
560    pub u32, pd_rc32k    , set_pd_rc32k    : 13;
561    /// Controls the power-down status of the low-power peripheral domain.
562    pub u32, pd_lp_periph, set_pd_lp_periph: 14;
563}
564
565impl PowerDownFlags {
566    /// Returns whether all memory groups are powered down.
567    pub fn pd_mem(self) -> bool {
568        self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3()
569    }
570
571    /// Sets the power-down status for all memory groups at once.
572    pub fn set_pd_mem(&mut self, value: bool) {
573        self.set_pd_mem_g0(value);
574        self.set_pd_mem_g1(value);
575        self.set_pd_mem_g2(value);
576        self.set_pd_mem_g3(value);
577    }
578}
579
580// Constants from `PMU_SLEEP_MC_DEFAULT()` in esp-idf pmu_param.h.
581struct MachineConstants;
582impl MachineConstants {
583    const LP_MIN_SLP_TIME_US: u32 = 450;
584    const LP_WAKEUP_WAIT_CYCLE: u32 = 4;
585    const LP_ANALOG_WAIT_TIME_US: u32 = 154;
586    const LP_XTAL_WAIT_STABLE_TIME_US: u32 = 250;
587    const LP_CLK_SWITCH_CYCLE: u32 = 1;
588    const LP_CLK_POWER_ON_WAIT_CYCLE: u32 = 1;
589    const LP_ISOLATE_WAIT_TIME_US: u32 = 1;
590    const LP_RESET_WAIT_TIME_US: u32 = 1;
591    const LP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2;
592    const LP_POWER_UP_WAIT_TIME_US: u32 = 2;
593
594    const HP_MIN_SLP_TIME_US: u32 = 450;
595    const HP_ANALOG_WAIT_TIME_US: u32 = 154;
596    const HP_ISOLATE_WAIT_TIME_US: u32 = 1;
597    const HP_RESET_WAIT_TIME_US: u32 = 1;
598    const HP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2;
599    const HP_POWER_UP_WAIT_TIME_US: u32 = 2;
600    const HP_REGDMA_M2A_WORK_TIME_US: u32 = 278;
601    const HP_REGDMA_RF_ON_WORK_TIME_US: u32 = 70;
602    const HP_SYSTEM_DFS_UP_WORK_TIME_US: u32 = 124;
603    const HP_XTAL_WAIT_STABLE_TIME_US: u32 = 250;
604    const HP_PLL_WAIT_STABLE_TIME_US: u32 = 50;
605
606    const MODEM_STATE_SKIP_TIME_US: u32 = Self::HP_REGDMA_M2A_WORK_TIME_US
607        + Self::HP_SYSTEM_DFS_UP_WORK_TIME_US
608        + Self::LP_MIN_SLP_TIME_US;
609}
610
611impl RtcSleepConfig {
612    /// Returns whether the device is in deep sleep mode.
613    pub fn deep_slp(&self) -> bool {
614        self.deep
615    }
616
617    /// Configures the device for deep sleep mode.
618    pub fn deep() -> Self {
619        Self {
620            deep: true,
621            ..Self::default()
622        }
623    }
624
625    pub(crate) fn is_deep_sleep(&self) -> bool {
626        self.deep
627    }
628
629    pub(crate) fn base_settings(_rtc: &Rtc<'_>) {}
630
631    /// Selects the kind of the sleep, and what the sleep powers down.
632    ///
633    /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep
634    /// powered what it needs.
635    pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) {
636        self.deep = kind == SleepKind::Deep;
637
638        let lp_slow_uses_xtal32k = cfg_select! {
639            use_xtal32k => ClockTree::with(|clocks| {
640                matches!(
641                    clocks::lp_slow_clk_config(clocks),
642                    Some(clocks::LpSlowClkConfig::Xtal32k)
643                )
644            }),
645            _ => false,
646        };
647
648        if self.deep {
649            self.pd_flags.set_pd_top(true);
650            self.pd_flags.set_pd_vddsdio(true);
651            self.pd_flags.set_pd_modem(true);
652            self.pd_flags.set_pd_hp_periph(true);
653            self.pd_flags.set_pd_cpu(true);
654            self.pd_flags.set_pd_mem(true);
655            self.pd_flags.set_pd_xtal(true);
656            self.pd_flags.set_pd_hp_aon(true);
657            self.pd_flags.set_pd_lp_periph(true);
658            self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k);
659            self.pd_flags.set_pd_rc32k(true);
660            self.pd_flags.set_pd_rc_fast(true);
661        } else {
662            self.pd_flags.set_pd_xtal(true);
663            self.pd_flags.set_pd_rc_fast(true);
664            self.pd_flags
665                .set_pd_xtal32k(!lp_slow_uses_xtal32k && !xtal32k::use_xtal32k());
666        }
667    }
668
669    /// Configures the wakeup and reject sources of the sleep.
670    ///
671    /// [`Self::enter_sleep`] requests the sleep after this call. The caller calls
672    /// [`SavedState::restore`] on the return value after [`Self::finish_sleep`].
673    #[crate::ram]
674    pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> SavedState {
675        let cpu_root_clk = ClockTree::with(|clocks| {
676            let old = clocks.cpu_root_clk();
677            clocks::configure_cpu_root_clk(clocks, CpuRootClkConfig::Xtal);
678            old
679        });
680
681        let power = PowerSleepConfig::defaults(self.pd_flags);
682        power.apply(self.deep);
683
684        let config = if self.deep {
685            SleepTimeConfig::deep_sleep()
686        } else {
687            SleepTimeConfig::light_sleep(self.pd_flags)
688        };
689
690        let mut param =
691            ParamSleepConfig::defaults(config, self.pd_flags, power.hp_sys.xtal.xpd_xtal());
692
693        if self.deep {
694            const PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US: u32 = 500;
695            param.lp_sys.analog_wait_target_cycle =
696                config.us_to_slowclk(PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US) as u8;
697
698            DigitalSleepConfig::defaults_deep_sleep(self.pd_flags).apply();
699            AnalogSleepConfig::defaults_deep_sleep().apply();
700        } else {
701            AnalogSleepConfig::defaults_light_sleep(self.pd_flags).apply();
702            DigitalSleepConfig::defaults_light_sleep(self.pd_flags).apply();
703        }
704
705        param.apply();
706
707        // lp_aon_hal_inform_wakeup_type: RTC_SLEEP_MODE_REG is LP_STORE8.
708        LP_AON::regs()
709            .lp_store(8)
710            .modify(|r, w| unsafe { w.bits(r.bits() & !0x01 | self.deep as u32) });
711
712        PMU::regs()
713            .slp_wakeup_cntl2()
714            .write(|w| unsafe { w.bits(wakeup_mask) });
715
716        PMU::regs()
717            .slp_wakeup_cntl1()
718            .write(|w| unsafe { w.sleep_reject_ena().bits(reject_mask) });
719
720        PMU::regs()
721            .slp_wakeup_cntl4()
722            .write(|w| w.slp_reject_cause_clr().bit(true));
723
724        PMU::regs().int_clr().write(|w| {
725            w.sw().clear_bit_by_one();
726            w.soc_sleep_reject().clear_bit_by_one();
727            w.soc_wakeup().clear_bit_by_one()
728        });
729
730        PMU::regs()
731            .slp_wakeup_cntl0()
732            .write(|w| w.slp_reject_en().bit(reject_mask != 0));
733
734        SavedState { cpu_root_clk }
735    }
736
737    /// Requests the sleep.
738    ///
739    /// The caller waits for the result of the request.
740    #[inline(always)]
741    pub(crate) fn enter_sleep(&self) -> bool {
742        request_sleep()
743    }
744
745    /// Cleans up after sleep.
746    #[inline(always)]
747    pub(crate) fn finish_sleep(&self) {
748        super::pmu_common::wait_for_efuse_idle();
749    }
750}
751
752/// The state that [`RtcSleepConfig::start_sleep`] changes for the length of the sleep.
753#[must_use]
754pub(crate) struct SavedState {
755    cpu_root_clk: Option<CpuRootClkConfig>,
756}
757
758impl SavedState {
759    /// Restores the state. Runs after a wakeup and after a rejected sleep.
760    pub(crate) fn restore(self) {
761        ClockTree::with(|clocks| {
762            // Light sleep powers XTAL_CLK down, so the MPLL that clocks PSRAM loses its
763            // calibration. The MPLL must be calibrated again before the next PSRAM access.
764            clocks::recalibrate_mpll(clocks);
765            // Light sleep powers XTAL_CLK down, so the CPLL loses its calibration. The CPLL must
766            // be calibrated again before the CPU or the flash controller runs from it.
767            clocks::recalibrate_cpll(clocks);
768            if let Some(cpu_root_clk) = self.cpu_root_clk {
769                clocks::configure_cpu_root_clk(clocks, cpu_root_clk);
770            }
771        });
772    }
773}