1 /*
2  * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdint.h>
8 #include <sys/cdefs.h>
9 #include <sys/param.h>
10 #include "sdkconfig.h"
11 #include "esp_attr.h"
12 #include "esp_log.h"
13 #include "esp_cpu.h"
14 #include "esp_private/esp_clk.h"
15 #include "esp_clk_internal.h"
16 #include "esp32c2/rom/ets_sys.h"
17 #include "esp32c2/rom/uart.h"
18 #include "esp32c2/rom/rtc.h"
19 #include "soc/system_reg.h"
20 #include "soc/soc.h"
21 #include "soc/rtc.h"
22 #include "soc/rtc_periph.h"
23 #include "hal/wdt_hal.h"
24 #include "esp_private/periph_ctrl.h"
25 #include "bootloader_clock.h"
26 #include "soc/syscon_reg.h"
27 #include "esp_rom_uart.h"
28 
29 /* Number of cycles to wait from the 32k XTAL oscillator to consider it running.
30  * Larger values increase startup delay. Smaller values may cause false positive
31  * detection (i.e. oscillator runs for a few cycles and then stops).
32  */
33 #define SLOW_CLK_CAL_CYCLES     CONFIG_RTC_CLK_CAL_CYCLES
34 
35 /* Indicates that this 32k oscillator gets input from external oscillator, rather
36  * than a crystal.
37  */
38 #define EXT_OSC_FLAG    BIT(3)
39 
40 /* This is almost the same as soc_rtc_slow_clk_src_t, except that we define
41  * an extra enum member for the external 32k oscillator.
42  * For convenience, lower 2 bits should correspond to soc_rtc_slow_clk_src_t values.
43  */
44 typedef enum {
45     SLOW_CLK_RTC = SOC_RTC_SLOW_CLK_SRC_RC_SLOW,                       //!< Internal 150 kHz RC oscillator
46     SLOW_CLK_8MD256 = SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256,               //!< Internal 8 MHz RC oscillator, divided by 256
47     SLOW_CLK_32K_EXT_OSC = SOC_RTC_SLOW_CLK_SRC_OSC_SLOW | EXT_OSC_FLAG //!< External 32k oscillator connected to pin0
48 } slow_clk_sel_t;
49 
50 static void select_rtc_slow_clk(slow_clk_sel_t slow_clk);
51 static __attribute__((unused)) void recalib_bbpll(void);
52 
53 static const char *TAG = "clk";
54 
55 
esp_rtc_init(void)56 void esp_rtc_init(void)
57 {
58 #if CONFIG_ESP_SYSTEM_BBPLL_RECALIB
59     // In earlier version of ESP-IDF, the PLL provided by bootloader is not stable enough.
60     // Do calibration again here so that we can use better clock for the timing tuning.
61     recalib_bbpll();
62 #endif
63 
64 #if !CONFIG_IDF_ENV_FPGA
65     rtc_config_t cfg = RTC_CONFIG_DEFAULT();
66     soc_reset_reason_t rst_reas;
67     rst_reas = esp_rom_get_reset_reason(0);
68     if (rst_reas == RESET_REASON_CHIP_POWER_ON) {
69         cfg.cali_ocode = 1;
70     }
71     rtc_init(cfg);
72 #endif
73 }
74 
esp_clk_init(void)75 __attribute__((weak)) void esp_clk_init(void)
76 {
77 #if !CONFIG_IDF_ENV_FPGA
78 #ifndef CONFIG_XTAL_FREQ_AUTO
79     assert(rtc_clk_xtal_freq_get() == CONFIG_XTAL_FREQ);
80 #endif
81 
82     bool rc_fast_d256_is_enabled = rtc_clk_8md256_enabled();
83     rtc_clk_8m_enable(true, rc_fast_d256_is_enabled);
84     rtc_clk_fast_src_set(SOC_RTC_FAST_CLK_SRC_RC_FAST);
85 #endif
86 
87 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
88     // WDT uses a SLOW_CLK clock source. After a function select_rtc_slow_clk a frequency of this source can changed.
89     // If the frequency changes from 150kHz to 32kHz, then the timeout set for the WDT will increase 4.6 times.
90     // Therefore, for the time of frequency change, set a new lower timeout value (1.6 sec on 40MHz XTAL and 2.5 sec on 26MHz XTAL).
91     // This prevents excessive delay before resetting in case the supply voltage is drawdown.
92     // (If frequency is changed from 150kHz to 32kHz then WDT timeout will increased to 1.6sec * 150/32 = 7.5 sec 40MHz XTAL,
93     //  or 11.72 sec on 26MHz XTAL).
94     wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
95 #ifdef CONFIG_XTAL_FREQ_26
96     uint32_t stage_timeout_ticks = (uint32_t)(2500ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
97 #else
98     uint32_t stage_timeout_ticks = (uint32_t)(1600ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
99 #endif
100     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
101     wdt_hal_feed(&rtc_wdt_ctx);
102     //Bootloader has enabled RTC WDT until now. We're only modifying timeout, so keep the stage and timeout action the same
103     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
104     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
105 #endif
106 
107 #if defined(CONFIG_RTC_CLK_SRC_EXT_OSC)
108     select_rtc_slow_clk(SLOW_CLK_32K_EXT_OSC);
109 #elif defined(CONFIG_RTC_CLK_SRC_INT_8MD256)
110     select_rtc_slow_clk(SLOW_CLK_8MD256);
111 #else
112     select_rtc_slow_clk(SLOW_CLK_RTC);
113 #endif
114 
115 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
116     // After changing a frequency WDT timeout needs to be set for new frequency.
117     stage_timeout_ticks = (uint32_t)((uint64_t)CONFIG_BOOTLOADER_WDT_TIME_MS * rtc_clk_slow_freq_get_hz() / 1000);
118     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
119     wdt_hal_feed(&rtc_wdt_ctx);
120     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
121     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
122 #endif
123 
124     rtc_cpu_freq_config_t old_config, new_config;
125     rtc_clk_cpu_freq_get_config(&old_config);
126     const uint32_t old_freq_mhz = old_config.freq_mhz;
127     const uint32_t new_freq_mhz = CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ;
128 
129     bool res = rtc_clk_cpu_freq_mhz_to_config(new_freq_mhz, &new_config);
130     assert(res);
131 
132     // Wait for UART TX to finish, otherwise some UART output will be lost
133     // when switching APB frequency
134     esp_rom_uart_tx_wait_idle(CONFIG_ESP_CONSOLE_UART_NUM);
135 
136     if (res)  {
137         rtc_clk_cpu_freq_set_config(&new_config);
138     }
139 
140     // Re calculate the ccount to make time calculation correct.
141     esp_cpu_set_cycle_count( (uint64_t)esp_cpu_get_cycle_count() * new_freq_mhz / old_freq_mhz );
142 }
143 
select_rtc_slow_clk(slow_clk_sel_t slow_clk)144 static void select_rtc_slow_clk(slow_clk_sel_t slow_clk)
145 {
146     soc_rtc_slow_clk_src_t rtc_slow_clk_src = slow_clk & RTC_CNTL_ANA_CLK_RTC_SEL_V;
147     uint32_t cal_val = 0;
148     /* number of times to repeat external clock calibration
149      * before giving up and switching to the internal RC
150      */
151     int retry_ext_clk = 3;
152 
153     do {
154         if (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_OSC_SLOW) {
155             /* external clock needs to be connected to PIN0 before it can
156              * be used. Here we use rtc_clk_cal function to count
157              * the number of ext clk cycles in the given number of ext clk
158              * cycles. If the ext clk has not started up, calibration
159              * will time out, returning 0.
160              */
161             ESP_EARLY_LOGD(TAG, "waiting for external clock by pin0 to start up");
162             rtc_clk_32k_enable_external();
163 
164             // When SLOW_CLK_CAL_CYCLES is set to 0, clock calibration will not be performed at startup.
165             if (SLOW_CLK_CAL_CYCLES > 0) {
166                 cal_val = rtc_clk_cal(RTC_CAL_32K_OSC_SLOW, SLOW_CLK_CAL_CYCLES);
167                 if (cal_val == 0) {
168                     if (retry_ext_clk-- > 0) {
169                         continue;
170                     }
171                     ESP_EARLY_LOGW(TAG, "external clock connected to pin0 not found, switching to internal 150 kHz oscillator");
172                     rtc_slow_clk_src = SOC_RTC_SLOW_CLK_SRC_RC_SLOW;
173                 }
174             }
175         } else if (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256) {
176             rtc_clk_8m_enable(true, true);
177         }
178         rtc_clk_slow_src_set(rtc_slow_clk_src);
179 
180         if (SLOW_CLK_CAL_CYCLES > 0) {
181             /* TODO: 32k XTAL oscillator has some frequency drift at startup.
182              * Improve calibration routine to wait until the frequency is stable.
183              */
184             cal_val = rtc_clk_cal(RTC_CAL_RTC_MUX, SLOW_CLK_CAL_CYCLES);
185         } else {
186             const uint64_t cal_dividend = (1ULL << RTC_CLK_CAL_FRACT) * 1000000ULL;
187             cal_val = (uint32_t) (cal_dividend / rtc_clk_slow_freq_get_hz());
188         }
189     } while (cal_val == 0);
190     ESP_EARLY_LOGD(TAG, "RTC_SLOW_CLK calibration value: %d", cal_val);
191     esp_clk_slowclk_cal_set(cal_val);
192 }
193 
194 /* This function is not exposed as an API at this point.
195  * All peripheral clocks are default enabled after chip is powered on.
196  * This function disables some peripheral clocks when cpu starts.
197  * These peripheral clocks are enabled when the peripherals are initialized
198  * and disabled when they are de-initialized.
199  */
esp_perip_clk_init(void)200 __attribute__((weak)) void esp_perip_clk_init(void)
201 {
202     uint32_t common_perip_clk, hwcrypto_perip_clk, wifi_bt_sdio_clk = 0;
203     uint32_t common_perip_clk1 = 0;
204 
205     soc_reset_reason_t rst_reason = esp_rom_get_reset_reason(0);
206 
207     /* For reason that only reset CPU, do not disable the clocks
208      * that have been enabled before reset.
209      */
210     if (rst_reason == RESET_REASON_CPU0_MWDT0 || rst_reason == RESET_REASON_CPU0_SW ||
211             rst_reason == RESET_REASON_CPU0_RTC_WDT || rst_reason == RESET_REASON_CPU0_JTAG) {
212         common_perip_clk = ~READ_PERI_REG(SYSTEM_PERIP_CLK_EN0_REG);
213         hwcrypto_perip_clk = ~READ_PERI_REG(SYSTEM_PERIP_CLK_EN1_REG);
214         wifi_bt_sdio_clk = ~READ_PERI_REG(SYSTEM_WIFI_CLK_EN_REG);
215     } else {
216         common_perip_clk = SYSTEM_SPI2_CLK_EN |
217 #if CONFIG_ESP_CONSOLE_UART_NUM != 0
218                            SYSTEM_UART_CLK_EN |
219 #endif
220 #if CONFIG_ESP_CONSOLE_UART_NUM != 1
221                            SYSTEM_UART1_CLK_EN |
222 #endif
223                            SYSTEM_LEDC_CLK_EN |
224                            SYSTEM_I2C_EXT0_CLK_EN |
225                            SYSTEM_LEDC_CLK_EN;
226 
227         common_perip_clk1 = 0;
228         hwcrypto_perip_clk = SYSTEM_CRYPTO_SHA_CLK_EN;
229         wifi_bt_sdio_clk = SYSTEM_WIFI_CLK_WIFI_EN |
230                            SYSTEM_WIFI_CLK_BT_EN_M |
231                            SYSTEM_WIFI_CLK_UNUSED_BIT5 |
232                            SYSTEM_WIFI_CLK_UNUSED_BIT12;
233     }
234 
235     //Reset the communication peripherals like I2C, SPI, UART and bring them to known state.
236     common_perip_clk |= SYSTEM_SPI2_CLK_EN |
237 #if CONFIG_ESP_CONSOLE_UART_NUM != 0
238                         SYSTEM_UART_CLK_EN |
239 #endif
240 #if CONFIG_ESP_CONSOLE_UART_NUM != 1
241                         SYSTEM_UART1_CLK_EN |
242 #endif
243                         SYSTEM_I2C_EXT0_CLK_EN;
244     common_perip_clk1 = 0;
245 
246     /* Disable some peripheral clocks. */
247     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN0_REG, common_perip_clk);
248     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN0_REG, common_perip_clk);
249 
250     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN1_REG, common_perip_clk1);
251     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, common_perip_clk1);
252 
253     /* Disable hardware crypto clocks. */
254     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN1_REG, hwcrypto_perip_clk);
255     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, hwcrypto_perip_clk);
256 
257     /* Disable WiFi/BT/SDIO clocks. */
258     CLEAR_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, wifi_bt_sdio_clk);
259     SET_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_EN);
260 
261     /* Set WiFi light sleep clock source to RTC slow clock */
262     REG_SET_FIELD(SYSTEM_BT_LPCK_DIV_INT_REG, SYSTEM_BT_LPCK_DIV_NUM, 0);
263     CLEAR_PERI_REG_MASK(SYSTEM_BT_LPCK_DIV_FRAC_REG, SYSTEM_LPCLK_SEL_XTAL32K | SYSTEM_LPCLK_SEL_XTAL | SYSTEM_LPCLK_SEL_8M | SYSTEM_LPCLK_SEL_RTC_SLOW);
264     SET_PERI_REG_MASK(SYSTEM_BT_LPCK_DIV_FRAC_REG, SYSTEM_LPCLK_SEL_RTC_SLOW);
265 
266     /* Enable RNG clock. */
267     periph_module_enable(PERIPH_RNG_MODULE);
268 
269     /* Enable TimerGroup 0 clock to ensure its reference counter will never
270      * be decremented to 0 during normal operation and preventing it from
271      * being disabled.
272      * If the TimerGroup 0 clock is disabled and then reenabled, the watchdog
273      * registers (Flashboot protection included) will be reenabled, and some
274      * seconds later, will trigger an unintended reset.
275      */
276     periph_module_enable(PERIPH_TIMG0_MODULE);
277 }
278 
279 // Workaround for bootloader not calibrated well issue.
280 // Placed in IRAM because disabling BBPLL may influence the cache
recalib_bbpll(void)281 static void IRAM_ATTR NOINLINE_ATTR recalib_bbpll(void)
282 {
283     rtc_cpu_freq_config_t old_config;
284     rtc_clk_cpu_freq_get_config(&old_config);
285 
286     // There are two paths we arrive here: 1. CPU reset. 2. Other reset reasons.
287     // - For other reasons, the bootloader will set CPU source to BBPLL and enable it. But there are calibration issues.
288     //   Turn off the BBPLL and do calibration again to fix the issue.
289     // - For CPU reset, the CPU source will be set to XTAL, while the BBPLL is kept to meet USB Serial JTAG's
290     //   requirements. In this case, we don't touch BBPLL to avoid USJ disconnection.
291     if (old_config.source == SOC_CPU_CLK_SRC_PLL) {
292         rtc_clk_cpu_freq_set_xtal();
293         rtc_clk_cpu_freq_set_config(&old_config);
294     }
295 }
296