Skip to main content

esp_hal/rtc_cntl/sleep/
esp32c3.rs

1use super::{TimerWakeupSource, WakeSource, WakeTriggers, WakeupLevel};
2use crate::{
3    gpio::{RtcFunction, RtcPinWithResistors},
4    peripherals::{APB_CTRL, BB, EXTMEM, FE, FE2, GPIO, IO_MUX, LPWR, NRX, SPI0, SPI1, SYSTEM},
5    rtc_cntl::{Rtc, sleep::RtcioWakeupSource},
6    soc::regi2c,
7};
8
9// Approximate mapping of voltages to RTC_CNTL_DBIAS_WAK, RTC_CNTL_DBIAS_SLP,
10// RTC_CNTL_DIG_DBIAS_WAK, RTC_CNTL_DIG_DBIAS_SLP values.
11// Valid if RTC_CNTL_DBG_ATTEN is 0.
12/// Digital bias voltage level of 0.90V.
13pub const RTC_CNTL_DBIAS_0V90: u8 = 13;
14/// Digital bias voltage level of 0.95V.
15pub const RTC_CNTL_DBIAS_0V95: u8 = 16;
16/// Digital bias voltage level of 1.00V.
17pub const RTC_CNTL_DBIAS_1V00: u8 = 18;
18/// Digital bias voltage level of 1.05V.
19pub const RTC_CNTL_DBIAS_1V05: u8 = 20;
20/// Digital bias voltage level of 1.10V.
21pub const RTC_CNTL_DBIAS_1V10: u8 = 23;
22/// Digital bias voltage level of 1.15V.
23pub const RTC_CNTL_DBIAS_1V15: u8 = 25;
24/// Digital bias voltage level of 1.20V.
25pub const RTC_CNTL_DBIAS_1V20: u8 = 28;
26/// Digital bias voltage level of 1.25V.
27pub const RTC_CNTL_DBIAS_1V25: u8 = 30;
28/// Digital bias voltage level of approximately 1.34V.
29pub const RTC_CNTL_DBIAS_1V30: u8 = 31;
30
31/// Default attenuation setting during light sleep, with a voltage drop.
32pub const RTC_CNTL_DBG_ATTEN_LIGHTSLEEP_DEFAULT: u8 = 5;
33/// No attenuation (no voltage drop) during light sleep.
34pub const RTC_CNTL_DBG_ATTEN_LIGHTSLEEP_NODROP: u8 = 0;
35/// Default attenuation setting during deep sleep, with maximum voltage drop.
36pub const RTC_CNTL_DBG_ATTEN_DEEPSLEEP_DEFAULT: u8 = 15;
37/// No attenuation (no voltage drop) during deep sleep.
38pub const RTC_CNTL_DBG_ATTEN_DEEPSLEEP_NODROP: u8 = 0;
39
40/// Default bias setting during sleep mode.
41pub const RTC_CNTL_BIASSLP_SLEEP_DEFAULT: u8 = 1;
42/// Keeps the bias for ultra-low power sleep mode always on.
43pub const RTC_CNTL_BIASSLP_SLEEP_ON: u8 = 0;
44
45/// Default power-down current setting during sleep mode.
46pub const RTC_CNTL_PD_CUR_SLEEP_DEFAULT: u8 = 1;
47/// Keeps the power-down current setting for sleep mode always on.
48pub const RTC_CNTL_PD_CUR_SLEEP_ON: u8 = 0;
49
50/// Default driver bias setting for the digital domain during sleep mode.
51pub const RTC_CNTL_DG_VDD_DRV_B_SLP_DEFAULT: u8 = 254;
52
53/// Default debug attenuation setting for the monitor mode.
54pub const RTC_CNTL_DBG_ATTEN_MONITOR_DEFAULT: u8 = 0;
55/// Default bias setting for sleep mode in the monitor mode.
56pub const RTC_CNTL_BIASSLP_MONITOR_DEFAULT: bool = false;
57/// Default power-down current setting for the monitor mode.
58pub const RTC_CNTL_PD_CUR_MONITOR_DEFAULT: bool = false;
59
60/// Default number of cycles to wait for the PLL buffer to stabilize.
61pub const RTC_CNTL_PLL_BUF_WAIT_DEFAULT: u8 = 20;
62/// Default number of cycles to wait for the XTL buffer to stabilize.
63pub const RTC_CNTL_XTL_BUF_WAIT_DEFAULT: u8 = 100;
64/// Default number of cycles to wait for the internal 8MHz clock to stabilize.
65pub const RTC_CNTL_CK8M_WAIT_DEFAULT: u8 = 20;
66/// Default number of cycles required to enable the internal 8MHz clock.
67pub const RTC_CK8M_ENABLE_WAIT_DEFAULT: u8 = 5;
68
69/// Minimum number of cycles for sleep duration.
70pub const RTC_CNTL_MIN_SLP_VAL_MIN: u8 = 2;
71
72/// Power-up cycles for other hardware blocks.
73pub const OTHER_BLOCKS_POWERUP: u8 = 1;
74/// Wait cycles for other hardware blocks to stabilize.
75pub const OTHER_BLOCKS_WAIT: u16 = 1;
76
77/// Disables GPIO interrupt.
78pub const GPIO_INTR_DISABLE: u8 = 0;
79/// Sets GPIO interrupt to trigger on a low level signal.
80pub const GPIO_INTR_LOW_LEVEL: u8 = 4;
81/// Sets GPIO interrupt to trigger on a high level signal.
82pub const GPIO_INTR_HIGH_LEVEL: u8 = 5;
83
84/// Specifies the function configuration for GPIO pins.
85pub const PIN_FUNC_GPIO: u8 = 1;
86/// Index for signaling GPIO output.
87pub const SIG_GPIO_OUT_IDX: u32 = 128;
88/// Maximum number of GPIO pins supported.
89pub const GPIO_NUM_MAX: usize = 22;
90
91impl WakeSource for TimerWakeupSource {
92    fn apply(
93        &self,
94        rtc: &Rtc<'_>,
95        triggers: &mut WakeTriggers,
96        _sleep_config: &mut RtcSleepConfig,
97    ) {
98        triggers.set_timer(true);
99        // TODO: maybe add check to prevent overflow?
100        let ticks = crate::clock::us_to_rtc_ticks(self.duration.as_micros() as u64);
101        // "alarm" time in slow rtc ticks
102        let now = rtc.time_since_boot_raw();
103        let time_in_ticks = now + ticks;
104        unsafe {
105            LPWR::regs()
106                .slp_timer0()
107                .write(|w| w.slp_val_lo().bits((time_in_ticks & 0xffffffff) as u32));
108
109            LPWR::regs()
110                .int_clr()
111                .write(|w| w.main_timer().clear_bit_by_one());
112
113            LPWR::regs().slp_timer1().write(|w| {
114                w.slp_val_hi()
115                    .bits(((time_in_ticks >> 32) & 0xffff) as u16)
116                    .main_timer_alarm_en()
117                    .set_bit()
118            });
119        }
120    }
121}
122
123impl RtcioWakeupSource<'_, '_> {
124    fn apply_pin(&self, pin: &mut dyn RtcPinWithResistors, level: WakeupLevel) {
125        // The pullup/pulldown part is like in gpio_deep_sleep_wakeup_prepare
126        let level = match level {
127            WakeupLevel::High => {
128                pin.rtcio_pullup(false);
129                pin.rtcio_pulldown(true);
130                GPIO_INTR_HIGH_LEVEL
131            }
132            WakeupLevel::Low => {
133                pin.rtcio_pullup(true);
134                pin.rtcio_pulldown(false);
135                GPIO_INTR_LOW_LEVEL
136            }
137        };
138        pin.rtcio_pad_hold(true);
139
140        // apply_wakeup does the same as idf's esp_deep_sleep_enable_gpio_wakeup
141        unsafe {
142            pin.apply_wakeup(true, level);
143        }
144    }
145}
146
147fn isolate_digital_gpio() {
148    // like esp_sleep_isolate_digital_gpio
149    let rtc_cntl = LPWR::regs();
150    let io_mux = IO_MUX::regs();
151    let gpio = GPIO::regs();
152
153    let dig_iso = &rtc_cntl.dig_iso().read();
154    let deep_sleep_hold_is_en =
155        !dig_iso.dg_pad_force_unhold().bit() && dig_iso.dg_pad_autohold_en().bit();
156    if !deep_sleep_hold_is_en {
157        return;
158    }
159
160    // TODO: assert that the task stack is not in external ram
161
162    for pin_num in 0..GPIO_NUM_MAX {
163        let pin_hold = rtc_cntl.dig_pad_hold().read().bits() & (1 << pin_num) != 0;
164        if !pin_hold {
165            // input disable, like gpio_ll_input_disable
166            io_mux.gpio(pin_num).modify(|_, w| w.fun_ie().clear_bit());
167            // output disable, like gpio_ll_output_disable
168            unsafe {
169                gpio.func_out_sel_cfg(pin_num)
170                    .modify(|_, w| w.bits(SIG_GPIO_OUT_IDX));
171            }
172
173            // disable pull-up and pull-down
174            io_mux.gpio(pin_num).modify(|_, w| w.fun_wpu().clear_bit());
175            io_mux.gpio(pin_num).modify(|_, w| w.fun_wpd().clear_bit());
176
177            // make pad work as gpio (otherwise, deep_sleep bottom current will rise)
178            io_mux
179                .gpio(pin_num)
180                .modify(|_, w| unsafe { w.mcu_sel().bits(RtcFunction::Digital as u8) });
181        }
182    }
183}
184
185impl WakeSource for RtcioWakeupSource<'_, '_> {
186    fn apply(
187        &self,
188        _rtc: &Rtc<'_>,
189        triggers: &mut WakeTriggers,
190        sleep_config: &mut RtcSleepConfig,
191    ) {
192        let mut pins = self.pins.borrow_mut();
193
194        if pins.is_empty() {
195            return;
196        }
197
198        triggers.set_gpio(true);
199
200        // If deep sleep is enabled, esp_start_sleep calls
201        // gpio_deep_sleep_wakeup_prepare which sets these pullup and
202        // pulldown values. But later in esp_start_sleep it calls
203        // esp_sleep_isolate_digital_gpio, which disables the pullup and pulldown (but
204        // only if it isn't held).
205        // But it looks like gpio_deep_sleep_wakeup_prepare enables hold for all pins
206        // in the wakeup mask.
207        //
208        // So: all pins in the wake mask should get this treatment here, and all pins
209        // not in the wake mask should get
210        // - pullup and pulldowns disabled
211        // - input and output disabled, and
212        // - their func should get set to GPIO.
213        // But this last block of things gets skipped if hold is disabled globally (see
214        // gpio_ll_deep_sleep_hold_is_en)
215
216        LPWR::regs()
217            .gpio_wakeup()
218            .modify(|_, w| w.gpio_pin_clk_gate().set_bit());
219
220        LPWR::regs()
221            .ext_wakeup_conf()
222            .modify(|_, w| w.gpio_wakeup_filter().set_bit());
223
224        if sleep_config.deep_slp() {
225            for (pin, level) in pins.iter_mut() {
226                self.apply_pin(*pin, *level);
227            }
228
229            isolate_digital_gpio();
230        }
231
232        // like rtc_cntl_ll_gpio_clear_wakeup_status, as called from
233        // gpio_deep_sleep_wakeup_prepare
234        LPWR::regs()
235            .gpio_wakeup()
236            .modify(|_, w| w.gpio_wakeup_status_clr().set_bit());
237        LPWR::regs()
238            .gpio_wakeup()
239            .modify(|_, w| w.gpio_wakeup_status_clr().clear_bit());
240    }
241}
242
243// impl Drop for RtcioWakeupSource<'_, '_> {
244// fn drop(&mut self) {
245// should we have saved the pin configuration first?
246// set pin back to IO_MUX (input_enable and func have no effect when pin is sent
247// to IO_MUX)
248// let mut pins = self.pins.borrow_mut();
249// for (pin, _level) in pins.iter_mut() {
250// pin.rtc_set_config(true, false, RtcFunction::Rtc);
251// }
252// }
253// }
254
255bitfield::bitfield! {
256    #[derive(Clone, Copy)]
257    /// RTC Configuration.
258    pub struct RtcConfig(u32);
259    impl Debug;
260    /// Number of rtc_fast_clk cycles to wait for 8M clock to be ready
261    pub u8, ck8m_wait, set_ck8m_wait: 7, 0;
262    /// Number of rtc_fast_clk cycles to wait for XTAL clock to be ready
263    pub u8, xtal_wait, set_xtal_wait: 15, 8;
264    /// Number of rtc_fast_clk cycles to wait for PLL clock to be ready
265    pub u8, pll_wait, set_pll_wait: 23, 16;
266    /// Perform clock control related initialization.
267    pub clkctl_init, set_clkctl_init: 24;
268    /// Perform power control related initialization.
269    pub pwrctl_init, set_pwrctl_init: 25;
270    /// Force power down `RTC_DBOOST`.
271    pub rtc_dboost_fpd, set_rtc_dboost_fpd: 26;
272    /// Keep the XTAL oscillator powered up in sleep.
273    pub xtal_fpu, set_xtal_fpu: 27;
274    /// Keep the BBPLL oscillator powered up in sleep.
275    pub bbpll_fpu, set_bbpll_fpu: 28;
276    /// Enable clock gating when the CPU is in wait-for-interrupt state.
277    pub cpu_waiti_clk_gate, set_cpu_waiti_clk_gate: 29;
278    /// Calibrate Ocode to make bandgap voltage more precise.
279    pub cali_ocode, set_cali_ocode: 30;
280}
281
282impl Default for RtcConfig {
283    fn default() -> Self {
284        let mut cfg = Self(Default::default());
285        cfg.set_ck8m_wait(RTC_CNTL_CK8M_WAIT_DEFAULT);
286        cfg.set_xtal_wait(RTC_CNTL_XTL_BUF_WAIT_DEFAULT);
287        cfg.set_pll_wait(RTC_CNTL_PLL_BUF_WAIT_DEFAULT);
288        cfg.set_clkctl_init(true);
289        cfg.set_pwrctl_init(true);
290        cfg.set_rtc_dboost_fpd(true);
291        cfg.set_cpu_waiti_clk_gate(true);
292        cfg
293    }
294}
295
296bitfield::bitfield! {
297    #[derive(Clone, Copy)]
298    /// Configuration for RTC initialization.
299    pub struct RtcInitConfig(u128);
300    impl Debug;
301    /// Number of cycles required to power up WiFi
302    pub u8, wifi_powerup_cycles, set_wifi_powerup_cycles: 6, 0;
303    /// Number of wait cycles for WiFi to stabilize
304    pub u16, wifi_wait_cycles, set_wifi_wait_cycles: 15, 7;
305    /// Number of cycles required to power up Bluetooth
306    pub u8, bt_powerup_cycles, set_bt_powerup_cycles: 22, 16;
307    /// Number of wait cycles for Bluetooth to stabilize
308    pub u16, bt_wait_cycles, set_bt_wait_cycles: 31, 23;
309    /// Number of cycles required to power up the top CPU
310    pub u8, cpu_top_powerup_cycles, set_cpu_top_powerup_cycles: 38, 32;
311    /// Number of wait cycles for the top CPU to stabilize
312    pub u16, cpu_top_wait_cycles, set_cpu_top_wait_cycles: 47, 39;
313    /// Number of cycles required to power up the digital wrapper
314    pub u8, dg_wrap_powerup_cycles, set_dg_wrap_powerup_cycles: 54, 48;
315    /// Number of wait cycles for the digital wrapper to stabilize
316    pub u16, dg_wrap_wait_cycles, set_dg_wrap_wait_cycles: 63, 55;
317    /// Number of cycles required to power up the digital peripherals
318    pub u8, dg_peri_powerup_cycles, set_dg_peri_powerup_cycles: 70, 64;
319    /// Number of wait cycles for the digital peripherals to stabilize
320    pub u16, dg_peri_wait_cycles, set_dg_peri_wait_cycles: 79, 71;
321}
322
323impl Default for RtcInitConfig {
324    fn default() -> Self {
325        let mut cfg = Self(Default::default());
326        cfg.set_wifi_powerup_cycles(OTHER_BLOCKS_POWERUP);
327        cfg.set_bt_powerup_cycles(OTHER_BLOCKS_POWERUP);
328        cfg.set_cpu_top_powerup_cycles(OTHER_BLOCKS_POWERUP);
329        cfg.set_dg_wrap_powerup_cycles(OTHER_BLOCKS_POWERUP);
330        cfg.set_dg_peri_powerup_cycles(OTHER_BLOCKS_POWERUP);
331        cfg.set_wifi_wait_cycles(OTHER_BLOCKS_WAIT);
332        cfg.set_bt_wait_cycles(OTHER_BLOCKS_WAIT);
333        cfg.set_cpu_top_wait_cycles(OTHER_BLOCKS_WAIT);
334        cfg.set_dg_wrap_wait_cycles(OTHER_BLOCKS_WAIT);
335        cfg.set_dg_peri_wait_cycles(OTHER_BLOCKS_WAIT);
336        cfg
337    }
338}
339
340bitfield::bitfield! {
341    #[derive(Clone, Copy)]
342    /// Configuration for RTC sleep mode.
343    pub struct RtcSleepConfig(u64);
344    impl Debug;
345    /// force normal voltage in sleep mode (digital domain memory)
346    pub lslp_mem_inf_fpu, set_lslp_mem_inf_fpu: 0;
347    /// keep low voltage in sleep mode (even if ULP/touch is used)
348    pub rtc_mem_inf_follow_cpu, set_rtc_mem_inf_follow_cpu: 1;
349    /// power down RTC fast memory
350    pub rtc_fastmem_pd_en, set_rtc_fastmem_pd_en: 2;
351    /// power down RTC slow memory
352    pub rtc_slowmem_pd_en, set_rtc_slowmem_pd_en: 3;
353    /// power down RTC peripherals
354    pub rtc_peri_pd_en, set_rtc_peri_pd_en: 4;
355    /// power down WiFi
356    pub wifi_pd_en, set_wifi_pd_en: 5;
357    /// power down BT
358    pub bt_pd_en, set_bt_pd_en: 6;
359    /// power down CPU, but not restart when lightsleep.
360    pub cpu_pd_en, set_cpu_pd_en: 7;
361    /// Power down Internal 8M oscillator
362    pub int_8m_pd_en, set_int_8m_pd_en: 8;
363    /// power down digital peripherals
364    pub dig_peri_pd_en, set_dig_peri_pd_en: 9;
365    /// power down digital domain
366    pub deep_slp, set_deep_slp: 10;
367    /// enable WDT flashboot mode
368    pub wdt_flashboot_mod_en, set_wdt_flashboot_mod_en: 11;
369    /// set bias for digital domain, in sleep mode
370    pub u8, dig_dbias_slp, set_dig_dbias_slp: 16, 12;
371    /// set bias for RTC domain, in sleep mode
372    pub u8, rtc_dbias_slp, set_rtc_dbias_slp: 21, 17;
373    /// voltage parameter, in sleep mode
374    pub u8, dbg_atten_slp, set_dbg_atten_slp: 25, 22;
375    /// circuit control parameter, in monitor mode
376    pub bias_sleep_monitor, set_bias_sleep_monitor: 26;
377    /// circuit control parameter, in sleep mode
378    pub bias_sleep_slp, set_bias_sleep_slp: 27;
379    /// circuit control parameter, in monitor mode
380    pub pd_cur_slp, set_pd_cur_slp: 28;
381    /// power down VDDSDIO regulator
382    pub vddsdio_pd_en, set_vddsdio_pd_en: 29;
383    /// keep main XTAL powered up in sleep
384    pub xtal_fpu, set_xtal_fpu: 30;
385    /// keep rtc regulator powered up in sleep
386    pub rtc_regulator_fpu, set_rtc_regulator_fpu: 31;
387    /// enable deep sleep reject
388    pub deep_slp_reject, set_deep_slp_reject: 32;
389    /// enable light sleep reject
390    pub light_slp_reject, set_light_slp_reject: 33;
391}
392
393impl Default for RtcSleepConfig {
394    fn default() -> Self {
395        let mut cfg = Self(Default::default());
396        cfg.set_deep_slp_reject(true);
397        cfg.set_light_slp_reject(true);
398        cfg.set_rtc_dbias_slp(RTC_CNTL_DBIAS_1V10);
399        cfg.set_dig_dbias_slp(RTC_CNTL_DBIAS_1V10);
400        cfg
401    }
402}
403
404const SYSCON_SRAM_POWER_UP: u8 = 0x0000000F;
405const SYSCON_ROM_POWER_UP: u8 = 0x00000003;
406
407fn rtc_sleep_pu(val: bool) {
408    LPWR::regs()
409        .dig_pwc()
410        .modify(|_, w| w.lslp_mem_force_pu().bit(val).fastmem_force_lpu().bit(val));
411
412    APB_CTRL::regs().front_end_mem_pd().modify(|_r, w| {
413        w.dc_mem_force_pu()
414            .bit(val)
415            .pbus_mem_force_pu()
416            .bit(val)
417            .agc_mem_force_pu()
418            .bit(val)
419    });
420
421    BB::regs()
422        .bbpd_ctrl()
423        .modify(|_r, w| w.fft_force_pu().bit(val).dc_est_force_pu().bit(val));
424
425    NRX::regs().nrxpd_ctrl().modify(|_, w| {
426        w.rx_rot_force_pu()
427            .bit(val)
428            .vit_force_pu()
429            .bit(val)
430            .demap_force_pu()
431            .bit(val)
432    });
433
434    FE::regs()
435        .gen_ctrl()
436        .modify(|_, w| w.iq_est_force_pu().bit(val));
437
438    FE2::regs()
439        .tx_interp_ctrl()
440        .modify(|_, w| w.tx_inf_force_pu().bit(val));
441
442    APB_CTRL::regs().mem_power_up().modify(|_r, w| unsafe {
443        w.sram_power_up()
444            .bits(if val { SYSCON_SRAM_POWER_UP } else { 0 })
445            .rom_power_up()
446            .bits(if val { SYSCON_ROM_POWER_UP } else { 0 })
447    });
448}
449
450impl RtcSleepConfig {
451    /// Configures the RTC for deep sleep mode.
452    pub fn deep() -> Self {
453        // Set up for ultra-low power sleep. Wakeup sources may modify these settings.
454        let mut cfg = Self::default();
455
456        cfg.set_lslp_mem_inf_fpu(false);
457        cfg.set_rtc_mem_inf_follow_cpu(true); // ?
458        cfg.set_rtc_fastmem_pd_en(true);
459        cfg.set_rtc_slowmem_pd_en(true);
460        cfg.set_rtc_peri_pd_en(true);
461        cfg.set_wifi_pd_en(true);
462        cfg.set_bt_pd_en(true);
463        cfg.set_cpu_pd_en(true);
464        cfg.set_int_8m_pd_en(true);
465
466        cfg.set_dig_peri_pd_en(true);
467        cfg.set_dig_dbias_slp(0); // because of dig_peri_pd_en
468
469        cfg.set_deep_slp(true);
470        cfg.set_wdt_flashboot_mod_en(false);
471        cfg.set_vddsdio_pd_en(true);
472        cfg.set_xtal_fpu(false);
473        cfg.set_deep_slp_reject(true);
474        cfg.set_light_slp_reject(true);
475        cfg.set_rtc_dbias_slp(RTC_CNTL_DBIAS_1V10);
476
477        // because of dig_peri_pd_en
478        cfg.set_rtc_regulator_fpu(false);
479        cfg.set_dbg_atten_slp(RTC_CNTL_DBG_ATTEN_DEEPSLEEP_DEFAULT);
480
481        // because of xtal_fpu
482        cfg.set_bias_sleep_monitor(true);
483        cfg.set_bias_sleep_slp(true);
484        cfg.set_pd_cur_slp(true);
485
486        cfg
487    }
488
489    pub(crate) fn base_settings(_rtc: &Rtc<'_>) {
490        let cfg = RtcConfig::default();
491
492        // settings derived from esp_clk_init -> rtc_init
493        let rtc_cntl = LPWR::regs();
494        let extmem = EXTMEM::regs();
495        let system = SYSTEM::regs();
496
497        unsafe {
498            rtc_cntl
499                .dig_pwc()
500                .modify(|_, w| w.wifi_force_pd().clear_bit());
501
502            regi2c::I2C_DIG_REG_XPD_RTC_REG.write_field(0);
503            regi2c::I2C_DIG_REG_XPD_DIG_REG.write_field(0);
504
505            rtc_cntl.ana_conf().modify(|_, w| w.pvtmon_pu().clear_bit());
506
507            rtc_cntl.timer1().modify(|_, w| {
508                w.pll_buf_wait().bits(cfg.pll_wait());
509                w.ck8m_wait().bits(cfg.ck8m_wait())
510            });
511
512            // Moved from rtc sleep to rtc init to save sleep function running time
513            // set shortest possible sleep time limit
514
515            rtc_cntl
516                .timer5()
517                .modify(|_, w| w.min_slp_val().bits(RTC_CNTL_MIN_SLP_VAL_MIN));
518
519            let init_cfg = RtcInitConfig::default();
520
521            rtc_cntl.timer3().modify(|_, w| {
522                w
523                    // set wifi timer
524                    .wifi_powerup_timer()
525                    .bits(init_cfg.wifi_powerup_cycles())
526                    .wifi_wait_timer()
527                    .bits(init_cfg.wifi_wait_cycles())
528                    // set bt timer
529                    .bt_powerup_timer()
530                    .bits(init_cfg.bt_powerup_cycles())
531                    .bt_wait_timer()
532                    .bits(init_cfg.bt_wait_cycles())
533            });
534
535            rtc_cntl.timer4().modify(|_, w| {
536                w.cpu_top_powerup_timer()
537                    .bits(init_cfg.cpu_top_powerup_cycles())
538                    .cpu_top_wait_timer()
539                    .bits(init_cfg.cpu_top_wait_cycles())
540                    // set digital wrap timer
541                    .dg_wrap_powerup_timer()
542                    .bits(init_cfg.dg_wrap_powerup_cycles())
543                    .dg_wrap_wait_timer()
544                    .bits(init_cfg.dg_wrap_wait_cycles())
545            });
546
547            rtc_cntl.timer6().modify(|_, w| {
548                w.dg_peri_powerup_timer()
549                    .bits(init_cfg.dg_peri_powerup_cycles())
550                    .dg_peri_wait_timer()
551                    .bits(init_cfg.dg_peri_wait_cycles())
552            });
553
554            // TODO: something about cali_ocode
555
556            // Reset RTC bias to default value (needed if waking up from deep sleep)
557            regi2c::I2C_DIG_REG_EXT_RTC_DREG_SLEEP.write_field(RTC_CNTL_DBIAS_1V10);
558
559            // LDO dbias initialization
560            // TODO: this modifies g_rtc_dbias_pvt_non_240m and g_dig_dbias_pvt_non_240m.
561            //       We're using a high enough default but we should read from the efuse.
562            // set_rtc_dig_dbias();
563
564            regi2c::I2C_DIG_REG_EXT_RTC_DREG.write_field(RTC_CNTL_DBIAS_1V25);
565            regi2c::I2C_DIG_REG_EXT_DIG_DREG.write_field(RTC_CNTL_DBIAS_1V25);
566
567            if cfg.clkctl_init() {
568                // clear CMMU clock force on
569
570                extmem
571                    .cache_mmu_power_ctrl()
572                    .modify(|_, w| w.cache_mmu_mem_force_on().clear_bit());
573                // clear tag clock force on
574
575                extmem
576                    .icache_tag_power_ctrl()
577                    .modify(|_, w| w.icache_tag_mem_force_on().clear_bit());
578                // clear register clock force on
579                SPI0::regs()
580                    .clock_gate()
581                    .modify(|_, w| w.clk_en().clear_bit());
582                SPI1::regs()
583                    .clock_gate()
584                    .modify(|_, w| w.clk_en().clear_bit());
585            }
586
587            if cfg.pwrctl_init() {
588                rtc_cntl
589                    .clk_conf()
590                    .modify(|_, w| w.ck8m_force_pu().clear_bit());
591
592                rtc_cntl
593                    .options0()
594                    .modify(|_, w| w.xtl_force_pu().bit(cfg.xtal_fpu() || cfg.bbpll_fpu()));
595
596                // force pd APLL
597
598                rtc_cntl
599                    .ana_conf()
600                    .modify(|_, w| w.plla_force_pu().clear_bit().plla_force_pd().set_bit());
601
602                rtc_cntl.ana_conf().modify(|_, w| {
603                    w
604                        // open sar_i2c protect function to avoid sar_i2c reset when rtc_ldo is low.
605                        .reset_por_force_pd()
606                        .clear_bit()
607                });
608
609                // cancel bbpll force pu if setting no force power up
610
611                rtc_cntl.options0().modify(|_, w| {
612                    w.bbpll_force_pu()
613                        .bit(cfg.bbpll_fpu())
614                        .bbpll_i2c_force_pu()
615                        .bit(cfg.bbpll_fpu())
616                        .bb_i2c_force_pu()
617                        .bit(cfg.bbpll_fpu())
618                });
619
620                rtc_cntl.rtc_cntl().modify(|_, w| {
621                    w.regulator_force_pu()
622                        .clear_bit()
623                        .dboost_force_pu()
624                        .clear_bit()
625                        .dboost_force_pd()
626                        .bit(cfg.rtc_dboost_fpd())
627                });
628
629                // If this mask is enabled, all soc memories cannot enter power down mode
630                // We should control soc memory power down mode from RTC, so we will not touch
631                // this register any more
632
633                system
634                    .mem_pd_mask()
635                    .modify(|_, w| w.lslp_mem_pd_mask().clear_bit());
636
637                // If this pd_cfg is set to 1, all memory won't enter low power mode during
638                // light sleep If this pd_cfg is set to 0, all memory will enter low
639                // power mode during light sleep
640                rtc_sleep_pu(false);
641
642                rtc_cntl.dig_pwc().modify(|_, w| {
643                    w.dg_wrap_force_pu()
644                        .clear_bit()
645                        .wifi_force_pu()
646                        .clear_bit()
647                        .bt_force_pu()
648                        .clear_bit()
649                        .cpu_top_force_pu()
650                        .clear_bit()
651                        .dg_peri_force_pu()
652                        .clear_bit()
653                });
654
655                rtc_cntl.dig_iso().modify(|_, w| {
656                    w.dg_wrap_force_noiso()
657                        .clear_bit()
658                        .wifi_force_noiso()
659                        .clear_bit()
660                        .bt_force_noiso()
661                        .clear_bit()
662                        .cpu_top_force_noiso()
663                        .clear_bit()
664                        .dg_peri_force_noiso()
665                        .clear_bit()
666                });
667
668                // if SYSTEM_CPU_WAIT_MODE_FORCE_ON == 0 , the cpu clk will be closed when cpu
669                // enter WAITI mode
670
671                system
672                    .cpu_per_conf()
673                    .modify(|_, w| w.cpu_wait_mode_force_on().bit(!cfg.cpu_waiti_clk_gate()));
674
675                // cancel digital PADS force no iso
676
677                rtc_cntl.dig_iso().modify(|_, w| {
678                    w.dg_pad_force_unhold()
679                        .clear_bit()
680                        .dg_pad_force_noiso()
681                        .clear_bit()
682                });
683            }
684
685            // force power down modem(wifi and ble) power domain
686
687            rtc_cntl
688                .dig_iso()
689                .modify(|_, w| w.wifi_force_iso().set_bit().bt_force_iso().set_bit());
690
691            rtc_cntl
692                .dig_pwc()
693                .modify(|_, w| w.wifi_force_pd().set_bit().bt_force_pd().set_bit());
694
695            rtc_cntl.int_ena().write(|w| w.bits(0));
696            rtc_cntl.int_clr().write(|w| w.bits(u32::MAX));
697
698            regi2c::I2C_ULP_IR_FORCE_XPD_CK.write_field(1);
699        }
700    }
701
702    pub(crate) fn apply(&self) {
703        // like esp-idf rtc_sleep_init()
704        let rtc_cntl = LPWR::regs();
705
706        if self.lslp_mem_inf_fpu() {
707            rtc_sleep_pu(true);
708        }
709
710        if self.wifi_pd_en() {
711            rtc_cntl.dig_iso().modify(|_, w| {
712                w.wifi_force_noiso()
713                    .clear_bit()
714                    .wifi_force_iso()
715                    .clear_bit()
716            });
717
718            rtc_cntl
719                .dig_pwc()
720                .modify(|_, w| w.wifi_force_pu().clear_bit().wifi_pd_en().set_bit());
721        } else {
722            rtc_cntl.dig_pwc().modify(|_, w| w.wifi_pd_en().clear_bit());
723        }
724        if self.bt_pd_en() {
725            rtc_cntl
726                .dig_iso()
727                .modify(|_, w| w.bt_force_noiso().clear_bit().bt_force_iso().clear_bit());
728
729            rtc_cntl
730                .dig_pwc()
731                .modify(|_, w| w.bt_force_pu().clear_bit().bt_pd_en().set_bit());
732        } else {
733            rtc_cntl.dig_pwc().modify(|_, w| w.bt_pd_en().clear_bit());
734        }
735
736        rtc_cntl
737            .dig_pwc()
738            .modify(|_, w| w.cpu_top_pd_en().bit(self.cpu_pd_en()));
739
740        rtc_cntl
741            .dig_pwc()
742            .modify(|_, w| w.dg_peri_pd_en().bit(self.dig_peri_pd_en()));
743
744        unsafe {
745            rtc_cntl.bias_conf().modify(|_, w| {
746                w.dbg_atten_monitor()
747                    .bits(RTC_CNTL_DBG_ATTEN_MONITOR_DEFAULT)
748                    // We have config values for this in self, so I don't know why we're setting
749                    // hardcoded defaults for these next two. It's what IDF does...
750                    .bias_sleep_monitor()
751                    .bit(RTC_CNTL_BIASSLP_MONITOR_DEFAULT)
752                    .pd_cur_monitor()
753                    .bit(RTC_CNTL_PD_CUR_MONITOR_DEFAULT)
754            });
755
756            assert!(!self.pd_cur_slp() || self.bias_sleep_slp());
757
758            regi2c::I2C_DIG_REG_EXT_RTC_DREG_SLEEP.write_field(self.rtc_dbias_slp());
759            regi2c::I2C_DIG_REG_EXT_DIG_DREG_SLEEP.write_field(self.dig_dbias_slp());
760
761            rtc_cntl.bias_conf().modify(|_, w| {
762                w.dbg_atten_deep_slp()
763                    .bits(self.dbg_atten_slp())
764                    .bias_sleep_deep_slp()
765                    .bit(self.bias_sleep_slp())
766                    .pd_cur_deep_slp()
767                    .bit(self.pd_cur_slp())
768            });
769
770            if self.deep_slp() {
771                regi2c::I2C_ULP_IR_FORCE_XPD_CK.write_field(0);
772
773                rtc_cntl
774                    .dig_pwc()
775                    .modify(|_, w| w.dg_wrap_pd_en().set_bit());
776
777                rtc_cntl.ana_conf().modify(|_, w| {
778                    w.ckgen_i2c_pu()
779                        .clear_bit()
780                        .pll_i2c_pu()
781                        .clear_bit()
782                        .rfrx_pbus_pu()
783                        .clear_bit()
784                        .txrf_i2c_pu()
785                        .clear_bit()
786                });
787
788                rtc_cntl
789                    .options0()
790                    .modify(|_, w| w.bb_i2c_force_pu().clear_bit());
791            } else {
792                rtc_cntl.bias_conf().modify(|_, w| {
793                    w.dg_vdd_drv_b_slp_en()
794                        .set_bit()
795                        .dg_vdd_drv_b_slp()
796                        .bits(RTC_CNTL_DG_VDD_DRV_B_SLP_DEFAULT)
797                });
798
799                rtc_cntl
800                    .dig_pwc()
801                    .modify(|_, w| w.dg_wrap_pd_en().clear_bit());
802            }
803
804            // mem force pu
805
806            rtc_cntl
807                .dig_pwc()
808                .modify(|_, w| w.lslp_mem_force_pu().set_bit());
809
810            rtc_cntl
811                .rtc_cntl()
812                .modify(|_, w| w.regulator_force_pu().bit(self.rtc_regulator_fpu()));
813
814            rtc_cntl.clk_conf().modify(|_, w| {
815                w.ck8m_force_pu()
816                    .bit(!self.int_8m_pd_en())
817                    .ck8m_force_nogating()
818                    .bit(!self.int_8m_pd_en())
819            });
820
821            // enable VDDSDIO control by state machine
822
823            rtc_cntl.sdio_conf().modify(|_, w| {
824                w.sdio_force()
825                    .clear_bit()
826                    .sdio_reg_pd_en()
827                    .bit(self.vddsdio_pd_en())
828            });
829
830            rtc_cntl.slp_reject_conf().modify(|_, w| {
831                w.deep_slp_reject_en()
832                    .bit(self.deep_slp_reject())
833                    .light_slp_reject_en()
834                    .bit(self.light_slp_reject())
835            });
836
837            rtc_cntl
838                .options0()
839                .modify(|_, w| w.xtl_force_pu().bit(self.xtal_fpu()));
840
841            rtc_cntl
842                .clk_conf()
843                .modify(|_, w| w.xtal_global_force_nogating().bit(self.xtal_fpu()));
844        }
845    }
846
847    pub(crate) fn start_sleep(&self, wakeup_triggers: WakeTriggers) {
848        // set bits for what can wake us up
849        LPWR::regs()
850            .wakeup_state()
851            .modify(|_, w| unsafe { w.wakeup_ena().bits(wakeup_triggers.0.into()) });
852
853        LPWR::regs()
854            .state0()
855            .write(|w| w.sleep_en().set_bit().slp_wakeup().set_bit());
856    }
857
858    pub(crate) fn finish_sleep(&self) {
859        // In deep sleep mode, we never get here
860        LPWR::regs().int_clr().write(|w| {
861            w.slp_reject().clear_bit_by_one();
862            w.slp_wakeup().clear_bit_by_one()
863        });
864
865        // restore config if it is a light sleep
866        if self.lslp_mem_inf_fpu() {
867            rtc_sleep_pu(true);
868        }
869    }
870}