Skip to main content

esp_hal/soc/esp32c61/
clocks.rs

1//! Clock tree definitions and implementations for ESP32-C61.
2//!
3//! Remarks:
4//! - Enabling a clock node assumes it has first been configured. Some fixed clock nodes don't need
5//!   to be configured.
6//! - Some information may be assumed, e.g. the possibility to disable watchdog timers before clock
7//!   configuration.
8//! - Internal RC oscillators (32K OSC_SLOW, 130k RC_SLOW and 20M RC_FAST) are not calibrated here,
9//!   this system can only give a rough estimate of their frequency. They can be calibrated
10//!   separately using a known crystal frequency.
11//! - Some of the SOC capabilities are not implemented: I2S external pad clock source, external 32k
12//!   oscillator, others.
13#![allow(dead_code, reason = "Some of this is bound to be unused")]
14#![allow(missing_docs, reason = "Experimental")]
15
16use crate::{
17    peripherals::{I2C_ANA_MST, LP_CLKRST, MODEM_LPCON, PCR, PMU},
18    soc::{regi2c, update_bus_clocks, with_single_bus_clock_update, xtal32k},
19};
20
21define_clock_tree_types!();
22
23/// Clock configuration options.
24#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
25#[cfg_attr(feature = "defmt", derive(defmt::Format))]
26#[allow(
27    clippy::enum_variant_names,
28    reason = "MHz suffix indicates physical unit."
29)]
30#[non_exhaustive]
31pub enum CpuClock {
32    /// Default CPU clock
33    #[default]
34    _80MHz  = 80,
35
36    /// 160 MHz CPU clock
37    _160MHz = 160,
38}
39
40impl CpuClock {
41    const PRESET_80: ClockConfig = ClockConfig {
42        xtal_clk: None,
43        hp_root_clk: Some(HpRootClkConfig::PllF160m),
44        cpu_clk: Some(CpuClkConfig::new(1)),
45        ahb_clk: Some(AhbClkConfig::new(3)),
46        apb_clk: Some(ApbClkConfig::new(0)),
47        lp_fast_clk: Some(LpFastClkConfig::RcFast),
48        lp_slow_clk: Some(xtal32k::default_lp_slow_clk()),
49        ble_lp_clk: Some(BleLpClkConfig::Xtal),
50        crypto_clk: Some(CryptoClkConfig::PllF480m),
51        timg_calibration_clock: None,
52    };
53    const PRESET_160: ClockConfig = ClockConfig {
54        xtal_clk: None,
55        hp_root_clk: Some(HpRootClkConfig::PllF160m),
56        cpu_clk: Some(CpuClkConfig::new(0)),
57        ahb_clk: Some(AhbClkConfig::new(3)),
58        apb_clk: Some(ApbClkConfig::new(0)),
59        lp_fast_clk: Some(LpFastClkConfig::RcFast),
60        lp_slow_clk: Some(xtal32k::default_lp_slow_clk()),
61        ble_lp_clk: Some(BleLpClkConfig::Xtal),
62        crypto_clk: Some(CryptoClkConfig::PllF480m),
63        timg_calibration_clock: None,
64    };
65}
66
67impl From<CpuClock> for ClockConfig {
68    fn from(value: CpuClock) -> ClockConfig {
69        match value {
70            CpuClock::_80MHz => CpuClock::PRESET_80,
71            CpuClock::_160MHz => CpuClock::PRESET_160,
72        }
73    }
74}
75
76impl Default for ClockConfig {
77    fn default() -> Self {
78        Self::from(CpuClock::default())
79    }
80}
81
82impl ClockConfig {
83    pub(crate) fn try_get_preset(self) -> Option<CpuClock> {
84        match self {
85            v if v == CpuClock::PRESET_80 => Some(CpuClock::_80MHz),
86            v if v == CpuClock::PRESET_160 => Some(CpuClock::_160MHz),
87            _ => None,
88        }
89    }
90
91    pub(crate) fn configure(mut self, clocks: &mut ClockTree) {
92        if self.xtal_clk.is_none() {
93            self.xtal_clk = Some(XtalClkConfig::_40);
94        }
95
96        with_single_bus_clock_update(|| self.apply(clocks));
97    }
98}
99
100// XTAL_CLK
101
102fn configure_xtal_clk_impl(
103    _clocks: &mut ClockTree,
104    _old_config: Option<XtalClkConfig>,
105    _config: XtalClkConfig,
106) {
107    // Nothing to do here.
108}
109
110/// Configures and calibrates the BBPLL again.
111///
112/// The BBPLL loses its analog configuration while the PMU powers it down, for example in a light
113/// sleep. ESP-IDF configures it again before it uses the PLL after a wake.
114pub(crate) fn reconfigure_pll(clocks: &mut ClockTree) {
115    if clocks.pll_clk_refcount > 0 {
116        enable_pll_clk_impl(clocks, true);
117    }
118}
119
120fn enable_pll_clk_impl(_clocks: &mut ClockTree, en: bool) {
121    if en {
122        PMU::regs().imm_hp_ck_power().write(|w| {
123            w.tie_high_xpd_bb_i2c().set_bit();
124            w.tie_high_xpd_bbpll().set_bit();
125            w.tie_high_xpd_bbpll_i2c().set_bit()
126        });
127        PMU::regs()
128            .imm_hp_ck_power()
129            .write(|w| w.tie_high_global_bbpll_icg().set_bit());
130    } else {
131        PMU::regs()
132            .imm_hp_ck_power()
133            .write(|w| w.tie_low_global_bbpll_icg().set_bit());
134        PMU::regs().imm_hp_ck_power().write(|w| {
135            w.tie_low_xpd_bb_i2c().set_bit();
136            w.tie_low_xpd_bbpll().set_bit();
137            w.tie_low_xpd_bbpll_i2c().set_bit()
138        });
139
140        return;
141    }
142
143    // Digital part - The target SPLL is fixed to 480MHz, do nothing.
144
145    // Analog part
146    I2C_ANA_MST::regs().ana_conf0().modify(|_, w| {
147        w.bbpll_stop_force_high().clear_bit();
148        w.bbpll_stop_force_low().set_bit()
149    });
150
151    const DIV7_0: u8 = 8;
152    const DIV_REF: u8 = 0; // Do not divide reference clock
153    const DCHGP: u8 = 5;
154    const DBIAS: u8 = 3;
155    const HREF: u8 = 3;
156    const LREF: u8 = 1;
157
158    const I2C_BBPLL_OC_DCHGP_LSB: u32 = 4;
159    // const I2C_BBPLL_OC_DHREF_SEL_LSB: u32 = 4;
160    // const I2C_BBPLL_OC_DLREF_SEL_LSB: u32 = 6;
161
162    const I2C_BBPLL_LREF: u8 = (DCHGP << I2C_BBPLL_OC_DCHGP_LSB) | DIV_REF;
163
164    regi2c::I2C_BBPLL_OC_REF.write_reg(I2C_BBPLL_LREF);
165    regi2c::I2C_BBPLL_OC_DIV_REG.write_reg(DIV7_0);
166    regi2c::I2C_BBPLL_OC_DLREF_SEL.write_field(LREF);
167    regi2c::I2C_BBPLL_OC_DHREF_SEL.write_field(HREF);
168    regi2c::I2C_BBPLL_OC_VCO_DBIAS.write_field(DBIAS);
169
170    // WAIT CALIBRATION DONE
171    while I2C_ANA_MST::regs()
172        .ana_conf0()
173        .read()
174        .cal_done()
175        .bit_is_clear()
176    {}
177    crate::rom::ets_delay_us(10);
178
179    // BBPLL CALIBRATION STOP
180    I2C_ANA_MST::regs().ana_conf0().modify(|_, w| {
181        w.bbpll_stop_force_high().set_bit();
182        w.bbpll_stop_force_low().clear_bit()
183    });
184}
185
186// RC_FAST_CLK
187
188fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) {
189    LP_CLKRST::regs()
190        .clk_to_hp()
191        .modify(|_, w| w.icg_hp_fosc().bit(en));
192}
193
194// XTAL32K_CLK
195
196#[cfg(use_xtal32k)]
197fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) {
198    LP_CLKRST::regs()
199        .clk_to_hp()
200        .modify(|_, w| w.icg_hp_xtal32k().bit(en));
201}
202
203// OSC_SLOW_CLK
204
205fn enable_osc_slow_clk_impl(_clocks: &mut ClockTree, en: bool) {
206    LP_CLKRST::regs()
207        .clk_to_hp()
208        .modify(|_, w| w.icg_hp_osc32k().bit(en));
209}
210
211// RC_SLOW_CLK
212
213fn enable_rc_slow_clk_impl(_clocks: &mut ClockTree, en: bool) {
214    LP_CLKRST::regs()
215        .clk_to_hp()
216        .modify(|_, w| w.icg_hp_sosc().bit(en));
217}
218
219// PLL_F20M
220
221fn enable_pll_f20m_impl(_clocks: &mut ClockTree, en: bool) {
222    PCR::regs()
223        .pll_div_clk_en()
224        .modify(|_, w| w.pll_20m_clk_en().bit(en));
225}
226
227// PLL_F40M
228
229fn enable_pll_f40m_impl(_clocks: &mut ClockTree, en: bool) {
230    PCR::regs()
231        .pll_div_clk_en()
232        .modify(|_, w| w.pll_40m_clk_en().bit(en));
233}
234
235// PLL_F48M
236
237fn enable_pll_f48m_impl(_clocks: &mut ClockTree, en: bool) {
238    PCR::regs()
239        .pll_div_clk_en()
240        .modify(|_, w| w.pll_48m_clk_en().bit(en));
241}
242
243// PLL_F60M
244
245fn enable_pll_f60m_impl(_clocks: &mut ClockTree, en: bool) {
246    PCR::regs()
247        .pll_div_clk_en()
248        .modify(|_, w| w.pll_60m_clk_en().bit(en));
249}
250
251// PLL_F80M
252
253fn enable_pll_f80m_impl(_clocks: &mut ClockTree, en: bool) {
254    PCR::regs()
255        .pll_div_clk_en()
256        .modify(|_, w| w.pll_80m_clk_en().bit(en));
257}
258
259// PLL_F120M
260
261fn enable_pll_f120m_impl(_clocks: &mut ClockTree, en: bool) {
262    PCR::regs()
263        .pll_div_clk_en()
264        .modify(|_, w| w.pll_120m_clk_en().bit(en));
265}
266
267// PLL_F160M
268
269fn enable_pll_f160m_impl(_clocks: &mut ClockTree, en: bool) {
270    PCR::regs()
271        .pll_div_clk_en()
272        .modify(|_, w| w.pll_160m_clk_en().bit(en));
273}
274
275// HP_ROOT_CLK
276
277fn enable_hp_root_clk_impl(_clocks: &mut ClockTree, _en: bool) {
278    // Nothing to do here.
279}
280
281fn configure_hp_root_clk_impl(
282    _clocks: &mut ClockTree,
283    _old_config: Option<HpRootClkConfig>,
284    new_config: HpRootClkConfig,
285) {
286    // TODO: Limit AHB to ensure it's running at <= XTAL_CLK && CPU_CLK must be an integer multiple
287    // of AHB
288    PCR::regs().sysclk_conf().modify(|_, w| unsafe {
289        w.soc_clk_sel().bits(match new_config {
290            HpRootClkConfig::Xtal => 0,
291            HpRootClkConfig::RcFast => 1,
292            HpRootClkConfig::PllF160m => 2,
293        })
294    });
295
296    update_bus_clocks();
297}
298
299// Idle frequency scaling. These functions write the registers, but do not change the
300// configuration that the clock tree stores.
301//
302// One bus clock update applies the root clock and both dividers together, so that CPU_CLK stays
303// an integer multiple of AHB_CLK, and AHB_CLK does not exceed XTAL_CLK.
304
305/// Switches the CPU clock to XTAL_CLK if it comes from the PLL, with configured dividers that
306/// [`restore_cpu_clock`] can restore. Returns whether the clock changed.
307#[cfg(idle_frequency_scaling)]
308pub(crate) fn switch_cpu_clock_to_xtal(clocks: &mut ClockTree) -> bool {
309    if clocks.hp_root_clk() != Some(HpRootClkConfig::PllF160m)
310        || clocks.cpu_clk().is_none()
311        || clocks.ahb_clk().is_none()
312    {
313        return false;
314    }
315    with_single_bus_clock_update(|| {
316        configure_hp_root_clk_impl(clocks, None, HpRootClkConfig::Xtal);
317        configure_cpu_clk_impl(clocks, None, CpuClkConfig::new(0));
318        configure_ahb_clk_impl(clocks, None, AhbClkConfig::new(0));
319    });
320    true
321}
322
323/// Restores the CPU clock that the clock tree configures.
324#[cfg(idle_frequency_scaling)]
325pub(crate) fn restore_cpu_clock(clocks: &mut ClockTree) {
326    with_single_bus_clock_update(|| {
327        configure_ahb_clk_impl(clocks, None, unwrap!(clocks.ahb_clk()));
328        configure_cpu_clk_impl(clocks, None, unwrap!(clocks.cpu_clk()));
329        configure_hp_root_clk_impl(clocks, None, unwrap!(clocks.hp_root_clk()));
330    });
331}
332
333// CPU_CLK
334
335fn configure_cpu_clk_impl(
336    _clocks: &mut ClockTree,
337    _old_config: Option<CpuClkConfig>,
338    new_config: CpuClkConfig,
339) {
340    PCR::regs()
341        .cpu_freq_conf()
342        .modify(|_, w| unsafe { w.cpu_div_num().bits(new_config.divisor() as u8) });
343
344    update_bus_clocks();
345}
346
347// AHB_CLK
348
349fn configure_ahb_clk_impl(
350    _clocks: &mut ClockTree,
351    _old_config: Option<AhbClkConfig>,
352    new_config: AhbClkConfig,
353) {
354    PCR::regs()
355        .ahb_freq_conf()
356        .modify(|_, w| unsafe { w.ahb_div_num().bits(new_config.divisor() as u8) });
357
358    update_bus_clocks();
359}
360
361// APB_CLK
362
363fn enable_apb_clk_impl(_clocks: &mut ClockTree, en: bool) {
364    crate::soc::enable_apb_frequency_reduction(!en);
365}
366
367fn configure_apb_clk_impl(
368    _clocks: &mut ClockTree,
369    old_config: Option<ApbClkConfig>,
370    new_config: ApbClkConfig,
371) {
372    PCR::regs()
373        .apb_freq_conf()
374        .modify(|_, w| unsafe { w.apb_div_num().bits(new_config.divisor() as u8) });
375
376    // No driver uses APB_CLK before the first configuration.
377    if old_config.is_none() {
378        crate::soc::enable_apb_frequency_reduction(true);
379    }
380}
381
382// XTAL_D2_CLK
383
384fn enable_xtal_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) {
385    // Nothing to do here.
386}
387
388// LP_FAST_CLK
389
390fn enable_lp_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) {
391    // Nothing to do here.
392}
393
394fn configure_lp_fast_clk_impl(
395    _clocks: &mut ClockTree,
396    _old_config: Option<LpFastClkConfig>,
397    new_config: LpFastClkConfig,
398) {
399    LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe {
400        w.fast_clk_sel().bits(match new_config {
401            LpFastClkConfig::RcFast => 0,
402            LpFastClkConfig::XtalD2 => 1,
403            LpFastClkConfig::Xtal => 2,
404        })
405    });
406}
407
408// LP_SLOW_CLK
409
410fn enable_lp_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) {
411    // Nothing to do here.
412}
413
414fn configure_lp_slow_clk_impl(
415    _clocks: &mut ClockTree,
416    _old_config: Option<LpSlowClkConfig>,
417    new_config: LpSlowClkConfig,
418) {
419    LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe {
420        w.slow_clk_sel().bits(match new_config {
421            LpSlowClkConfig::RcSlow => 0,
422            #[cfg(use_xtal32k)]
423            LpSlowClkConfig::Xtal32k => 1,
424            // LpSlowClkConfig::Ext32k => 2,
425            LpSlowClkConfig::OscSlow => 3,
426        })
427    });
428}
429
430// CRYPTO_PLL_DIV
431
432fn enable_crypto_pll_div_impl(_clocks: &mut ClockTree, _en: bool) {
433    // The divider is fixed in hardware, there is nothing to gate.
434}
435
436// CRYPTO_CLK
437
438fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) {
439    // Nothing to do here.
440}
441
442fn configure_crypto_clk_impl(
443    _clocks: &mut ClockTree,
444    _old_config: Option<CryptoClkConfig>,
445    new_config: CryptoClkConfig,
446) {
447    PCR::regs().sec_conf().modify(|_, w| unsafe {
448        w.sec_clk_sel().bits(match new_config {
449            CryptoClkConfig::Xtal => 0,
450            CryptoClkConfig::RcFast => 1,
451            CryptoClkConfig::PllF480m => 2,
452        })
453    });
454}
455
456// TIMG_CALIBRATION_CLOCK
457
458fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) {
459    // Nothing to do here.
460}
461
462fn configure_timg_calibration_clock_impl(
463    _clocks: &mut ClockTree,
464    _old_config: Option<TimgCalibrationClockConfig>,
465    new_config: TimgCalibrationClockConfig,
466) {
467    PCR::regs().ctrl_32k_conf().modify(|_, w| unsafe {
468        w._32k_sel().bits(match new_config {
469            TimgCalibrationClockConfig::OscSlowClk => 0,
470            #[cfg(use_xtal32k)]
471            TimgCalibrationClockConfig::Xtal32kClk => 1,
472            // TimgCalibrationClockConfig::Ext32kClk => 2,
473            TimgCalibrationClockConfig::RcSlowClk => 3,
474            TimgCalibrationClockConfig::RcFastDivClk => 4,
475        })
476    });
477}
478
479impl AdcInstance {
480    // ADC_FUNCTION_CLOCK
481
482    fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) {
483        PCR::regs()
484            .saradc_clkm_conf()
485            .modify(|_, w| w.saradc_clkm_en().bit(en));
486    }
487
488    fn configure_function_clock_impl(
489        self,
490        _clocks: &mut ClockTree,
491        _old_config: Option<AdcFunctionClockConfig>,
492        new_config: AdcFunctionClockConfig,
493    ) {
494        PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe {
495            w.saradc_clkm_sel().bits(match new_config {
496                AdcFunctionClockConfig::Xtal => 0,
497                AdcFunctionClockConfig::RcFast => 1,
498                AdcFunctionClockConfig::PllF80m => 2,
499            })
500        });
501    }
502}
503
504impl TimgInstance {
505    // TIMG_FUNCTION_CLOCK
506
507    // TIMG0_FUNCTION_CLOCK
508
509    fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) {
510        let timg = match self {
511            TimgInstance::Timg0 => 0,
512            TimgInstance::Timg1 => 1,
513        };
514        PCR::regs()
515            .timergroup(timg)
516            .timer_clk_conf()
517            .modify(|_, w| w.timer_clk_en().bit(en));
518    }
519
520    fn configure_function_clock_impl(
521        self,
522        _clocks: &mut ClockTree,
523        _old_config: Option<TimgFunctionClockConfig>,
524        new_config: TimgFunctionClockConfig,
525    ) {
526        // TODO: add variants to PAC
527        let timg = match self {
528            TimgInstance::Timg0 => 0,
529            TimgInstance::Timg1 => 1,
530        };
531        PCR::regs()
532            .timergroup(timg)
533            .timer_clk_conf()
534            .modify(|_, w| unsafe {
535                w.timer_clk_sel().bits(match new_config {
536                    TimgFunctionClockConfig::XtalClk => 0,
537                    TimgFunctionClockConfig::RcFastClk => 1,
538                    TimgFunctionClockConfig::PllF80m => 2,
539                })
540            });
541    }
542
543    // TIMG_WDT_CLOCK
544
545    fn enable_wdt_clock_impl(self, _clocks: &mut ClockTree, en: bool) {
546        let timg = match self {
547            TimgInstance::Timg0 => 0,
548            TimgInstance::Timg1 => 1,
549        };
550        PCR::regs()
551            .timergroup(timg)
552            .wdt_clk_conf()
553            .modify(|_, w| w.wdt_clk_en().bit(en));
554    }
555
556    fn configure_wdt_clock_impl(
557        self,
558        _clocks: &mut ClockTree,
559        _old_config: Option<TimgWdtClockConfig>,
560        new_config: TimgWdtClockConfig,
561    ) {
562        let timg = match self {
563            TimgInstance::Timg0 => 0,
564            TimgInstance::Timg1 => 1,
565        };
566        PCR::regs()
567            .timergroup(timg)
568            .wdt_clk_conf()
569            .modify(|_, w| unsafe {
570                w.wdt_clk_sel().bits(match new_config {
571                    TimgWdtClockConfig::XtalClk => 0,
572                    TimgWdtClockConfig::RcFastClk => 1,
573                    TimgWdtClockConfig::PllF80m => 2,
574                })
575            });
576    }
577}
578
579// BLE_LP_XTAL_CLK
580
581fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) {
582    // Nothing to do.
583}
584
585// BLE_LP_RC_SLOW_CLK
586
587fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) {
588    // Nothing to do, divisor and gate are configured in BLE_LP_CLK
589    // (see modem_clock_select_lp_clock_source() in modem_clock.c).
590}
591
592// BLE_LP_CLK
593
594fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, en: bool) {
595    MODEM_LPCON::regs()
596        .clk_conf()
597        .modify(|_, w| w.clk_lp_timer_en().bit(en));
598}
599
600fn configure_ble_lp_clk_impl(
601    _clocks: &mut ClockTree,
602    _old_config: Option<BleLpClkConfig>,
603    new_config: BleLpClkConfig,
604) {
605    let divisor = match new_config {
606        BleLpClkConfig::Xtal => xtal_clk_frequency() / ble_lp_xtal_clk_frequency() - 1,
607        // Divided by 5 (div_num = 4), see esp_bt_rtc_slow_clk_select() in esp32c6/bt.c.
608        BleLpClkConfig::RcSlow => rc_slow_clk_frequency() / ble_lp_rc_slow_clk_frequency() - 1,
609        #[cfg(use_xtal32k)]
610        BleLpClkConfig::Xtal32k => 0,
611    };
612    let sel_xtal32k = cfg_select! {
613        use_xtal32k => new_config == BleLpClkConfig::Xtal32k,
614        _ => false,
615    };
616
617    MODEM_LPCON::regs()
618        .test_conf()
619        .modify(|_, w| w.clk_en().set_bit());
620
621    MODEM_LPCON::regs().lp_timer_conf().modify(|_, w| unsafe {
622        w.clk_lp_timer_sel_osc_slow()
623            .bit(new_config == BleLpClkConfig::RcSlow);
624        w.clk_lp_timer_sel_osc_fast().clear_bit();
625        w.clk_lp_timer_sel_xtal()
626            .bit(new_config == BleLpClkConfig::Xtal);
627        w.clk_lp_timer_sel_xtal32k().bit(sel_xtal32k);
628        w.clk_lp_timer_div_num().bits(divisor as u16)
629    });
630
631    if sel_xtal32k {
632        // 0 routes XTAL32K to the modem 32 kHz input.
633        MODEM_LPCON::regs()
634            .modem_32k_clk_conf()
635            .modify(|_, w| unsafe { w.clk_modem_32k_sel().bits(0) });
636    }
637}