1 
2 // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include <stdint.h>
17 #include <sys/cdefs.h>
18 #include <sys/time.h>
19 #include <sys/param.h>
20 #include "sdkconfig.h"
21 #include "esp_attr.h"
22 #include "esp_log.h"
23 #include "esp32s2/clk.h"
24 #include "esp_clk_internal.h"
25 #include "esp32s2/rom/rtc.h"
26 #include "esp_rom_uart.h"
27 #include "soc/system_reg.h"
28 #include "soc/dport_access.h"
29 #include "soc/soc.h"
30 #include "soc/rtc.h"
31 #include "soc/rtc_periph.h"
32 #include "soc/i2s_reg.h"
33 #include "hal/cpu_hal.h"
34 #include "hal/wdt_hal.h"
35 #include "driver/periph_ctrl.h"
36 #include "bootloader_clock.h"
37 #include "soc/syscon_reg.h"
38 
39 static const char *TAG = "clk";
40 
41 /* Number of cycles to wait from the 32k XTAL oscillator to consider it running.
42  * Larger values increase startup delay. Smaller values may cause false positive
43  * detection (i.e. oscillator runs for a few cycles and then stops).
44  */
45 #define SLOW_CLK_CAL_CYCLES     CONFIG_ESP32S2_RTC_CLK_CAL_CYCLES
46 
47 #ifdef CONFIG_ESP32S2_RTC_XTAL_CAL_RETRY
48 #define RTC_XTAL_CAL_RETRY CONFIG_ESP32S2_RTC_XTAL_CAL_RETRY
49 #else
50 #define RTC_XTAL_CAL_RETRY 1
51 #endif
52 
53 /* Lower threshold for a reasonably-looking calibration value for a 32k XTAL.
54  * The ideal value (assuming 32768 Hz frequency) is 1000000/32768*(2**19) = 16*10^6.
55  */
56 #define MIN_32K_XTAL_CAL_VAL  15000000L
57 
58 /* Indicates that this 32k oscillator gets input from external oscillator, rather
59  * than a crystal.
60  */
61 #define EXT_OSC_FLAG    BIT(3)
62 
63 /* This is almost the same as rtc_slow_freq_t, except that we define
64  * an extra enum member for the external 32k oscillator.
65  * For convenience, lower 2 bits should correspond to rtc_slow_freq_t values.
66  */
67 typedef enum {
68     SLOW_CLK_RTC = RTC_SLOW_FREQ_RTC,           //!< Internal 90 kHz RC oscillator
69     SLOW_CLK_32K_XTAL = RTC_SLOW_FREQ_32K_XTAL, //!< External 32 kHz XTAL
70     SLOW_CLK_8MD256 = RTC_SLOW_FREQ_8MD256,     //!< Internal 8 MHz RC oscillator, divided by 256
71     SLOW_CLK_32K_EXT_OSC = RTC_SLOW_FREQ_32K_XTAL | EXT_OSC_FLAG //!< External 32k oscillator connected to 32K_XP pin
72 } slow_clk_sel_t;
73 
74 static void select_rtc_slow_clk(slow_clk_sel_t slow_clk);
75 
esp_clk_init(void)76  __attribute__((weak)) void esp_clk_init(void)
77 {
78     rtc_config_t cfg = RTC_CONFIG_DEFAULT();
79     RESET_REASON rst_reas;
80     rst_reas = rtc_get_reset_reason(0);
81     if (rst_reas == POWERON_RESET) {
82         cfg.cali_ocode = 1;
83     }
84     rtc_init(cfg);
85 
86     assert(rtc_clk_xtal_freq_get() == RTC_XTAL_FREQ_40M);
87 
88     rtc_clk_fast_freq_set(RTC_FAST_FREQ_8M);
89 
90 #ifdef CONFIG_BOOTLOADER_WDT_ENABLE
91     // WDT uses a SLOW_CLK clock source. After a function select_rtc_slow_clk a frequency of this source can changed.
92     // If the frequency changes from 90kHz to 32kHz, then the timeout set for the WDT will increase 2.8 times.
93     // Therefore, for the time of frequency change, set a new lower timeout value (1.6 sec).
94     // This prevents excessive delay before resetting in case the supply voltage is drawdown.
95     // (If frequency is changed from 90kHz to 32kHz then WDT timeout will increased to 1.6sec * 90/32 = 4.5 sec).
96     wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
97     uint32_t stage_timeout_ticks = (uint32_t)(1600ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
98     wdt_hal_write_protect_disable(&rtc_wdt_ctx);
99     wdt_hal_feed(&rtc_wdt_ctx);
100     //Bootloader has enabled RTC WDT until now. We're only modifying timeout, so keep the stage and  timeout action the same
101     wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
102     wdt_hal_write_protect_enable(&rtc_wdt_ctx);
103 #endif
104 
105 #if defined(CONFIG_ESP32S2_RTC_CLK_SRC_EXT_CRYS)
106     select_rtc_slow_clk(SLOW_CLK_32K_XTAL);
107 #elif defined(CONFIG_ESP32S2_RTC_CLK_SRC_EXT_OSC)
108     select_rtc_slow_clk(SLOW_CLK_32K_EXT_OSC);
109 #elif defined(CONFIG_ESP32S2_RTC_CLK_SRC_INT_8MD256)
110     select_rtc_slow_clk(SLOW_CLK_8MD256);
111 #else
112     select_rtc_slow_clk(RTC_SLOW_FREQ_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() / 1000ULL);
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_ESP32S2_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     if (CONFIG_ESP_CONSOLE_UART_NUM >= 0) {
135         esp_rom_uart_tx_wait_idle(CONFIG_ESP_CONSOLE_UART_NUM);
136     }
137 
138     rtc_clk_cpu_freq_set_config(&new_config);
139 
140     // Re calculate the ccount to make time calculation correct.
141     cpu_hal_set_cycle_count( (uint64_t)cpu_hal_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     rtc_slow_freq_t rtc_slow_freq = slow_clk & RTC_CNTL_ANA_CLK_RTC_SEL_V;
147     uint32_t cal_val = 0;
148     /* number of times to repeat 32k XTAL calibration
149      * before giving up and switching to the internal RC
150      */
151     int retry_32k_xtal = RTC_XTAL_CAL_RETRY;
152 
153     do {
154         if (rtc_slow_freq == RTC_SLOW_FREQ_32K_XTAL) {
155             /* 32k XTAL oscillator needs to be enabled and running before it can
156              * be used. Hardware doesn't have a direct way of checking if the
157              * oscillator is running. Here we use rtc_clk_cal function to count
158              * the number of main XTAL cycles in the given number of 32k XTAL
159              * oscillator cycles. If the 32k XTAL has not started up, calibration
160              * will time out, returning 0.
161              */
162             ESP_EARLY_LOGD(TAG, "waiting for 32k oscillator to start up");
163             if (slow_clk == SLOW_CLK_32K_XTAL) {
164                 rtc_clk_32k_enable(true);
165             } else if (slow_clk == SLOW_CLK_32K_EXT_OSC) {
166                 rtc_clk_32k_enable_external();
167             }
168             // When SLOW_CLK_CAL_CYCLES is set to 0, clock calibration will not be performed at startup.
169             if (SLOW_CLK_CAL_CYCLES > 0) {
170                 cal_val = rtc_clk_cal(RTC_CAL_32K_XTAL, SLOW_CLK_CAL_CYCLES);
171                 if (cal_val == 0 || cal_val < MIN_32K_XTAL_CAL_VAL) {
172                     if (retry_32k_xtal-- > 0) {
173                         continue;
174                     }
175                     ESP_EARLY_LOGW(TAG, "32 kHz XTAL not found, switching to internal 90 kHz oscillator");
176                     rtc_slow_freq = RTC_SLOW_FREQ_RTC;
177                 }
178             }
179         } else if (rtc_slow_freq == RTC_SLOW_FREQ_8MD256) {
180             rtc_clk_8m_enable(true, true);
181         }
182         rtc_clk_slow_freq_set(rtc_slow_freq);
183 
184         if (SLOW_CLK_CAL_CYCLES > 0) {
185             /* TODO: 32k XTAL oscillator has some frequency drift at startup.
186              * Improve calibration routine to wait until the frequency is stable.
187              */
188             cal_val = rtc_clk_cal(RTC_CAL_RTC_MUX, SLOW_CLK_CAL_CYCLES);
189         } else {
190             const uint64_t cal_dividend = (1ULL << RTC_CLK_CAL_FRACT) * 1000000ULL;
191             cal_val = (uint32_t) (cal_dividend / rtc_clk_slow_freq_get_hz());
192         }
193     } while (cal_val == 0);
194     ESP_EARLY_LOGD(TAG, "RTC_SLOW_CLK calibration value: %d", cal_val);
195     esp_clk_slowclk_cal_set(cal_val);
196 }
197 
rtc_clk_select_rtc_slow_clk(void)198 void rtc_clk_select_rtc_slow_clk(void)
199 {
200     select_rtc_slow_clk(RTC_SLOW_FREQ_32K_XTAL);
201 }
202 
203 /* This function is not exposed as an API at this point.
204  * All peripheral clocks are default enabled after chip is powered on.
205  * This function disables some peripheral clocks when cpu starts.
206  * These peripheral clocks are enabled when the peripherals are initialized
207  * and disabled when they are de-initialized.
208  */
esp_perip_clk_init(void)209 __attribute__((weak)) void esp_perip_clk_init(void)
210 {
211     uint32_t common_perip_clk, hwcrypto_perip_clk, wifi_bt_sdio_clk = 0;
212     uint32_t common_perip_clk1 = 0;
213 
214     RESET_REASON rst_reas[1];
215 
216     rst_reas[0] = rtc_get_reset_reason(0);
217 
218     /* For reason that only reset CPU, do not disable the clocks
219      * that have been enabled before reset.
220      */
221     if (rst_reas[0] >= TG0WDT_CPU_RESET &&
222             rst_reas[0] <= TG0WDT_CPU_RESET &&
223             rst_reas[0] != RTCWDT_BROWN_OUT_RESET) {
224         common_perip_clk = ~DPORT_READ_PERI_REG(DPORT_PERIP_CLK_EN_REG);
225         hwcrypto_perip_clk = ~DPORT_READ_PERI_REG(DPORT_PERIP_CLK_EN1_REG);
226         wifi_bt_sdio_clk = ~DPORT_READ_PERI_REG(DPORT_WIFI_CLK_EN_REG);
227     } else {
228         common_perip_clk = DPORT_WDG_CLK_EN |
229                            DPORT_I2S0_CLK_EN |
230 #if CONFIG_ESP_CONSOLE_UART_NUM != 0
231                            DPORT_UART_CLK_EN |
232 #endif
233 #if CONFIG_ESP_CONSOLE_UART_NUM != 1
234                            DPORT_UART1_CLK_EN |
235 #endif
236                            DPORT_SPI2_CLK_EN |
237                            DPORT_I2C_EXT0_CLK_EN |
238                            DPORT_UHCI0_CLK_EN |
239                            DPORT_RMT_CLK_EN |
240                            DPORT_PCNT_CLK_EN |
241                            DPORT_LEDC_CLK_EN |
242                            DPORT_TIMERGROUP1_CLK_EN |
243                            DPORT_SPI3_CLK_EN |
244                            DPORT_PWM0_CLK_EN |
245                            DPORT_TWAI_CLK_EN |
246                            DPORT_PWM1_CLK_EN |
247                            DPORT_I2S1_CLK_EN |
248                            DPORT_SPI2_DMA_CLK_EN |
249                            DPORT_SPI3_DMA_CLK_EN |
250                            DPORT_PWM2_CLK_EN |
251                            DPORT_PWM3_CLK_EN;
252         common_perip_clk1 = 0;
253         hwcrypto_perip_clk = DPORT_CRYPTO_AES_CLK_EN |
254                              DPORT_CRYPTO_SHA_CLK_EN |
255                              DPORT_CRYPTO_RSA_CLK_EN;
256         wifi_bt_sdio_clk = DPORT_WIFI_CLK_WIFI_EN |
257                            DPORT_WIFI_CLK_BT_EN_M |
258                            DPORT_WIFI_CLK_UNUSED_BIT5 |
259                            DPORT_WIFI_CLK_UNUSED_BIT12 |
260                            DPORT_WIFI_CLK_SDIOSLAVE_EN |
261                            DPORT_WIFI_CLK_SDIO_HOST_EN |
262                            DPORT_WIFI_CLK_EMAC_EN;
263     }
264 
265     //Reset the communication peripherals like I2C, SPI, UART, I2S and bring them to known state.
266     common_perip_clk |= DPORT_I2S0_CLK_EN |
267 #if CONFIG_ESP_CONSOLE_UART_NUM != 0
268                         DPORT_UART_CLK_EN |
269 #endif
270 #if CONFIG_ESP_CONSOLE_UART_NUM != 1
271                         DPORT_UART1_CLK_EN |
272 #endif
273 #ifndef CONFIG_ESP32S2_KEEP_USB_ALIVE
274                         DPORT_USB_CLK_EN |
275 #endif
276                         DPORT_SPI2_CLK_EN |
277                         DPORT_I2C_EXT0_CLK_EN |
278                         DPORT_UHCI0_CLK_EN |
279                         DPORT_RMT_CLK_EN |
280                         DPORT_UHCI1_CLK_EN |
281                         DPORT_SPI3_CLK_EN |
282                         DPORT_I2C_EXT1_CLK_EN |
283                         DPORT_I2S1_CLK_EN |
284                         DPORT_SPI2_DMA_CLK_EN |
285                         DPORT_SPI3_DMA_CLK_EN;
286     common_perip_clk1 = 0;
287 
288     /* Change I2S clock to audio PLL first. Because if I2S uses 160MHz clock,
289      * the current is not reduced when disable I2S clock.
290      */
291     REG_SET_FIELD(I2S_CLKM_CONF_REG(0), I2S_CLK_SEL, I2S_CLK_AUDIO_PLL);
292     REG_SET_FIELD(I2S_CLKM_CONF_REG(1), I2S_CLK_SEL, I2S_CLK_AUDIO_PLL);
293 
294     /* Disable some peripheral clocks. */
295     DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, common_perip_clk);
296     DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, common_perip_clk);
297 
298     DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_CLK_EN1_REG, common_perip_clk1);
299     DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN1_REG, common_perip_clk1);
300 
301     /* Disable hardware crypto clocks. */
302     DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_CLK_EN1_REG, hwcrypto_perip_clk);
303     DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN1_REG, hwcrypto_perip_clk);
304 
305     /* Disable WiFi/BT/SDIO clocks. */
306     DPORT_CLEAR_PERI_REG_MASK(DPORT_WIFI_CLK_EN_REG, wifi_bt_sdio_clk);
307 
308     /* Enable WiFi MAC and POWER clocks */
309     DPORT_SET_PERI_REG_MASK(DPORT_WIFI_CLK_EN_REG, DPORT_WIFI_CLK_WIFI_EN);
310 
311     /* Set WiFi light sleep clock source to RTC slow clock */
312     DPORT_REG_SET_FIELD(DPORT_BT_LPCK_DIV_INT_REG, DPORT_BT_LPCK_DIV_NUM, 0);
313     DPORT_CLEAR_PERI_REG_MASK(DPORT_BT_LPCK_DIV_FRAC_REG, DPORT_LPCLK_SEL_8M);
314     DPORT_SET_PERI_REG_MASK(DPORT_BT_LPCK_DIV_FRAC_REG, DPORT_LPCLK_SEL_RTC_SLOW);
315 
316     /* Enable RNG clock. */
317     periph_module_enable(PERIPH_RNG_MODULE);
318 }
319