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