1 /*
2  * SPDX-FileCopyrightText: 2022-2023 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_clk_internal.h"
14 #include "esp32c6/rom/ets_sys.h"
15 #include "esp32c6/rom/uart.h"
16 #include "soc/soc.h"
17 #include "soc/rtc.h"
18 #include "soc/rtc_periph.h"
19 #include "soc/i2s_reg.h"
20 #include "esp_cpu.h"
21 #include "hal/wdt_hal.h"
22 #include "esp_private/esp_modem_clock.h"
23 #include "esp_private/periph_ctrl.h"
24 #include "esp_private/esp_clk.h"
25 #include "esp_private/esp_pmu.h"
26 #include "esp_rom_uart.h"
27 #include "esp_rom_sys.h"
28 #include "ocode_init.h"
29 
30 /* Number of cycles to wait from the 32k XTAL oscillator to consider it running.
31  * Larger values increase startup delay. Smaller values may cause false positive
32  * detection (i.e. oscillator runs for a few cycles and then stops).
33  */
34 #define SLOW_CLK_CAL_CYCLES     CONFIG_RTC_CLK_CAL_CYCLES
35 
36 static void select_rtc_slow_clk(soc_rtc_slow_clk_src_t rtc_slow_clk_src);
37 
38 static const char *TAG = "clk";
39 
40 
esp_clk_init(void)41 __attribute__((weak)) void esp_clk_init(void)
42 {
43 #if !CONFIG_IDF_ENV_FPGA
44     pmu_init();
45     if (esp_rom_get_reset_reason(0) == RESET_REASON_CHIP_POWER_ON) {
46         esp_ocode_calib_init();
47     }
48 
49     assert(rtc_clk_xtal_freq_get() == RTC_XTAL_FREQ_40M);
50 
51     rtc_clk_8m_enable(true);
52     rtc_clk_fast_src_set(SOC_RTC_FAST_CLK_SRC_RC_FAST);
53 #endif
54 
55 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
56     // WDT uses a SLOW_CLK clock source. After a function select_rtc_slow_clk a frequency of this source can changed.
57     // If the frequency changes from 150kHz to 32kHz, then the timeout set for the WDT will increase 4.6 times.
58     // Therefore, for the time of frequency change, set a new lower timeout value (1.6 sec).
59     // This prevents excessive delay before resetting in case the supply voltage is drawdown.
60     // (If frequency is changed from 150kHz to 32kHz then WDT timeout will increased to 1.6sec * 150/32 = 7.5 sec).
61     wdt_hal_context_t rtc_wdt_ctx = RWDT_HAL_CONTEXT_DEFAULT();
62     uint32_t stage_timeout_ticks = (uint32_t)(1600ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
63     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
64     wdt_hal_feed(&rtc_wdt_ctx);
65     //Bootloader has enabled RTC WDT until now. We're only modifying timeout, so keep the stage and timeout action the same
66     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
67     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
68 #endif
69 
70 #if defined(CONFIG_RTC_CLK_SRC_EXT_CRYS)
71     select_rtc_slow_clk(SOC_RTC_SLOW_CLK_SRC_XTAL32K);
72 #elif defined(CONFIG_RTC_CLK_SRC_EXT_OSC)
73     select_rtc_slow_clk(SOC_RTC_SLOW_CLK_SRC_OSC_SLOW);
74 #elif defined(CONFIG_RTC_CLK_SRC_INT_RC32K)
75     select_rtc_slow_clk(SOC_RTC_SLOW_CLK_SRC_RC32K);
76 #else
77     select_rtc_slow_clk(SOC_RTC_SLOW_CLK_SRC_RC_SLOW);
78 #endif
79 
80 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
81     // After changing a frequency WDT timeout needs to be set for new frequency.
82     stage_timeout_ticks = (uint32_t)((uint64_t)CONFIG_BOOTLOADER_WDT_TIME_MS * rtc_clk_slow_freq_get_hz() / 1000);
83     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
84     wdt_hal_feed(&rtc_wdt_ctx);
85     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
86     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
87 #endif
88 
89     rtc_cpu_freq_config_t old_config, new_config;
90     rtc_clk_cpu_freq_get_config(&old_config);
91     const uint32_t old_freq_mhz = old_config.freq_mhz;
92     const uint32_t new_freq_mhz = CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ;
93 
94     bool res = rtc_clk_cpu_freq_mhz_to_config(new_freq_mhz, &new_config);
95     assert(res);
96 
97     // Wait for UART TX to finish, otherwise some UART output will be lost
98     // when switching APB frequency
99     esp_rom_uart_tx_wait_idle(CONFIG_ESP_CONSOLE_UART_NUM);
100 
101     if (res)  {
102         rtc_clk_cpu_freq_set_config(&new_config);
103     }
104 
105     // Re calculate the ccount to make time calculation correct.
106     esp_cpu_set_cycle_count( (uint64_t)esp_cpu_get_cycle_count() * new_freq_mhz / old_freq_mhz );
107 }
108 
select_rtc_slow_clk(soc_rtc_slow_clk_src_t rtc_slow_clk_src)109 static void select_rtc_slow_clk(soc_rtc_slow_clk_src_t rtc_slow_clk_src)
110 {
111     uint32_t cal_val = 0;
112     /* number of times to repeat 32k XTAL calibration
113      * before giving up and switching to the internal RC
114      */
115     int retry_32k_xtal = 3;
116 
117     do {
118         if (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_XTAL32K || rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_OSC_SLOW) {
119             /* 32k XTAL oscillator needs to be enabled and running before it can
120              * be used. Hardware doesn't have a direct way of checking if the
121              * oscillator is running. Here we use rtc_clk_cal function to count
122              * the number of main XTAL cycles in the given number of 32k XTAL
123              * oscillator cycles. If the 32k XTAL has not started up, calibration
124              * will time out, returning 0.
125              */
126             ESP_EARLY_LOGD(TAG, "waiting for 32k oscillator to start up");
127             rtc_cal_sel_t cal_sel = 0;
128             if (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_XTAL32K) {
129                 rtc_clk_32k_enable(true);
130                 cal_sel = RTC_CAL_32K_XTAL;
131             } else if (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_OSC_SLOW) {
132                 rtc_clk_32k_enable_external();
133                 cal_sel = RTC_CAL_32K_OSC_SLOW;
134             }
135             // When SLOW_CLK_CAL_CYCLES is set to 0, clock calibration will not be performed at startup.
136             if (SLOW_CLK_CAL_CYCLES > 0) {
137                 cal_val = rtc_clk_cal(cal_sel, SLOW_CLK_CAL_CYCLES);
138                 if (cal_val == 0) {
139                     if (retry_32k_xtal-- > 0) {
140                         continue;
141                     }
142                     ESP_EARLY_LOGW(TAG, "32 kHz clock not found, switching to internal 150 kHz oscillator");
143                     rtc_slow_clk_src = SOC_RTC_SLOW_CLK_SRC_RC_SLOW;
144                 }
145             }
146         } else if (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_RC32K) {
147             rtc_clk_rc32k_enable(true);
148         }
149         rtc_clk_slow_src_set(rtc_slow_clk_src);
150 
151         if (SLOW_CLK_CAL_CYCLES > 0) {
152             /* TODO: 32k XTAL oscillator has some frequency drift at startup.
153              * Improve calibration routine to wait until the frequency is stable.
154              */
155             cal_val = rtc_clk_cal(RTC_CAL_RTC_MUX, SLOW_CLK_CAL_CYCLES);
156         } else {
157             const uint64_t cal_dividend = (1ULL << RTC_CLK_CAL_FRACT) * 1000000ULL;
158             cal_val = (uint32_t) (cal_dividend / rtc_clk_slow_freq_get_hz());
159         }
160     } while (cal_val == 0);
161     ESP_EARLY_LOGD(TAG, "RTC_SLOW_CLK calibration value: %d", cal_val);
162     esp_clk_slowclk_cal_set(cal_val);
163 }
164 
rtc_clk_select_rtc_slow_clk(void)165 void rtc_clk_select_rtc_slow_clk(void)
166 {
167     select_rtc_slow_clk(SOC_RTC_SLOW_CLK_SRC_XTAL32K);
168 }
169 
170 /* This function is not exposed as an API at this point.
171  * All peripheral clocks are default enabled after chip is powered on.
172  * This function disables some peripheral clocks when cpu starts.
173  * These peripheral clocks are enabled when the peripherals are initialized
174  * and disabled when they are de-initialized.
175  */
esp_perip_clk_init(void)176 __attribute__((weak)) void esp_perip_clk_init(void)
177 {
178     modem_clock_domain_pmu_state_icg_map_init();
179 
180     /* During system initialization, the low-power clock source of the modem
181      * (WiFi, BLE or Coexist) follows the configuration of the slow clock source
182      * of the system. If the WiFi, BLE or Coexist module needs a higher
183      * precision sleep clock (for example, the BLE needs to use the main XTAL
184      * oscillator (40 MHz) to provide the clock during the sleep process in some
185      * scenarios), the module needs to switch to the required clock source by
186      * itself. */ //TODO - WIFI-5233
187     soc_rtc_slow_clk_src_t rtc_slow_clk_src = rtc_clk_slow_src_get();
188     modem_clock_lpclk_src_t modem_lpclk_src = (modem_clock_lpclk_src_t) ( \
189                   (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_RC_SLOW)  ? MODEM_CLOCK_LPCLK_SRC_RC_SLOW \
190                 : (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_XTAL32K)  ? MODEM_CLOCK_LPCLK_SRC_XTAL32K  \
191                 : (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_RC32K)    ? MODEM_CLOCK_LPCLK_SRC_RC32K    \
192                 : (rtc_slow_clk_src == SOC_RTC_SLOW_CLK_SRC_OSC_SLOW) ? MODEM_CLOCK_LPCLK_SRC_EXT32K   \
193                 : SOC_RTC_SLOW_CLK_SRC_RC_SLOW);
194     modem_clock_select_lp_clock_source(PERIPH_WIFI_MODULE, modem_lpclk_src, 0);
195 
196     ESP_EARLY_LOGW(TAG, "esp_perip_clk_init() has not been implemented yet");
197 #if 0 // TODO: IDF-5658
198     uint32_t common_perip_clk, hwcrypto_perip_clk, wifi_bt_sdio_clk = 0;
199     uint32_t common_perip_clk1 = 0;
200 
201     soc_reset_reason_t rst_reason = esp_rom_get_reset_reason(0);
202 
203     /* For reason that only reset CPU, do not disable the clocks
204      * that have been enabled before reset.
205      */
206     if (rst_reason == RESET_REASON_CPU0_MWDT0 || rst_reason == RESET_REASON_CPU0_SW ||
207             rst_reason == RESET_REASON_CPU0_RTC_WDT || rst_reason == RESET_REASON_CPU0_MWDT1) {
208         common_perip_clk = ~READ_PERI_REG(SYSTEM_PERIP_CLK_EN0_REG);
209         hwcrypto_perip_clk = ~READ_PERI_REG(SYSTEM_PERIP_CLK_EN1_REG);
210         wifi_bt_sdio_clk = ~READ_PERI_REG(SYSTEM_WIFI_CLK_EN_REG);
211     } else {
212         common_perip_clk = SYSTEM_WDG_CLK_EN |
213                            SYSTEM_I2S0_CLK_EN |
214 #if CONFIG_ESP_CONSOLE_UART_NUM != 0
215                            SYSTEM_UART_CLK_EN |
216 #endif
217 #if CONFIG_ESP_CONSOLE_UART_NUM != 1
218                            SYSTEM_UART1_CLK_EN |
219 #endif
220                            SYSTEM_SPI2_CLK_EN |
221                            SYSTEM_I2C_EXT0_CLK_EN |
222                            SYSTEM_UHCI0_CLK_EN |
223                            SYSTEM_RMT_CLK_EN |
224                            SYSTEM_LEDC_CLK_EN |
225                            SYSTEM_TIMERGROUP1_CLK_EN |
226                            SYSTEM_SPI3_CLK_EN |
227                            SYSTEM_SPI4_CLK_EN |
228                            SYSTEM_TWAI_CLK_EN |
229                            SYSTEM_I2S1_CLK_EN |
230                            SYSTEM_SPI2_DMA_CLK_EN |
231                            SYSTEM_SPI3_DMA_CLK_EN;
232 
233         common_perip_clk1 = 0;
234         hwcrypto_perip_clk = SYSTEM_CRYPTO_AES_CLK_EN |
235                              SYSTEM_CRYPTO_SHA_CLK_EN |
236                              SYSTEM_CRYPTO_RSA_CLK_EN;
237         wifi_bt_sdio_clk = SYSTEM_WIFI_CLK_WIFI_EN |
238                            SYSTEM_WIFI_CLK_BT_EN_M |
239                            SYSTEM_WIFI_CLK_UNUSED_BIT5 |
240                            SYSTEM_WIFI_CLK_UNUSED_BIT12;
241     }
242 
243     //Reset the communication peripherals like I2C, SPI, UART, I2S and bring them to known state.
244     common_perip_clk |= SYSTEM_I2S0_CLK_EN |
245 #if CONFIG_ESP_CONSOLE_UART_NUM != 0
246                         SYSTEM_UART_CLK_EN |
247 #endif
248 #if CONFIG_ESP_CONSOLE_UART_NUM != 1
249                         SYSTEM_UART1_CLK_EN |
250 #endif
251                         SYSTEM_SPI2_CLK_EN |
252                         SYSTEM_I2C_EXT0_CLK_EN |
253                         SYSTEM_UHCI0_CLK_EN |
254                         SYSTEM_RMT_CLK_EN |
255                         SYSTEM_UHCI1_CLK_EN |
256                         SYSTEM_SPI3_CLK_EN |
257                         SYSTEM_SPI4_CLK_EN |
258                         SYSTEM_I2C_EXT1_CLK_EN |
259                         SYSTEM_I2S1_CLK_EN |
260                         SYSTEM_SPI2_DMA_CLK_EN |
261                         SYSTEM_SPI3_DMA_CLK_EN;
262     common_perip_clk1 = 0;
263 
264     /* Change I2S clock to audio PLL first. Because if I2S uses 160MHz clock,
265      * the current is not reduced when disable I2S clock.
266      */
267     // TOCK(check replacement)
268     // REG_SET_FIELD(I2S_CLKM_CONF_REG(0), I2S_CLK_SEL, I2S_CLK_AUDIO_PLL);
269     // REG_SET_FIELD(I2S_CLKM_CONF_REG(1), I2S_CLK_SEL, I2S_CLK_AUDIO_PLL);
270 
271     /* Disable some peripheral clocks. */
272     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN0_REG, common_perip_clk);
273     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN0_REG, common_perip_clk);
274 
275     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN1_REG, common_perip_clk1);
276     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, common_perip_clk1);
277 
278     /* Disable hardware crypto clocks. */
279     CLEAR_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN1_REG, hwcrypto_perip_clk);
280     SET_PERI_REG_MASK(SYSTEM_PERIP_RST_EN1_REG, hwcrypto_perip_clk);
281 
282     /* Disable WiFi/BT/SDIO clocks. */
283     CLEAR_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, wifi_bt_sdio_clk);
284     SET_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_EN);
285 
286     /* Set WiFi light sleep clock source to RTC slow clock */
287     REG_SET_FIELD(SYSTEM_BT_LPCK_DIV_INT_REG, SYSTEM_BT_LPCK_DIV_NUM, 0);
288     CLEAR_PERI_REG_MASK(SYSTEM_BT_LPCK_DIV_FRAC_REG, SYSTEM_LPCLK_SEL_8M);
289     SET_PERI_REG_MASK(SYSTEM_BT_LPCK_DIV_FRAC_REG, SYSTEM_LPCLK_SEL_RTC_SLOW);
290 
291     /* Enable RNG clock. */
292     periph_module_enable(PERIPH_RNG_MODULE);
293 #endif
294 
295     /* Enable TimerGroup 0 clock to ensure its reference counter will never
296      * be decremented to 0 during normal operation and preventing it from
297      * being disabled.
298      * If the TimerGroup 0 clock is disabled and then reenabled, the watchdog
299      * registers (Flashboot protection included) will be reenabled, and some
300      * seconds later, will trigger an unintended reset.
301      */
302     periph_module_enable(PERIPH_TIMG0_MODULE);
303 }
304