1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdbool.h>
8 #include <stdint.h>
9 #include <stddef.h>
10 #include <stdlib.h>
11 #include "esp_rom_uart.h"
12 #include "esp32s3/rom/rtc.h"
13 #include "soc/rtc.h"
14 #include "soc/rtc_cntl_reg.h"
15 #include "soc/syscon_reg.h"
16 #include "hal/cpu_hal.h"
17 #include "regi2c_ctrl.h"
18 #include "soc_log.h"
19 #include "rtc_clk_common.h"
20 
21 static const char *TAG = "rtc_clk_init";
22 
rtc_clk_init(rtc_clk_config_t cfg)23 void rtc_clk_init(rtc_clk_config_t cfg)
24 {
25     rtc_cpu_freq_config_t old_config, new_config;
26 
27     /* Set tuning parameters for 8M and 150k clocks.
28      * Note: this doesn't attempt to set the clocks to precise frequencies.
29      * Instead, we calibrate these clocks against XTAL frequency later, when necessary.
30      * - SCK_DCAP value controls tuning of 150k clock.
31      *   The higher the value of DCAP is, the lower is the frequency.
32      * - CK8M_DFREQ value controls tuning of 8M clock.
33      *   CLK_8M_DFREQ constant gives the best temperature characteristics.
34      */
35     REG_SET_FIELD(RTC_CNTL_REG, RTC_CNTL_SCK_DCAP, cfg.slow_clk_dcap);
36     REG_SET_FIELD(RTC_CNTL_CLK_CONF_REG, RTC_CNTL_CK8M_DFREQ, cfg.clk_8m_dfreq);
37 
38     /* Configure 150k clock division */
39     rtc_clk_divider_set(cfg.clk_rtc_clk_div);
40 
41     /* Configure 8M clock division */
42     rtc_clk_8m_divider_set(cfg.clk_8m_clk_div);
43 
44     /* Enable the internal bus used to configure PLLs */
45     SET_PERI_REG_BITS(ANA_CONFIG_REG, ANA_CONFIG_M, ANA_CONFIG_M, ANA_CONFIG_S);
46     CLEAR_PERI_REG_MASK(ANA_CONFIG_REG, I2C_APLL_M | I2C_BBPLL_M);
47 
48     rtc_xtal_freq_t xtal_freq = cfg.xtal_freq;
49     esp_rom_uart_tx_wait_idle(0);
50     rtc_clk_xtal_freq_update(xtal_freq);
51     rtc_clk_apb_freq_update(xtal_freq * MHZ);
52 
53     /* Set CPU frequency */
54     rtc_clk_cpu_freq_get_config(&old_config);
55     uint32_t freq_before = old_config.freq_mhz;
56     bool res = rtc_clk_cpu_freq_mhz_to_config(cfg.cpu_freq_mhz, &new_config);
57     if (!res) {
58         SOC_LOGE(TAG, "invalid CPU frequency value");
59         abort();
60     }
61     rtc_clk_cpu_freq_set_config(&new_config);
62 
63     /* Re-calculate the ccount to make time calculation correct. */
64     cpu_hal_set_cycle_count( (uint64_t)cpu_hal_get_cycle_count() * cfg.cpu_freq_mhz / freq_before );
65 
66     /* Slow & fast clocks setup */
67     if (cfg.slow_freq == RTC_SLOW_FREQ_32K_XTAL) {
68         rtc_clk_32k_enable(true);
69     }
70     if (cfg.fast_freq == RTC_FAST_FREQ_8M) {
71         bool need_8md256 = cfg.slow_freq == RTC_SLOW_FREQ_8MD256;
72         rtc_clk_8m_enable(true, need_8md256);
73     }
74     rtc_clk_fast_freq_set(cfg.fast_freq);
75     rtc_clk_slow_freq_set(cfg.slow_freq);
76 }
77