1 /*
2  * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "hal/clk_tree_hal.h"
8 #include "hal/clk_tree_ll.h"
9 #include "soc/rtc.h"
10 #include "hal/assert.h"
11 #include "hal/log.h"
12 
13 static const char *CLK_HAL_TAG = "clk_hal";
14 
clk_hal_soc_root_get_freq_mhz(soc_cpu_clk_src_t cpu_clk_src)15 uint32_t clk_hal_soc_root_get_freq_mhz(soc_cpu_clk_src_t cpu_clk_src)
16 {
17     switch (cpu_clk_src) {
18     case SOC_CPU_CLK_SRC_XTAL:
19         return clk_hal_xtal_get_freq_mhz();
20     case SOC_CPU_CLK_SRC_PLL:
21         return clk_ll_bbpll_get_freq_mhz();
22     case SOC_CPU_CLK_SRC_RC_FAST:
23         return SOC_CLK_RC_FAST_FREQ_APPROX / MHZ;
24     default:
25         // Unknown CPU_CLK mux input
26         HAL_ASSERT(false);
27         return 0;
28     }
29 }
30 
clk_hal_cpu_get_freq_hz(void)31 uint32_t clk_hal_cpu_get_freq_hz(void)
32 {
33     soc_cpu_clk_src_t source = clk_ll_cpu_get_src();
34     uint32_t divider = (source == SOC_CPU_CLK_SRC_PLL) ? clk_ll_cpu_get_hs_divider() : clk_ll_cpu_get_ls_divider();
35     return clk_hal_soc_root_get_freq_mhz(source) * MHZ / divider;
36 }
37 
clk_hal_ahb_get_freq_hz(void)38 uint32_t clk_hal_ahb_get_freq_hz(void)
39 {
40     soc_cpu_clk_src_t source = clk_ll_cpu_get_src();
41     uint32_t divider = (source == SOC_CPU_CLK_SRC_PLL) ? clk_ll_ahb_get_hs_divider() : clk_ll_ahb_get_ls_divider();
42     return clk_hal_soc_root_get_freq_mhz(source) * MHZ / divider;
43 }
44 
clk_hal_apb_get_freq_hz(void)45 uint32_t clk_hal_apb_get_freq_hz(void)
46 {
47     return clk_hal_ahb_get_freq_hz() / clk_ll_apb_get_divider();
48 }
49 
clk_hal_lp_slow_get_freq_hz(void)50 uint32_t clk_hal_lp_slow_get_freq_hz(void)
51 {
52     switch (clk_ll_rtc_slow_get_src()) {
53     case SOC_RTC_SLOW_CLK_SRC_RC_SLOW:
54         return SOC_CLK_RC_SLOW_FREQ_APPROX;
55     case SOC_RTC_SLOW_CLK_SRC_XTAL32K:
56         return SOC_CLK_XTAL32K_FREQ_APPROX;
57     case SOC_RTC_SLOW_CLK_SRC_OSC_SLOW:
58         return SOC_CLK_OSC_SLOW_FREQ_APPROX;
59     case SOC_RTC_SLOW_CLK_SRC_RC32K:
60         return SOC_CLK_RC32K_FREQ_APPROX;
61     default:
62         // Unknown RTC_SLOW_CLK mux input
63         HAL_ASSERT(false);
64         return 0;
65     }
66 }
67 
clk_hal_xtal_get_freq_mhz(void)68 uint32_t clk_hal_xtal_get_freq_mhz(void)
69 {
70     uint32_t freq = clk_ll_xtal_load_freq_mhz();
71     if (freq == 0) {
72         HAL_LOGW(CLK_HAL_TAG, "invalid RTC_XTAL_FREQ_REG value, assume 40MHz");
73         return (uint32_t)RTC_XTAL_FREQ_40M;
74     }
75     return freq;
76 }
77