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