1 /*
2  * SPDX-FileCopyrightText: 2015-2021 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 #if !defined(__ZEPHYR__)
10 #include <sys/time.h>
11 #include "sdkconfig.h"
12 #endif
13 #include <sys/param.h>
14 #include "esp_attr.h"
15 #include "esp_log.h"
16 #include "esp32s3/clk.h"
17 #include "esp_clk_internal.h"
18 #include "esp_rom_uart.h"
19 #include "esp_rom_sys.h"
20 #include "soc/system_reg.h"
21 #include "soc/dport_access.h"
22 #include "soc/soc.h"
23 #include "soc/rtc.h"
24 #include "soc/rtc_periph.h"
25 #include "soc/i2s_reg.h"
26 #include "hal/cpu_hal.h"
27 #include "hal/wdt_hal.h"
28 #include "driver/periph_ctrl.h"
29 #include "bootloader_clock.h"
30 #include "soc/syscon_reg.h"
31 
32 #if defined(__ZEPHYR__)
33 #include "stubs.h"
34 #endif /* defined(__ZEPHYR__) */
35 
36 static const char *TAG = "clk";
37 
38 /* Number of cycles to wait from the 32k XTAL oscillator to consider it running.
39  * Larger values increase startup delay. Smaller values may cause false positive
40  * detection (i.e. oscillator runs for a few cycles and then stops).
41  */
42 #define SLOW_CLK_CAL_CYCLES     CONFIG_ESP32S3_RTC_CLK_CAL_CYCLES
43 
44 #ifdef CONFIG_ESP32S3_RTC_XTAL_CAL_RETRY
45 #define RTC_XTAL_CAL_RETRY CONFIG_ESP32S3_RTC_XTAL_CAL_RETRY
46 #else
47 #define RTC_XTAL_CAL_RETRY 1
48 #endif
49 
50 /* Lower threshold for a reasonably-looking calibration value for a 32k XTAL.
51  * The ideal value (assuming 32768 Hz frequency) is 1000000/32768*(2**19) = 16*10^6.
52  */
53 #define MIN_32K_XTAL_CAL_VAL  15000000L
54 
55 /* Indicates that this 32k oscillator gets input from external oscillator, rather
56  * than a crystal.
57  */
58 #define EXT_OSC_FLAG    BIT(3)
59 
60 /* This is almost the same as rtc_slow_freq_t, except that we define
61  * an extra enum member for the external 32k oscillator.
62  * For convenience, lower 2 bits should correspond to rtc_slow_freq_t values.
63  */
64 typedef enum {
65     SLOW_CLK_RTC = RTC_SLOW_FREQ_RTC,           //!< Internal 150 kHz RC oscillator
66     SLOW_CLK_32K_XTAL = RTC_SLOW_FREQ_32K_XTAL, //!< External 32 kHz XTAL
67     SLOW_CLK_8MD256 = RTC_SLOW_FREQ_8MD256,     //!< Internal 8 MHz RC oscillator, divided by 256
68     SLOW_CLK_32K_EXT_OSC = RTC_SLOW_FREQ_32K_XTAL | EXT_OSC_FLAG //!< External 32k oscillator connected to 32K_XP pin
69 } slow_clk_sel_t;
70 
71 static void select_rtc_slow_clk(slow_clk_sel_t slow_clk);
72 
esp_clk_init(void)73  __attribute__((weak)) void esp_clk_init(void)
74 {
75     rtc_config_t cfg = RTC_CONFIG_DEFAULT();
76     soc_reset_reason_t rst_reas;
77     rst_reas = esp_rom_get_reset_reason(0);
78     //When power on, we need to set `cali_ocode` to 1, to do a OCode calibration, which will calibrate the rtc reference voltage to a tested value
79     if (rst_reas == RESET_REASON_CHIP_POWER_ON) {
80         cfg.cali_ocode = 1;
81     }
82 
83     rtc_init(cfg);
84 
85     assert(rtc_clk_xtal_freq_get() == RTC_XTAL_FREQ_40M);
86 
87     rtc_clk_fast_freq_set(RTC_FAST_FREQ_8M);
88 
89 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
90     // WDT uses a SLOW_CLK clock source. After a function select_rtc_slow_clk a frequency of this source can changed.
91     // If the frequency changes from 150kHz to 32kHz, then the timeout set for the WDT will increase 4.6 times.
92     // Therefore, for the time of frequency change, set a new lower timeout value (1.6 sec).
93     // This prevents excessive delay before resetting in case the supply voltage is drawdown.
94     // (If frequency is changed from 150kHz to 32kHz then WDT timeout will increased to 1.6sec * 150/32 = 7.5 sec).
95     wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
96     uint32_t stage_timeout_ticks = (uint32_t)(1600ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
97     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
98     wdt_hal_feed(&rtc_wdt_ctx);
99     //Bootloader has enabled RTC WDT until now. We're only modifying timeout, so keep the stage and timeout action the same
100     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
101     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
102 #endif
103 
104 #if defined(CONFIG_ESP32S3_RTC_CLK_SRC_EXT_CRYS)
105     select_rtc_slow_clk(SLOW_CLK_32K_XTAL);
106 #elif defined(CONFIG_ESP32S3_RTC_CLK_SRC_EXT_OSC)
107     select_rtc_slow_clk(SLOW_CLK_32K_EXT_OSC);
108 #elif defined(CONFIG_ESP32S3_RTC_CLK_SRC_INT_8MD256)
109     select_rtc_slow_clk(SLOW_CLK_8MD256);
110 #else
111     select_rtc_slow_clk(RTC_SLOW_FREQ_RTC);
112 #endif
113 
114 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
115     // After changing a frequency WDT timeout needs to be set for new frequency.
116     stage_timeout_ticks = (uint32_t)((uint64_t)CONFIG_BOOTLOADER_WDT_TIME_MS * rtc_clk_slow_freq_get_hz() / 1000ULL);
117     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
118     wdt_hal_feed(&rtc_wdt_ctx);
119     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
120     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
121 #endif
122 
123     rtc_cpu_freq_config_t old_config, new_config;
124     rtc_clk_cpu_freq_get_config(&old_config);
125     const uint32_t old_freq_mhz = old_config.freq_mhz;
126     const uint32_t new_freq_mhz = CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ;
127 
128     bool res = rtc_clk_cpu_freq_mhz_to_config(new_freq_mhz, &new_config);
129     assert(res);
130 
131     // Wait for UART TX to finish, otherwise some UART output will be lost
132     // when switching APB frequency
133     if (CONFIG_ESP_CONSOLE_UART_NUM >= 0) {
134         esp_rom_uart_tx_wait_idle(CONFIG_ESP_CONSOLE_UART_NUM);
135     }
136 
137     if (res) {
138         rtc_clk_cpu_freq_set_config(&new_config);
139     }
140 
141     // Re calculate the ccount to make time calculation correct.
142     cpu_hal_set_cycle_count( (uint64_t)cpu_hal_get_cycle_count() * new_freq_mhz / old_freq_mhz );
143 }
144 
select_rtc_slow_clk(slow_clk_sel_t slow_clk)145 static void select_rtc_slow_clk(slow_clk_sel_t slow_clk)
146 {
147     rtc_slow_freq_t rtc_slow_freq = slow_clk & RTC_CNTL_ANA_CLK_RTC_SEL_V;
148     uint32_t cal_val = 0;
149     /* number of times to repeat 32k XTAL calibration
150      * before giving up and switching to the internal RC
151      */
152     int retry_32k_xtal = RTC_XTAL_CAL_RETRY;
153 
154     do {
155         if (rtc_slow_freq == RTC_SLOW_FREQ_32K_XTAL) {
156             /* 32k XTAL oscillator needs to be enabled and running before it can
157              * be used. Hardware doesn't have a direct way of checking if the
158              * oscillator is running. Here we use rtc_clk_cal function to count
159              * the number of main XTAL cycles in the given number of 32k XTAL
160              * oscillator cycles. If the 32k XTAL has not started up, calibration
161              * will time out, returning 0.
162              */
163             ESP_EARLY_LOGD(TAG, "waiting for 32k oscillator to start up");
164             if (slow_clk == SLOW_CLK_32K_XTAL) {
165                 rtc_clk_32k_enable(true);
166             } else if (slow_clk == SLOW_CLK_32K_EXT_OSC) {
167                 rtc_clk_32k_enable_external();
168             }
169             // When SLOW_CLK_CAL_CYCLES is set to 0, clock calibration will not be performed at startup.
170             if (SLOW_CLK_CAL_CYCLES > 0) {
171                 cal_val = rtc_clk_cal(RTC_CAL_32K_XTAL, SLOW_CLK_CAL_CYCLES);
172                 if (cal_val == 0 || cal_val < MIN_32K_XTAL_CAL_VAL) {
173                     if (retry_32k_xtal-- > 0) {
174                         continue;
175                     }
176                     ESP_EARLY_LOGW(TAG, "32 kHz XTAL not found, switching to internal 150 kHz oscillator");
177                     rtc_slow_freq = RTC_SLOW_FREQ_RTC;
178                 }
179             }
180         } else if (rtc_slow_freq == RTC_SLOW_FREQ_8MD256) {
181             rtc_clk_8m_enable(true, true);
182         }
183         rtc_clk_slow_freq_set(rtc_slow_freq);
184 
185         if (SLOW_CLK_CAL_CYCLES > 0) {
186             /* TODO: 32k XTAL oscillator has some frequency drift at startup.
187              * Improve calibration routine to wait until the frequency is stable.
188              */
189             cal_val = rtc_clk_cal(RTC_CAL_RTC_MUX, SLOW_CLK_CAL_CYCLES);
190         } else {
191             const uint64_t cal_dividend = (1ULL << RTC_CLK_CAL_FRACT) * 1000000ULL;
192             cal_val = (uint32_t) (cal_dividend / rtc_clk_slow_freq_get_hz());
193         }
194     } while (cal_val == 0);
195     ESP_EARLY_LOGD(TAG, "RTC_SLOW_CLK calibration value: %d", cal_val);
196     esp_clk_slowclk_cal_set(cal_val);
197 }
198 
rtc_clk_select_rtc_slow_clk(void)199 void rtc_clk_select_rtc_slow_clk(void)
200 {
201     select_rtc_slow_clk(RTC_SLOW_FREQ_32K_XTAL);
202 }
203 
204 /* This function is not exposed as an API at this point.
205  * All peripheral clocks are default enabled after chip is powered on.
206  * This function disables some peripheral clocks when cpu starts.
207  * These peripheral clocks are enabled when the peripherals are initialized
208  * and disabled when they are de-initialized.
209  */
esp_perip_clk_init(void)210 __attribute__((weak)) void esp_perip_clk_init(void)
211 {
212     uint32_t common_perip_clk, hwcrypto_perip_clk, wifi_bt_sdio_clk = 0;
213     uint32_t common_perip_clk1 = 0;
214 
215 #if CONFIG_FREERTOS_UNICORE
216     soc_reset_reason_t rst_reas[1];
217 #else
218     soc_reset_reason_t rst_reas[2];
219 #endif
220 
221     rst_reas[0] = esp_rom_get_reset_reason(0);
222 #if !CONFIG_FREERTOS_UNICORE
223     rst_reas[1] = esp_rom_get_reset_reason(1);
224 #endif
225 
226     /* For reason that only reset CPU, do not disable the clocks
227      * that have been enabled before reset.
228      */
229     if ((rst_reas[0] == RESET_REASON_CPU0_MWDT0 || rst_reas[0] == RESET_REASON_CPU0_SW ||
230             rst_reas[0] == RESET_REASON_CPU0_RTC_WDT || rst_reas[0] == RESET_REASON_CPU0_MWDT1)
231 #if !CONFIG_FREERTOS_UNICORE
232         || (rst_reas[1] == RESET_REASON_CPU1_MWDT0 || rst_reas[1] == RESET_REASON_CPU1_SW ||
233             rst_reas[1] == RESET_REASON_CPU1_RTC_WDT || rst_reas[1] == RESET_REASON_CPU1_MWDT1)
234 #endif
235        ) {
236         common_perip_clk = ~READ_PERI_REG(SYSTEM_PERIP_CLK_EN0_REG);
237         hwcrypto_perip_clk = ~READ_PERI_REG(SYSTEM_PERIP_CLK_EN1_REG);
238         wifi_bt_sdio_clk = ~READ_PERI_REG(SYSTEM_WIFI_CLK_EN_REG);
239     } else {
240         common_perip_clk = SYSTEM_WDG_CLK_EN |
241                            SYSTEM_I2S0_CLK_EN |
242 #if CONFIG_CONSOLE_UART_NUM != 0
243                            SYSTEM_UART_CLK_EN |
244 #endif
245 #if CONFIG_CONSOLE_UART_NUM != 1
246                            SYSTEM_UART1_CLK_EN |
247 #endif
248 #if CONFIG_CONSOLE_UART_NUM != 2
249                            SYSTEM_UART2_CLK_EN |
250 #endif
251                            SYSTEM_USB_CLK_EN |
252                            SYSTEM_SPI2_CLK_EN |
253                            SYSTEM_I2C_EXT0_CLK_EN |
254                            SYSTEM_UHCI0_CLK_EN |
255                            SYSTEM_RMT_CLK_EN |
256                            SYSTEM_PCNT_CLK_EN |
257                            SYSTEM_LEDC_CLK_EN |
258                            SYSTEM_TIMERGROUP1_CLK_EN |
259                            SYSTEM_SPI3_CLK_EN |
260                            SYSTEM_SPI4_CLK_EN |
261                            SYSTEM_PWM0_CLK_EN |
262                            SYSTEM_TWAI_CLK_EN |
263                            SYSTEM_PWM1_CLK_EN |
264                            SYSTEM_I2S1_CLK_EN |
265                            SYSTEM_SPI2_DMA_CLK_EN |
266                            SYSTEM_SPI3_DMA_CLK_EN |
267                            SYSTEM_PWM2_CLK_EN |
268                            SYSTEM_PWM3_CLK_EN;
269         common_perip_clk1 = 0;
270         hwcrypto_perip_clk = SYSTEM_CRYPTO_AES_CLK_EN |
271                              SYSTEM_CRYPTO_SHA_CLK_EN |
272                              SYSTEM_CRYPTO_RSA_CLK_EN;
273         wifi_bt_sdio_clk = SYSTEM_WIFI_CLK_WIFI_EN |
274                            SYSTEM_WIFI_CLK_BT_EN_M |
275                            SYSTEM_WIFI_CLK_UNUSED_BIT5 |
276                            SYSTEM_WIFI_CLK_UNUSED_BIT12 |
277                            SYSTEM_WIFI_CLK_SDIO_HOST_EN;
278     }
279 
280     //Reset the communication peripherals like I2C, SPI, UART, I2S and bring them to known state.
281     common_perip_clk |= SYSTEM_I2S0_CLK_EN |
282 #if CONFIG_CONSOLE_UART_NUM != 0
283                         SYSTEM_UART_CLK_EN |
284 #endif
285 #if CONFIG_CONSOLE_UART_NUM != 1
286                         SYSTEM_UART1_CLK_EN |
287 #endif
288 #if CONFIG_CONSOLE_UART_NUM != 2
289                         SYSTEM_UART2_CLK_EN |
290 #endif
291                         SYSTEM_USB_CLK_EN |
292                         SYSTEM_SPI2_CLK_EN |
293                         SYSTEM_I2C_EXT0_CLK_EN |
294                         SYSTEM_UHCI0_CLK_EN |
295                         SYSTEM_RMT_CLK_EN |
296                         SYSTEM_UHCI1_CLK_EN |
297                         SYSTEM_SPI3_CLK_EN |
298                         SYSTEM_SPI4_CLK_EN |
299                         SYSTEM_I2C_EXT1_CLK_EN |
300                         SYSTEM_I2S1_CLK_EN |
301                         SYSTEM_SPI2_DMA_CLK_EN |
302                         SYSTEM_SPI3_DMA_CLK_EN;
303     common_perip_clk1 = 0;
304 
305     /* Disable some peripheral clocks. */
306     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN0_REG, common_perip_clk);
307     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN0_REG, common_perip_clk);
308 
309     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN1_REG, common_perip_clk1);
310     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, common_perip_clk1);
311 
312     /* Disable hardware crypto clocks. */
313     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN1_REG, hwcrypto_perip_clk);
314     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, hwcrypto_perip_clk);
315 
316     /* Force clear backup dma reset signal. This is a fix to the backup dma
317      * implementation in the ROM, the reset signal was not cleared when the
318      * backup dma was started, which caused the backup dma operation to fail. */
319     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, SYSTEM_PERI_BACKUP_RST);
320 
321     /* Disable WiFi/BT/SDIO clocks. */
322     CLEAR_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, wifi_bt_sdio_clk);
323     SET_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_EN);
324 
325     /* Set WiFi light sleep clock source to RTC slow clock */
326     REG_SET_FIELD(SYSTEM_BT_LPCK_DIV_INT_REG, SYSTEM_BT_LPCK_DIV_NUM, 0);
327     CLEAR_PERI_REG_MASK(SYSTEM_BT_LPCK_DIV_FRAC_REG, SYSTEM_LPCLK_SEL_8M);
328     SET_PERI_REG_MASK(SYSTEM_BT_LPCK_DIV_FRAC_REG, SYSTEM_LPCLK_SEL_RTC_SLOW);
329 
330     /* Enable RNG clock. */
331     periph_module_enable(PERIPH_RNG_MODULE);
332 }
333