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