1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #pragma once
7 
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdint.h>
11 #include "stubs.h"
12 #include "soc/soc.h"
13 #include "soc/rtc_periph.h"
14 #include "soc/clk_tree_defs.h"
15 
16 #ifdef __cplusplus
17 extern "C" {
18 #endif
19 
20 /**
21  * @file rtc.h
22  * @brief Low-level RTC power, clock, and sleep functions.
23  *
24  * Functions in this file facilitate configuration of ESP32's RTC_CNTL peripheral.
25  * RTC_CNTL peripheral handles many functions:
26  * - enables/disables clocks and power to various parts of the chip; this is
27  *   done using direct register access (forcing power up or power down) or by
28  *   allowing state machines to control power and clocks automatically
29  * - handles sleep and wakeup functions
30  * - maintains a 48-bit counter which can be used for timekeeping
31  *
32  * These functions are not thread safe, and should not be viewed as high level
33  * APIs. For example, while this file provides a function which can switch
34  * CPU frequency, this function is on its own is not sufficient to implement
35  * frequency switching in ESP-IDF context: some coordination with RTOS,
36  * peripheral drivers, and WiFi/BT stacks is also required.
37  *
38  * These functions will normally not be used in applications directly.
39  * ESP-IDF provides, or will provide, drivers and other facilities to use
40  * RTC subsystem functionality.
41  *
42  * The functions are loosely split into the following groups:
43  * - rtc_clk: clock switching, calibration
44  * - rtc_time: reading RTC counter, conversion between counter values and time
45  * - rtc_sleep: entry into sleep modes
46  * - rtc_init: initialization
47  */
48 
49 /* Delays for various clock sources to be enabled/switched.
50  * All values are in microseconds.
51  */
52 #define SOC_DELAY_PLL_DBIAS_RAISE           3
53 #define SOC_DELAY_PLL_ENABLE_WITH_150K      80
54 #define SOC_DELAY_PLL_ENABLE_WITH_32K       160
55 #define SOC_DELAY_RTC_FAST_CLK_SWITCH       3
56 #define SOC_DELAY_RTC_SLOW_CLK_SWITCH       300
57 #define SOC_DELAY_RC_FAST_ENABLE            50
58 #define SOC_DELAY_RC_FAST_DIGI_SWITCH       5
59 
60 /* Core voltage needs to be increased in two cases:
61  * 1. running at 240 MHz
62  * 2. running with 80MHz Flash frequency
63  *
64  * There is a record in efuse which indicates the proper voltage for these two cases.
65  */
66 #define RTC_CNTL_DBIAS_HP_VOLT         (RTC_CNTL_DBIAS_1V25 - efuse_ll_get_vol_level_hp_inv())
67 #ifdef CONFIG_ESPTOOLPY_FLASHFREQ_80M
68 #define DIG_DBIAS_80M_160M  RTC_CNTL_DBIAS_HP_VOLT
69 #else
70 #define DIG_DBIAS_80M_160M  RTC_CNTL_DBIAS_1V10
71 #endif
72 #define DIG_DBIAS_240M      RTC_CNTL_DBIAS_HP_VOLT
73 #define DIG_DBIAS_XTAL      RTC_CNTL_DBIAS_1V10
74 #define DIG_DBIAS_2M        RTC_CNTL_DBIAS_1V00
75 
76 /**
77  * @brief Possible main XTAL frequency values.
78  *
79  * Enum values should be equal to frequency in MHz.
80  */
81 typedef enum {
82     RTC_XTAL_FREQ_AUTO = 0,     //!< Automatic XTAL frequency detection
83     RTC_XTAL_FREQ_40M = 40,     //!< 40 MHz XTAL
84     RTC_XTAL_FREQ_26M = 26,     //!< 26 MHz XTAL
85     RTC_XTAL_FREQ_24M = 24,     //!< 24 MHz XTAL
86 } rtc_xtal_freq_t;
87 
88 /**
89  * @brief CPU clock configuration structure
90  */
91 typedef struct rtc_cpu_freq_config_s {
92     soc_cpu_clk_src_t source;       //!< The clock from which CPU clock is derived
93     uint32_t source_freq_mhz;       //!< Source clock frequency
94     uint32_t div;                   //!< Divider, freq_mhz = source_freq_mhz / div
95     uint32_t freq_mhz;              //!< CPU clock frequency
96 } rtc_cpu_freq_config_t;
97 
98 /**
99  * @brief Clock source to be calibrated using rtc_clk_cal function
100  */
101 typedef enum {
102     RTC_CAL_RTC_MUX = 0,       //!< Currently selected RTC SLOW_CLK
103     RTC_CAL_8MD256 = 1,        //!< Internal 8 MHz RC oscillator, divided by 256
104     RTC_CAL_32K_XTAL = 2       //!< External 32 kHz XTAL
105 } rtc_cal_sel_t;
106 
107 /**
108  * Initialization parameters for rtc_clk_init
109  */
110 typedef struct rtc_clk_config_s {
111     rtc_xtal_freq_t xtal_freq : 8;             //!< Main XTAL frequency
112     uint32_t cpu_freq_mhz : 10;                //!< CPU frequency to set, in MHz
113     soc_rtc_fast_clk_src_t fast_clk_src : 2;   //!< RTC_FAST_CLK clock source to choose
114     soc_rtc_slow_clk_src_t slow_clk_src : 2;   //!< RTC_SLOW_CLK clock source to choose
115     uint32_t clk_8m_div : 3;                   //!< RTC 8M clock divider (division is by clk_8m_div+1, i.e. 0 means 8MHz frequency)
116     uint32_t slow_clk_dcap : 8;                //!< RTC 150k clock adjustment parameter (higher value leads to lower frequency)
117     uint32_t clk_8m_dfreq : 8;                 //!< RTC 8m clock adjustment parameter (higher value leads to higher frequency)
118 } rtc_clk_config_t;
119 
120 /**
121  * Default initializer for rtc_clk_config_t
122  */
123 #define RTC_CLK_CONFIG_DEFAULT() { \
124     .xtal_freq = CONFIG_XTAL_FREQ, \
125     .cpu_freq_mhz = 80, \
126     .fast_clk_src = SOC_RTC_FAST_CLK_SRC_RC_FAST, \
127     .slow_clk_src = SOC_RTC_SLOW_CLK_SRC_RC_SLOW, \
128     .clk_8m_div = 0, \
129     .slow_clk_dcap = RTC_CNTL_SCK_DCAP_DEFAULT, \
130     .clk_8m_dfreq = RTC_CNTL_CK8M_DFREQ_DEFAULT, \
131 }
132 
133 /**
134  * Initialize clocks and set CPU frequency
135  *
136  * If cfg.xtal_freq is set to RTC_XTAL_FREQ_AUTO, this function will attempt
137  * to auto detect XTAL frequency. Auto detection is performed by comparing
138  * XTAL frequency with the frequency of internal 8MHz oscillator. Note that at
139  * high temperatures the frequency of the internal 8MHz oscillator may drift
140  * enough for auto detection to be unreliable.
141  * Auto detection code will attempt to distinguish between 26MHz and 40MHz
142  * crystals. 24 MHz crystals are not supported by auto detection code.
143  * If XTAL frequency can not be auto detected, this 26MHz frequency will be used.
144  *
145  * @param cfg clock configuration as rtc_clk_config_t
146  */
147 void rtc_clk_init(rtc_clk_config_t cfg);
148 
149 /**
150  * @brief Get main XTAL frequency
151  *
152  * This is the value stored in RTC register RTC_XTAL_FREQ_REG by the bootloader. As passed to
153  * rtc_clk_init function, or if the value was RTC_XTAL_FREQ_AUTO, the detected
154  * XTAL frequency.
155  *
156  * @return XTAL frequency, one of rtc_xtal_freq_t
157  */
158 rtc_xtal_freq_t rtc_clk_xtal_freq_get(void);
159 
160 /**
161  * @brief Update XTAL frequency
162  *
163  * Updates the XTAL value stored in RTC_XTAL_FREQ_REG. Usually this value is ignored
164  * after startup.
165  *
166  * @param xtal_freq New frequency value
167  */
168 void rtc_clk_xtal_freq_update(rtc_xtal_freq_t xtal_freq);
169 
170 /**
171  * @brief Enable or disable 32 kHz XTAL oscillator
172  * @param en  true to enable, false to disable
173  */
174 void rtc_clk_32k_enable(bool en);
175 
176 /**
177  * @brief Configure 32 kHz XTAL oscillator to accept external clock signal
178  */
179 void rtc_clk_32k_enable_external(void);
180 
181 /**
182  * @brief Get the state of 32k XTAL oscillator
183  * @return true if 32k XTAL oscillator has been enabled
184  */
185 bool rtc_clk_32k_enabled(void);
186 
187 /**
188  * @brief Enable 32k oscillator, configuring it for fast startup time.
189  * Note: to achieve higher frequency stability, rtc_clk_32k_enable function
190  * must be called one the 32k XTAL oscillator has started up. This function
191  * will initially disable the 32k XTAL oscillator, so it should not be called
192  * when the system is using 32k XTAL as RTC_SLOW_CLK.
193  *
194  * @param cycle Number of 32kHz cycles to bootstrap external crystal.
195  *              If 0, no square wave will be used to bootstrap crystal oscillation.
196  */
197 void rtc_clk_32k_bootstrap(uint32_t cycle);
198 
199 /**
200  * @brief Enable or disable 8 MHz internal oscillator
201  *
202  * Output from 8 MHz internal oscillator is passed into a configurable
203  * divider, which by default divides the input clock frequency by 256.
204  * Output of the divider may be used as RTC_SLOW_CLK source.
205  * Output of the divider is referred to in register descriptions and code as
206  * 8md256 or simply d256. Divider values other than 256 may be configured, but
207  * this facility is not currently needed, so is not exposed in the code.
208  *
209  * When 8MHz/256 divided output is not needed, the divider should be disabled
210  * to reduce power consumption.
211  *
212  * @param clk_8m_en true to enable 8MHz generator
213  * @param d256_en true to enable /256 divider
214  */
215 void rtc_clk_8m_enable(bool clk_8m_en, bool d256_en);
216 
217 /**
218  * @brief Get the state of 8 MHz internal oscillator
219  * @return true if the oscillator is enabled
220  */
221 bool rtc_clk_8m_enabled(void);
222 
223 /**
224  * @brief Get the state of /256 divider which is applied to 8MHz clock
225  * @return true if the divided output is enabled
226  */
227 bool rtc_clk_8md256_enabled(void);
228 
229 /**
230  * @brief Enable or disable APLL
231  *
232  * Output frequency is given by the formula:
233  * apll_freq = xtal_freq * (4 + sdm2 + sdm1/256 + sdm0/65536)/((o_div + 2) * 2)
234  *
235  * The dividend in this expression should be in the range of 240 - 600 MHz.
236  *
237  * In rev. 0 of ESP32, sdm0 and sdm1 are unused and always set to 0.
238  *
239  * @param enable  true to enable, false to disable
240  */
241 void rtc_clk_apll_enable(bool enable);
242 
243 /**
244  * @brief Calculate APLL clock coeffifcients
245  *
246  * @param freq  expected APLL frequency
247  * @param o_div  frequency divider, 0..31
248  * @param sdm0  frequency adjustment parameter, 0..255
249  * @param sdm1  frequency adjustment parameter, 0..255
250  * @param sdm2  frequency adjustment parameter, 0..63
251  *
252  * @return
253  *      - 0 Failed
254  *      - else Sucess
255  */
256 uint32_t rtc_clk_apll_coeff_calc(uint32_t freq, uint32_t *_o_div, uint32_t *_sdm0, uint32_t *_sdm1, uint32_t *_sdm2);
257 
258 /**
259  * @brief Set APLL clock coeffifcients
260  *
261  * @param o_div  frequency divider, 0..31
262  * @param sdm0  frequency adjustment parameter, 0..255
263  * @param sdm1  frequency adjustment parameter, 0..255
264  * @param sdm2  frequency adjustment parameter, 0..63
265  */
266 void rtc_clk_apll_coeff_set(uint32_t o_div, uint32_t sdm0, uint32_t sdm1, uint32_t sdm2);
267 
268 /**
269  * @brief Select source for RTC_SLOW_CLK
270  * @param clk_src clock source (one of soc_rtc_slow_clk_src_t values)
271  */
272 void rtc_clk_slow_src_set(soc_rtc_slow_clk_src_t clk_src);
273 
274 /**
275  * @brief Get the RTC_SLOW_CLK source
276  * @return currently selected clock source (one of soc_rtc_slow_clk_src_t values)
277  */
278 soc_rtc_slow_clk_src_t rtc_clk_slow_src_get(void);
279 
280 /**
281  * @brief Get the approximate frequency of RTC_SLOW_CLK, in Hz
282  *
283  * - if SOC_RTC_SLOW_CLK_SRC_RC_SLOW is selected, returns ~150000
284  * - if SOC_RTC_SLOW_CLK_SRC_XTAL32K is selected, returns 32768
285  * - if SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256 is selected, returns ~33000
286  *
287  * rtc_clk_cal function can be used to get more precise value by comparing
288  * RTC_SLOW_CLK frequency to the frequency of main XTAL.
289  *
290  * @return RTC_SLOW_CLK frequency, in Hz
291  */
292 uint32_t rtc_clk_slow_freq_get_hz(void);
293 
294 /**
295  * @brief Select source for RTC_FAST_CLK
296  * @param clk_src clock source (one of soc_rtc_fast_clk_src_t values)
297  */
298 void rtc_clk_fast_src_set(soc_rtc_fast_clk_src_t clk_src);
299 
300 /**
301  * @brief Get the RTC_FAST_CLK source
302  * @return currently selected clock source (one of soc_rtc_fast_clk_src_t values)
303  */
304 soc_rtc_fast_clk_src_t rtc_clk_fast_src_get(void);
305 
306  /**
307   * @brief Get CPU frequency config for a given frequency
308   * @param freq_mhz  Frequency in MHz
309   * @param[out] out_config Output, CPU frequency configuration structure
310   * @return true if frequency can be obtained, false otherwise
311   */
312  bool rtc_clk_cpu_freq_mhz_to_config(uint32_t freq_mhz, rtc_cpu_freq_config_t* out_config);
313 
314  /**
315   * @brief Switch CPU frequency
316   *
317   * This function sets CPU frequency according to the given configuration
318   * structure. It enables PLLs, if necessary.
319   *
320   * @note This function in not intended to be called by applications in FreeRTOS
321   * environment. This is because it does not adjust various timers based on the
322   * new CPU frequency.
323   *
324   * @param config  CPU frequency configuration structure
325   */
326  void rtc_clk_cpu_freq_set_config(const rtc_cpu_freq_config_t* config);
327 
328  /**
329   * @brief Switch CPU frequency (optimized for speed)
330   *
331   * This function is a faster equivalent of rtc_clk_cpu_freq_set_config.
332   * It works faster because it does not disable PLLs when switching from PLL to
333   * XTAL and does not enabled them when switching back. If PLL is not already
334   * enabled when this function is called to switch from XTAL to PLL frequency,
335   * or the PLL which is enabled is the wrong one, this function will fall back
336   * to calling rtc_clk_cpu_freq_set_config.
337   *
338   * Unlike rtc_clk_cpu_freq_set_config, this function relies on static data,
339   * so it is less safe to use it e.g. from a panic handler (when memory might
340   * be corrupted).
341   *
342   * @note This function in not intended to be called by applications in FreeRTOS
343   * environment. This is because it does not adjust various timers based on the
344   * new CPU frequency.
345   *
346   * @param config  CPU frequency configuration structure
347   */
348  void rtc_clk_cpu_freq_set_config_fast(const rtc_cpu_freq_config_t* config);
349 
350  /**
351   * @brief Get the currently used CPU frequency configuration
352   * @param[out] out_config  Output, CPU frequency configuration structure
353   */
354  void rtc_clk_cpu_freq_get_config(rtc_cpu_freq_config_t* out_config);
355 
356  /**
357   * @brief Switch CPU clock source to XTAL
358   *
359   * Short form for filling in rtc_cpu_freq_config_t structure and calling
360   * rtc_clk_cpu_freq_set_config when a switch to XTAL is needed.
361   * Assumes that XTAL frequency has been determined — don't call in startup code.
362   */
363  void rtc_clk_cpu_freq_set_xtal(void);
364 
365 
366 /**
367  * @brief Store new APB frequency value into RTC_APB_FREQ_REG
368  *
369  * This function doesn't change any hardware clocks.
370  *
371  * Functions which perform frequency switching and change APB frequency call
372  * this function to update the value of APB frequency stored in RTC_APB_FREQ_REG
373  * (one of RTC general purpose retention registers). This should not normally
374  * be called from application code.
375  *
376  * @param apb_freq  new APB frequency, in Hz
377  */
378 void rtc_clk_apb_freq_update(uint32_t apb_freq);
379 
380 /**
381  * @brief Get the current stored APB frequency.
382  * @return The APB frequency value as last set via rtc_clk_apb_freq_update(), in Hz.
383  */
384 uint32_t rtc_clk_apb_freq_get(void);
385 
386 #define RTC_CLK_CAL_FRACT  19  //!< Number of fractional bits in values returned by rtc_clk_cal
387 
388 /**
389  * @brief Measure RTC slow clock's period, based on main XTAL frequency
390  *
391  * This function will time out and return 0 if the time for the given number
392  * of cycles to be counted exceeds the expected time twice. This may happen if
393  * 32k XTAL is being calibrated, but the oscillator has not started up (due to
394  * incorrect loading capacitance, board design issue, or lack of 32 XTAL on board).
395  *
396  * @note When 32k CLK is being calibrated, this function will check the accuracy
397  * of the clock. Since the xtal 32k or ext osc 32k is generally very stable, if
398  * the check fails, then consider this an invalid 32k clock and return 0. This
399  * check can filter some jamming signal.
400  *
401  * @param cal_clk  clock to be measured
402  * @param slow_clk_cycles  number of slow clock cycles to average
403  * @return average slow clock period in microseconds, Q13.19 fixed point format,
404  *         or 0 if calibration has timed out
405  */
406 uint32_t rtc_clk_cal(rtc_cal_sel_t cal_clk, uint32_t slow_clk_cycles);
407 
408 /**
409  * @brief Measure ratio between XTAL frequency and RTC slow clock frequency
410  * @param cal_clk slow clock to be measured
411  * @param slow_clk_cycles number of slow clock cycles to average
412  * @return average ratio between XTAL frequency and slow clock frequency,
413  *         Q13.19 fixed point format, or 0 if calibration has timed out.
414  */
415 uint32_t rtc_clk_cal_ratio(rtc_cal_sel_t cal_clk, uint32_t slow_clk_cycles);
416 
417 /**
418  * @brief Convert time interval from microseconds to RTC_SLOW_CLK cycles
419  * @param time_in_us Time interval in microseconds
420  * @param slow_clk_period  Period of slow clock in microseconds, Q13.19
421  *                         fixed point format (as returned by rtc_slowck_cali).
422  * @return number of slow clock cycles
423  */
424 uint64_t rtc_time_us_to_slowclk(uint64_t time_in_us, uint32_t period);
425 
426 /**
427  * @brief Convert time interval from RTC_SLOW_CLK to microseconds
428  * @param time_in_us Time interval in RTC_SLOW_CLK cycles
429  * @param slow_clk_period  Period of slow clock in microseconds, Q13.19
430  *                         fixed point format (as returned by rtc_slowck_cali).
431  * @return time interval in microseconds
432  */
433 uint64_t rtc_time_slowclk_to_us(uint64_t rtc_cycles, uint32_t period);
434 
435 /**
436  * @brief Get current value of RTC counter
437  *
438  * RTC has a 48-bit counter which is incremented by 2 every 2 RTC_SLOW_CLK
439  * cycles. Counter value is not writable by software. The value is not adjusted
440  * when switching to a different RTC_SLOW_CLK source.
441  *
442  * Note: this function may take up to 1 RTC_SLOW_CLK cycle to execute
443  *
444  * @return current value of RTC counter
445  */
446 uint64_t rtc_time_get(void);
447 
448 /**
449  * @brief Busy loop until next RTC_SLOW_CLK cycle
450  *
451  * This function returns not earlier than the next RTC_SLOW_CLK clock cycle.
452  * In some cases (e.g. when RTC_SLOW_CLK cycle is very close), it may return
453  * one RTC_SLOW_CLK cycle later.
454  */
455 void rtc_clk_wait_for_slow_cycle(void);
456 
457 /**
458  * @brief Enable the rtc digital 8M clock
459  *
460  * This function is used to enable the digital rtc 8M clock to support peripherals.
461  * For enabling the analog 8M clock, using `rtc_clk_8M_enable` function above.
462  */
463 void rtc_dig_clk8m_enable(void);
464 
465 /**
466  * @brief Disable the rtc digital 8M clock
467  *
468  * This function is used to disable the digital rtc 8M clock, which is only used to support peripherals.
469  */
470 void rtc_dig_clk8m_disable(void);
471 
472 /**
473  * @brief Get whether the rtc digital 8M clock is enabled
474  */
475 bool rtc_dig_8m_enabled(void);
476 
477 /**
478  * @brief Calculate the real clock value after the clock calibration
479  *
480  * @param cal_val Average slow clock period in microseconds, fixed point value as returned from `rtc_clk_cal`
481  * @return Frequency of the clock in Hz
482  */
483 uint32_t rtc_clk_freq_cal(uint32_t cal_val);
484 
485 /**
486  * @brief sleep configuration for rtc_sleep_init function
487  */
488 typedef struct rtc_sleep_config_s {
489     uint32_t lslp_mem_inf_fpu : 1;      //!< force normal voltage in sleep mode (digital domain memory)
490     uint32_t rtc_mem_inf_fpu : 1;       //!< force normal voltage in sleep mode (RTC memory)
491     uint32_t rtc_mem_inf_follow_cpu : 1;//!< keep low voltage in sleep mode (even if ULP/touch is used)
492     uint32_t rtc_fastmem_pd_en : 1;     //!< power down RTC fast memory
493     uint32_t rtc_slowmem_pd_en : 1;     //!< power down RTC slow memory
494     uint32_t rtc_peri_pd_en : 1;        //!< power down RTC peripherals
495     uint32_t modem_pd_en : 1;           //!< power down Modem(wifi and btdm)
496     uint32_t int_8m_pd_en : 1;          //!< Power down Internal 8M oscillator
497     uint32_t rom_mem_pd_en : 1;         //!< power down main RAM and ROM
498     uint32_t deep_slp : 1;              //!< power down digital domain
499     uint32_t wdt_flashboot_mod_en : 1;  //!< enable WDT flashboot mode
500     uint32_t dig_dbias_wak : 3;         //!< set bias for digital domain, in active mode
501     uint32_t dig_dbias_slp : 3;         //!< set bias for digital domain, in sleep mode
502     uint32_t rtc_dbias_wak : 3;         //!< set bias for RTC domain, in active mode
503     uint32_t rtc_dbias_slp : 3;         //!< set bias for RTC domain, in sleep mode
504     uint32_t lslp_meminf_pd : 1;        //!< remove all peripheral force power up flags
505     uint32_t vddsdio_pd_en : 1;         //!< power down VDDSDIO regulator
506     uint32_t xtal_fpu : 1;              //!< keep main XTAL powered up in sleep
507     uint32_t deep_slp_reject : 1;       //!< enable deep sleep reject
508     uint32_t light_slp_reject : 1;      //!< enable light sleep reject
509     uint32_t dbg_atten_slp : 2;             //!< voltage parameter
510 } rtc_sleep_config_t;
511 
512 #define RTC_SLEEP_PD_DIG                BIT(0)  //!< Deep sleep (power down digital domain)
513 #define RTC_SLEEP_PD_RTC_PERIPH         BIT(1)  //!< Power down RTC peripherals
514 #define RTC_SLEEP_PD_RTC_SLOW_MEM       BIT(2)  //!< Power down RTC SLOW memory
515 #define RTC_SLEEP_PD_RTC_FAST_MEM       BIT(3)  //!< Power down RTC FAST memory
516 #define RTC_SLEEP_PD_RTC_MEM_FOLLOW_CPU BIT(4)  //!< RTC FAST and SLOW memories are automatically powered up and down along with the CPU
517 #define RTC_SLEEP_PD_VDDSDIO            BIT(5)  //!< Power down VDDSDIO regulator
518 #define RTC_SLEEP_PD_MODEM              BIT(6)  //!< Power down Modem(wifi and btdm)
519 #define RTC_SLEEP_PD_XTAL               BIT(7)  //!< Power down main XTAL
520 #define RTC_SLEEP_PD_INT_8M             BIT(8)  //!< Power down Internal 8M oscillator
521 
522 //These flags are not power domains, but will affect some sleep parameters
523 #define RTC_SLEEP_DIG_USE_8M            BIT(16)
524 #define RTC_SLEEP_USE_ADC_TESEN_MONITOR BIT(17)
525 #define RTC_SLEEP_NO_ULTRA_LOW          BIT(18) //!< Avoid using ultra low power in deep sleep, in which RTCIO cannot be used as input, and RTCMEM can't work under high temperature
526 
527 /**
528  * Default initializer for rtc_sleep_config_t
529  *
530  * This initializer sets all fields to "reasonable" values (e.g. suggested for
531  * production use) based on a combination of RTC_SLEEP_PD_x flags.
532  *
533  * @param RTC_SLEEP_PD_x flags combined using bitwise OR
534  */
535 void rtc_sleep_get_default_config(uint32_t sleep_flags, rtc_sleep_config_t *out_config);
536 
537 /* Various delays to be programmed into power control state machines */
538 #define RTC_CNTL_XTL_BUF_WAIT_SLP_US        (1000)
539 #define RTC_CNTL_PLL_BUF_WAIT_SLP_CYCLES    (1)
540 #define RTC_CNTL_CK8M_WAIT_SLP_CYCLES       (4)
541 #define RTC_CNTL_WAKEUP_DELAY_CYCLES        (7)
542 #define RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES    (1)
543 #define RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES       (1)
544 #define RTC_CNTL_MIN_SLP_VAL_MIN            (128)
545 
546 #define RTC_CNTL_CK8M_WAIT_DEFAULT          20
547 #define RTC_CK8M_ENABLE_WAIT_DEFAULT        5
548 
549 /**
550  * @brief Prepare the chip to enter sleep mode
551  *
552  * This function configures various power control state machines to handle
553  * entry into light sleep or deep sleep mode, switches APB and CPU clock source
554  * (usually to XTAL), and sets bias voltages for digital and RTC power domains.
555  *
556  * This function does not actually enter sleep mode; this is done using
557  * rtc_sleep_start function. Software may do some other actions between
558  * rtc_sleep_init and rtc_sleep_start, such as set wakeup timer and configure
559  * wakeup sources.
560  * @param cfg sleep mode configuration
561  */
562 void rtc_sleep_init(rtc_sleep_config_t cfg);
563 
564 /**
565  * @brief Low level initialize for rtc state machine waiting cycles after waking up
566  *
567  * This function configures the cycles chip need to wait for internal 8MHz
568  * oscillator and external 40MHz crystal. As we configure fixed time for waiting
569  * crystal, we need to pass period to calculate cycles. Now this function only
570  * used in lightsleep mode.
571  *
572  * @param slowclk_period re-calibrated slow clock period
573  */
574 void rtc_sleep_low_init(uint32_t slowclk_period);
575 
576 #define RTC_EXT0_TRIG_EN    BIT(0)  //!< EXT0 GPIO wakeup
577 #define RTC_EXT1_TRIG_EN    BIT(1)  //!< EXT1 GPIO wakeup
578 #define RTC_GPIO_TRIG_EN    BIT(2)  //!< GPIO wakeup (light sleep only)
579 #define RTC_TIMER_TRIG_EN   BIT(3)  //!< Timer wakeup
580 #define RTC_SDIO_TRIG_EN    BIT(4)  //!< SDIO wakeup (light sleep only)
581 #define RTC_MAC_TRIG_EN     BIT(5)  //!< MAC wakeup (light sleep only)
582 #define RTC_UART0_TRIG_EN   BIT(6)  //!< UART0 wakeup (light sleep only)
583 #define RTC_UART1_TRIG_EN   BIT(7)  //!< UART1 wakeup (light sleep only)
584 #define RTC_TOUCH_TRIG_EN   BIT(8)  //!< Touch wakeup
585 #define RTC_ULP_TRIG_EN     BIT(9)  //!< ULP wakeup
586 #define RTC_BT_TRIG_EN      BIT(10) //!< BT wakeup (light sleep only)
587 
588 /**
589  * RTC_SLEEP_REJECT_MASK records sleep reject sources supported by chip
590  * esp32 only supports GPIO and SDIO sleep reject sources
591  */
592 #define RTC_SLEEP_REJECT_MASK (RTC_GPIO_TRIG_EN | RTC_SDIO_TRIG_EN)
593 
594 /**
595  * @brief Enter deep or light sleep mode
596  *
597  * This function enters the sleep mode previously configured using rtc_sleep_init
598  * function. Before entering sleep, software should configure wake up sources
599  * appropriately (set up GPIO wakeup registers, timer wakeup registers,
600  * and so on).
601  *
602  * If deep sleep mode was configured using rtc_sleep_init, and sleep is not
603  * rejected by hardware (based on reject_opt flags), this function never returns.
604  * When the chip wakes up from deep sleep, CPU is reset and execution starts
605  * from ROM bootloader.
606  *
607  * If light sleep mode was configured using rtc_sleep_init, this function
608  * returns on wakeup, or if sleep is rejected by hardware.
609  *
610  * @param wakeup_opt  bit mask wake up reasons to enable (RTC_xxx_TRIG_EN flags
611  *                    combined with OR)
612  * @param reject_opt  bit mask of sleep reject reasons:
613  *                      - RTC_CNTL_GPIO_REJECT_EN
614  *                      - RTC_CNTL_SDIO_REJECT_EN
615  *                    These flags are used to prevent entering sleep when e.g.
616  *                    an external host is communicating via SDIO slave
617  * @return non-zero if sleep was rejected by hardware
618  */
619 uint32_t rtc_sleep_start(uint32_t wakeup_opt, uint32_t reject_opt);
620 
621 /**
622  * @brief Enter deep sleep mode
623  *
624  * Similar to rtc_sleep_start(), but additionally uses hardware to calculate the CRC value
625  * of RTC FAST memory. On wake, this CRC is used to determine if a deep sleep wake
626  * stub is valid to execute (if a wake address is set).
627  *
628  * No RAM is accessed while calculating the CRC and going into deep sleep, which makes
629  * this function safe to use even if the caller's stack is in RTC FAST memory.
630  *
631  * @note If no deep sleep wake stub address is set then calling rtc_sleep_start() will
632  * have the same effect and takes less time as CRC calculation is skipped.
633  *
634  * @note This function should only be called after rtc_sleep_init() has been called to
635  * configure the system for deep sleep.
636  *
637  * @param wakeup_opt - same as for rtc_sleep_start
638  * @param reject_opt - same as for rtc_sleep_start
639  *
640  * @return non-zero if sleep was rejected by hardware
641  */
642 uint32_t rtc_deep_sleep_start(uint32_t wakeup_opt, uint32_t reject_opt);
643 
644 /**
645  * RTC power and clock control initialization settings
646  */
647 typedef struct rtc_config_s {
648     uint32_t ck8m_wait : 8;         //!< Number of rtc_fast_clk cycles to wait for 8M clock to be ready
649     uint32_t xtal_wait : 8;         //!< Number of rtc_fast_clk cycles to wait for XTAL clock to be ready
650     uint32_t pll_wait : 8;          //!< Number of rtc_fast_clk cycles to wait for PLL to be ready
651     uint32_t clkctl_init : 1;       //!< Perform clock control related initialization
652     uint32_t pwrctl_init : 1;       //!< Perform power control related initialization
653     uint32_t rtc_dboost_fpd : 1;    //!< Force power down RTC_DBOOST
654 } rtc_config_t;
655 
656 /**
657  * Default initializer of rtc_config_t.
658  *
659  * This initializer sets all fields to "reasonable" values (e.g. suggested for
660  * production use).
661  */
662 #define RTC_CONFIG_DEFAULT() {\
663     .ck8m_wait = RTC_CNTL_CK8M_WAIT_DEFAULT, \
664     .xtal_wait = RTC_CNTL_XTL_BUF_WAIT_DEFAULT, \
665     .pll_wait  = RTC_CNTL_PLL_BUF_WAIT_DEFAULT, \
666     .clkctl_init = 1, \
667     .pwrctl_init = 1, \
668     .rtc_dboost_fpd = 1 \
669 }
670 
671 /**
672  * Initialize RTC clock and power control related functions
673  * @param cfg configuration options as rtc_config_t
674  */
675 void rtc_init(rtc_config_t cfg);
676 
677 #define RTC_VDDSDIO_TIEH_1_8V 0 //!< TIEH field value for 1.8V VDDSDIO
678 #define RTC_VDDSDIO_TIEH_3_3V 1 //!< TIEH field value for 3.3V VDDSDIO
679 
680 /**
681  * Structure describing vddsdio configuration
682  */
683 typedef struct rtc_vddsdio_config_s {
684     uint32_t force : 1;     //!< If 1, use configuration from RTC registers; if 0, use EFUSE/bootstrapping pins.
685     uint32_t enable : 1;    //!< Enable VDDSDIO regulator
686     uint32_t tieh  : 1;     //!< Select VDDSDIO voltage. One of RTC_VDDSDIO_TIEH_1_8V, RTC_VDDSDIO_TIEH_3_3V
687     uint32_t drefh : 2;     //!< Tuning parameter for VDDSDIO regulator
688     uint32_t drefm : 2;     //!< Tuning parameter for VDDSDIO regulator
689     uint32_t drefl : 2;     //!< Tuning parameter for VDDSDIO regulator
690 } rtc_vddsdio_config_t;
691 
692 /**
693  * Get current VDDSDIO configuration
694  * If VDDSDIO configuration is overridden by RTC, get values from RTC
695  * Otherwise, if VDDSDIO is configured by EFUSE, get values from EFUSE
696  * Otherwise, use default values and the level of MTDI bootstrapping pin.
697  * @return currently used VDDSDIO configuration
698  */
699 rtc_vddsdio_config_t rtc_vddsdio_get_config(void);
700 
701 /**
702  * Set new VDDSDIO configuration using RTC registers.
703  * If config.force == 1, this overrides configuration done using bootstrapping
704  * pins and EFUSE.
705  *
706  * @param config new VDDSDIO configuration
707  */
708 void rtc_vddsdio_set_config(rtc_vddsdio_config_t config);
709 
710 
711 // -------------------------- CLOCK TREE DEFS ALIAS ----------------------------
712 // **WARNING**: The following are only for backwards compatibility.
713 // Please use the declarations in soc/clk_tree_defs.h instead.
714 /**
715  * @brief CPU clock source
716  */
717 typedef soc_cpu_clk_src_t rtc_cpu_freq_src_t;
718 #define RTC_CPU_FREQ_SRC_XTAL SOC_CPU_CLK_SRC_XTAL  //!< XTAL
719 #define RTC_CPU_FREQ_SRC_PLL SOC_CPU_CLK_SRC_PLL    //!< PLL (480M or 320M)
720 #define RTC_CPU_FREQ_SRC_8M SOC_CPU_CLK_SRC_RC_FAST //!< Internal 8M RTC oscillator
721 #define RTC_CPU_FREQ_SRC_APLL SOC_CPU_CLK_SRC_APLL  //!< APLL
722 
723 /**
724  * @brief RTC SLOW_CLK frequency values
725  */
726 typedef soc_rtc_slow_clk_src_t rtc_slow_freq_t;
727 #define RTC_SLOW_FREQ_RTC SOC_RTC_SLOW_CLK_SRC_RC_SLOW         //!< Internal 150 kHz RC oscillator
728 #define RTC_SLOW_FREQ_32K_XTAL SOC_RTC_SLOW_CLK_SRC_XTAL32K    //!< External 32 kHz XTAL
729 #define RTC_SLOW_FREQ_8MD256 SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256 //!< Internal 8 MHz RC oscillator, divided by 256
730 
731 /**
732  * @brief RTC FAST_CLK frequency values
733  */
734 typedef soc_rtc_fast_clk_src_t rtc_fast_freq_t;
735 #define RTC_FAST_FREQ_XTALD4 SOC_RTC_FAST_CLK_SRC_XTAL_DIV  //!< Main XTAL, divided by 4
736 #define RTC_FAST_FREQ_8M SOC_RTC_FAST_CLK_SRC_RC_FAST       //!< Internal 8 MHz RC oscillator
737 
738 /* Alias of frequency related macros */
739 #define RTC_FAST_CLK_FREQ_APPROX    SOC_CLK_RC_FAST_FREQ_APPROX
740 #define RTC_FAST_CLK_FREQ_8M        SOC_CLK_RC_FAST_FREQ_APPROX
741 #define RTC_SLOW_CLK_FREQ_150K      SOC_CLK_RC_SLOW_FREQ_APPROX
742 #define RTC_SLOW_CLK_FREQ_8MD256    SOC_CLK_RC_FAST_D256_FREQ_APPROX
743 #define RTC_SLOW_CLK_FREQ_32K       SOC_CLK_XTAL32K_FREQ_APPROX
744 
745 /* Alias of deprecated function names */
746 #define rtc_clk_slow_freq_set(slow_freq) rtc_clk_slow_src_set(slow_freq)
747 #define rtc_clk_slow_freq_get() rtc_clk_slow_src_get()
748 #define rtc_clk_fast_freq_set(fast_freq) rtc_clk_fast_src_set(fast_freq)
749 #define rtc_clk_fast_freq_get() rtc_clk_fast_src_get()
750 
751 #ifdef __cplusplus
752 }
753 #endif
754