Skip to main content

ch32_hal/rcc/
v3.rs

1//! CH32V2, CH32V3
2use core::ops::{self, Div};
3
4pub use crate::pac::rcc::vals::{
5    Hpre as AHBPrescaler, PllMul, PllxMul, Ppre as APBPrescaler, Prediv as PllPreDiv, Sw as Sysclk, Usbpre,
6};
7use crate::pac::{EXTEND, FLASH, RCC};
8use crate::time::Hertz;
9
10pub const HSI_FREQUENCY: Hertz = Hertz(8_000_000);
11
12#[derive(Clone, Copy)]
13pub struct Pll {
14    /// PLL pre-divider
15    pub prediv: PllPreDiv,
16
17    /// PLL multiplication factor.
18    pub mul: PllMul,
19}
20
21// PLLSRC, the div ratio is set in Pll.prediv
22#[derive(Clone, Copy, PartialEq)]
23pub enum PllSource {
24    /// HSI or HSI div 2
25    HSI,
26    // HSE or HSE div (2 or Prediv)
27    HSE,
28
29    // PLL2 or not, selected by PREDIV1SRC
30    #[cfg(d8c)]
31    PLL2,
32}
33
34pub struct Pllx {
35    pub prediv2: PllPreDiv,
36    pub pll2: Option<PllxMul>,
37    pub pll3: Option<PllxMul>,
38}
39
40#[derive(Clone, Copy, PartialEq)]
41// USBHSPLLSRC bits in rcc_cfgr2
42pub enum HsPllSource {
43    HSI,
44    HSE,
45}
46
47// TODO: should be in PAC
48// USBHSDIV bits in rcc_cfgr2
49#[derive(Clone, Copy, PartialEq)]
50pub enum HsPllPrescaler {
51    DIV1 = 0b000,
52    DIV2 = 0b001,
53    DIV3 = 0b010,
54    DIV4 = 0b011,
55    DIV5 = 0b100,
56    DIV6 = 0b101,
57    DIV7 = 0b110,
58    DIV8 = 0b111,
59}
60
61impl Div<HsPllPrescaler> for Hertz {
62    type Output = Hertz;
63    fn div(self, rhs: HsPllPrescaler) -> Hertz {
64        Hertz(self.0 / (rhs as u32 + 1))
65    }
66}
67
68#[derive(Clone, Copy, PartialEq)]
69pub enum HsPllRef {
70    _3M = 0b00,
71    _4M = 0b01,
72    _8M = 0b10,
73    _5M = 0b11,
74}
75
76#[derive(Clone, Copy)]
77pub struct HsPll {
78    pub pre: HsPllPrescaler,
79}
80
81pub struct Config {
82    // won't close hsi
83    // pub hsi: bool,
84    pub hse: Option<super::Hse>,
85    pub sys: Sysclk,
86
87    pub pll_src: PllSource,
88    pub pll: Option<Pll>,
89
90    // TODO: optional
91    pub pllx: Option<Pllx>,
92
93    pub ahb_pre: AHBPrescaler,
94    pub apb1_pre: APBPrescaler,
95    pub apb2_pre: APBPrescaler,
96
97    pub ls: super::LsConfig,
98
99    pub hspll_src: HsPllSource,
100    pub hspll: Option<HsPll>,
101    // /// Per-peripheral kernel clock selection muxes
102    // pub mux: super::mux::ClockMux,
103}
104
105impl Config {
106    pub const SYSCLK_FREQ_96MHZ_HSE: Config = {
107        Config {
108            hse: Some(super::Hse {
109                freq: Hertz(8_000_000),
110                mode: super::HseMode::Oscillator,
111            }),
112            sys: Sysclk::PLL,
113            pll_src: PllSource::HSE,
114            pll: Some(Pll {
115                prediv: PllPreDiv::DIV1,
116                mul: PllMul::MUL12,
117            }),
118
119            pllx: None,
120            ahb_pre: AHBPrescaler::DIV1,
121            apb1_pre: APBPrescaler::DIV1,
122            apb2_pre: APBPrescaler::DIV1,
123            ls: super::LsConfig::default_lsi(),
124            hspll_src: HsPllSource::HSE,
125            hspll: Some(HsPll {
126                pre: HsPllPrescaler::DIV2,
127            }),
128        }
129    };
130    pub const SYSCLK_FREQ_144MHZ_HSE: Config = {
131        Config {
132            hse: Some(super::Hse {
133                freq: Hertz(8_000_000),
134                mode: super::HseMode::Oscillator,
135            }),
136            sys: Sysclk::PLL,
137            pll_src: PllSource::HSE,
138            pll: Some(Pll {
139                prediv: PllPreDiv::DIV1,
140                mul: PllMul::MUL18,
141            }),
142            pllx: None,
143            ahb_pre: AHBPrescaler::DIV1,
144            apb1_pre: APBPrescaler::DIV1,
145            apb2_pre: APBPrescaler::DIV1,
146            ls: super::LsConfig::default_lsi(),
147            hspll_src: HsPllSource::HSE,
148            hspll: Some(HsPll {
149                pre: HsPllPrescaler::DIV2,
150            }),
151        }
152    };
153    pub const SYSCLK_FREQ_144MHZ_HSI: Config = {
154        Config {
155            hse: None,
156            sys: Sysclk::PLL,
157            pll_src: PllSource::HSI,
158            pll: Some(Pll {
159                prediv: PllPreDiv::DIV1,
160                mul: PllMul::MUL18,
161            }),
162            pllx: None,
163            ahb_pre: AHBPrescaler::DIV1,
164            apb1_pre: APBPrescaler::DIV1,
165            apb2_pre: APBPrescaler::DIV1,
166            ls: super::LsConfig::default_lsi(),
167            hspll_src: HsPllSource::HSI,
168            hspll: Some(HsPll {
169                pre: HsPllPrescaler::DIV2,
170            }),
171        }
172    };
173    pub const SYSCLK_FREQ_96MHZ_HSI: Config = {
174        Config {
175            hse: None,
176            sys: Sysclk::PLL,
177            pll_src: PllSource::HSI,
178            pll: Some(Pll {
179                prediv: PllPreDiv::DIV1,
180                mul: PllMul::MUL12,
181            }),
182            pllx: None,
183            ahb_pre: AHBPrescaler::DIV1,
184            apb1_pre: APBPrescaler::DIV4, // 24MHz
185            apb2_pre: APBPrescaler::DIV4,
186            ls: super::LsConfig::default_lsi(),
187            hspll_src: HsPllSource::HSI,
188            hspll: Some(HsPll {
189                pre: HsPllPrescaler::DIV2,
190            }),
191        }
192    };
193}
194
195impl Default for Config {
196    fn default() -> Self {
197        Self {
198            // hsi: true,
199            hse: None,
200            sys: Sysclk::HSI,
201            pll_src: PllSource::HSI,
202            pll: None,
203            pllx: None,
204            ahb_pre: AHBPrescaler::DIV1,
205            apb1_pre: APBPrescaler::DIV1,
206            apb2_pre: APBPrescaler::DIV1,
207            ls: super::LsConfig::default(),
208            hspll_src: HsPllSource::HSE,
209            hspll: None,
210        }
211    }
212}
213
214/// Polls a clock ready or switch flag, with the bound `rcc::v4x7` uses: a crystal that does not
215/// start, or an HSE mode that does not match the board, panics instead of hanging `init`.
216fn wait_for(mut ready: impl FnMut() -> bool) {
217    for _attempt in 0..1_000_000 {
218        if ready() {
219            return;
220        }
221    }
222    panic!("RCC: clock startup or switch timed out");
223}
224
225#[allow(unused_variables)]
226pub(crate) unsafe fn init(config: Config) {
227    // Configure HSI
228    wait_for(|| RCC.ctlr().read().hsirdy());
229
230    #[cfg(pwr_v3)]
231    super::ls::init_ls(&config.ls);
232    let hsi = Some(HSI_FREQUENCY);
233
234    // Configure HSE
235    let hse = match config.hse {
236        None => {
237            RCC.ctlr().modify(|w| w.set_hseon(false));
238            None
239        }
240        Some(hse) => {
241            RCC.ctlr().modify(|w| w.set_hsebyp(hse.mode != super::HseMode::Oscillator));
242            RCC.ctlr().modify(|w| w.set_hseon(true));
243            wait_for(|| RCC.ctlr().read().hserdy());
244            Some(hse.freq)
245        }
246    };
247
248    // Configure PLLs.
249    //
250    // TODO: Configure PLL2 and PLL3
251    #[cfg(d8c)]
252    let (pll2_clk, pll3_clk): (Option<Hertz>, Option<Hertz>) = if let Some(_pllx) = config.pllx {
253        todo!()
254    } else {
255        (None, None)
256    };
257    // Configure PLL
258    let pll_clk = {
259        // Disable PLL
260        RCC.ctlr().modify(|w| w.set_pllon(false));
261        if let Some(pll) = config.pll {
262            let pll_src = match config.pll_src {
263                PllSource::HSI => hsi.unwrap(),
264                PllSource::HSE => hse.unwrap(),
265                #[cfg(d8c)]
266                PllSource::PLL2 => todo!(),
267            };
268            let in_freq = pll_src / pll.prediv;
269            let vco_freq = in_freq * pll.mul;
270
271            // Usb clock must be 48MHz
272            let usb_pre = calc_usbpre(vco_freq);
273            if let Some(usb_pre) = usb_pre {
274                RCC.cfgr0().modify(|w| w.set_usbpre(usb_pre));
275            }
276            // TODO: handle USBHS clk
277
278            RCC.cfgr0().modify(|w| w.set_pllmul(pll.mul));
279
280            match config.pll_src {
281                PllSource::HSI => {
282                    RCC.cfgr0().modify(|w| w.set_pllsrc(false)); // use HSI or HSI/2
283                    match pll.prediv {
284                        PllPreDiv::DIV1 => EXTEND.ctr().modify(|w| w.set_pll_hsi_pre(true)), // set no divided
285                        PllPreDiv::DIV2 => EXTEND.ctr().modify(|w| w.set_pll_hsi_pre(false)),
286                        _ => panic!(
287                            "If HSI is selected as the PLL source (PLLSRC), only dividers DIV1 and DIV2 are available"
288                        ),
289                    }
290                }
291                #[cfg(d8c)]
292                PllSource::HSE => {
293                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
294                    RCC.cfgr2().modify(|w| {
295                        w.set_prediv1src(false); // HSE
296                        w.set_prediv1(pll.prediv);
297                    });
298                }
299                #[cfg(d8c)]
300                PllSource::PLL2 => {
301                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
302                    RCC.cfgr2().modify(|w| {
303                        w.set_prediv1src(true); // PLL2
304                        w.set_prediv1(pll.prediv);
305                    });
306                }
307                // FV203/V303
308                #[cfg(any(d6, all(d8, not(ch32v2))))]
309                PllSource::HSE => {
310                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
311                    match pll.prediv {
312                        PllPreDiv::DIV1 => RCC.cfgr0().modify(|w| w.set_pllxtpre(false)),
313                        PllPreDiv::DIV2 => RCC.cfgr0().modify(|w| w.set_pllxtpre(true)),
314                        _ => panic!(),
315                    }
316                }
317                // CH32V20x_D8
318                #[cfg(all(ch32v2, d8))]
319                PllSource::HSE => {
320                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
321                    match pll.prediv {
322                        PllPreDiv::DIV4 => RCC.cfgr0().modify(|w| w.set_pllxtpre(false)),
323                        PllPreDiv::DIV8 => RCC.cfgr0().modify(|w| w.set_pllxtpre(true)),
324                        _ => panic!(),
325                    }
326                }
327                // CH32F20x_D8W、、CH32V20x_D8W
328                #[cfg(d8w)]
329                PllSource::HSE => {
330                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
331                    match pll.prediv {
332                        // When using USB and ETH together, the HSE frequency must be 32MHz
333                        PllPreDiv::DIV2 if usb_pre == Some(Usbpre::DIV5) => {}
334                        PllPreDiv::DIV4 => RCC.cfgr0().modify(|w| w.set_pllxtpre(false)),
335                        PllPreDiv::DIV8 => RCC.cfgr0().modify(|w| w.set_pllxtpre(true)),
336                        _ => panic!(),
337                    }
338                }
339            }
340
341            // Enable PLL
342            RCC.ctlr().modify(|w| w.set_pllon(true));
343            wait_for(|| RCC.ctlr().read().pllrdy());
344
345            Some(vco_freq)
346        } else {
347            None
348        }
349    };
350
351    // Configure HSPLL for USBHS
352
353    #[cfg(d8c)]
354    if let Some(hspll) = config.hspll {
355        // Disable HSPLL
356        RCC.cfgr2().modify(|w| w.set_usbhs_pllalive(false));
357        let hspll_src = match config.hspll_src {
358            HsPllSource::HSI => hsi.unwrap(),
359            HsPllSource::HSE => hse.unwrap(),
360        };
361        let in_freq = hspll_src / hspll.pre;
362        let ref_clk = match in_freq {
363            Hertz(3_000_000) => HsPllRef::_3M,
364            Hertz(4_000_000) => HsPllRef::_4M,
365            Hertz(8_000_000) => HsPllRef::_8M,
366            Hertz(5_000_000) => HsPllRef::_5M,
367            _ => panic!(),
368        };
369
370        RCC.cfgr2().modify(|w| {
371            w.set_usbhs_prediy(hspll.pre as u8);
372            w.set_usbhs_ckpef_sel(ref_clk as u8);
373            w.set_usbhs_pll_src(if config.hspll_src == HsPllSource::HSI {
374                true
375            } else {
376                false
377            });
378            w.set_usbhs_clk_src(true);
379        });
380        RCC.cfgr2().modify(|w| w.set_usbhs_pllalive(true));
381    };
382
383    // Configure sysclk
384    let sys = match config.sys {
385        Sysclk::HSI => hsi.unwrap(),
386        Sysclk::HSE => hse.unwrap(),
387        Sysclk::PLL => pll_clk.unwrap(),
388        _ => unreachable!(),
389    };
390    let hclk = sys / config.ahb_pre;
391    let (pclk1, pclk1_tim) = calc_pclk(hclk, config.apb1_pre);
392    let (pclk2, pclk2_tim) = calc_pclk(hclk, config.apb2_pre);
393
394    // 当 AHB 时钟来源的预分频系数大于 1 时,必须开启预取缓冲器
395
396    FLASH.ctlr().modify(|w| {
397        w.set_sckmode(sys.0 <= 72_000_000);
398        w.set_enhancemode(true);
399    });
400
401    RCC.cfgr0().modify(|w| {
402        w.set_sw(config.sys);
403        w.set_hpre(config.ahb_pre);
404        w.set_ppre1(config.apb1_pre);
405        w.set_ppre2(config.apb2_pre);
406    });
407    wait_for(|| RCC.cfgr0().read().sws() == config.sys);
408
409    refresh_clocks(config.hse.map(|h| h.freq));
410}
411
412pub(crate) unsafe fn refresh_clocks(hse: Option<Hertz>) {
413    super::set_clocks(clocks_from_registers(hse));
414}
415
416fn clocks_from_registers(hse: Option<Hertz>) -> super::Clocks {
417    let cfgr = RCC.cfgr0().read();
418    let sys = sysclk_hz(cfgr.sws(), hse);
419    let hclk = sys / cfgr.hpre();
420    let (pclk1, pclk1_tim) = calc_pclk(hclk, cfgr.ppre1());
421    let (pclk2, pclk2_tim) = calc_pclk(hclk, cfgr.ppre2());
422    super::Clocks {
423        sysclk: sys,
424        hclk,
425        pclk1,
426        pclk2,
427        pclk1_tim,
428        pclk2_tim,
429    }
430}
431
432fn sysclk_hz(sw: Sysclk, hse: Option<Hertz>) -> Hertz {
433    let cfgr = RCC.cfgr0().read();
434    match sw {
435        Sysclk::HSI => HSI_FREQUENCY,
436        Sysclk::HSE => hse.expect("RCC: HSE frequency required"),
437        Sysclk::PLL => {
438            let pll_src = if cfgr.pllsrc() {
439                PllSource::HSE
440            } else {
441                PllSource::HSI
442            };
443            let input = match pll_src {
444                PllSource::HSI => {
445                    if EXTEND.ctr().read().pll_hsi_pre() {
446                        HSI_FREQUENCY
447                    } else {
448                        HSI_FREQUENCY / 2u32
449                    }
450                }
451                PllSource::HSE => {
452                    let hse = hse.expect("RCC: HSE frequency required");
453                    #[cfg(d8c)]
454                    {
455                        let pre = RCC.cfgr2().read().prediv1();
456                        hse / pre
457                    }
458                    #[cfg(any(d6, all(d8, not(ch32v2))))]
459                    {
460                        if cfgr.pllxtpre() {
461                            hse / 2u32
462                        } else {
463                            hse
464                        }
465                    }
466                    #[cfg(all(ch32v2, d8))]
467                    {
468                        if cfgr.pllxtpre() {
469                            hse / 8u32
470                        } else {
471                            hse / 4u32
472                        }
473                    }
474                    #[cfg(d8w)]
475                    {
476                        // USBPRE = 0b11, set for a 240 MHz PLL, also feeds the PLL with HSE/2.
477                        if cfgr.usbpre() == Usbpre::DIV5 {
478                            hse / 2u32
479                        } else if cfgr.pllxtpre() {
480                            hse / 8u32
481                        } else {
482                            hse / 4u32
483                        }
484                    }
485                }
486                #[cfg(d8c)]
487                PllSource::PLL2 => todo!("PLL2 clock measure"),
488            };
489            input * cfgr.pllmul()
490        }
491        _ => HSI_FREQUENCY,
492    }
493}
494
495fn calc_pclk<D>(hclk: Hertz, ppre: D) -> (Hertz, Hertz)
496where
497    Hertz: ops::Div<D, Output = Hertz>,
498{
499    let pclk = hclk / ppre;
500    let pclk_tim = super::apb_timer_clk(hclk, pclk, true);
501    (pclk, pclk_tim)
502}
503
504fn calc_usbpre(pllclk: Hertz) -> Option<Usbpre> {
505    // output 48MHz
506    match pllclk.0 {
507        48_000_000 => Some(Usbpre::DIV1),
508        96_000_000 => Some(Usbpre::DIV2),
509        144_000_000 => Some(Usbpre::DIV3),
510        #[cfg(d8w)]
511        240_000_000 => Some(Usbpre::DIV5),
512        _ => None,
513    }
514}
515
516impl ops::Div<PllPreDiv> for Hertz {
517    type Output = Hertz;
518    fn div(self, rhs: PllPreDiv) -> Hertz {
519        Hertz(self.0 / (rhs as u32 + 1))
520    }
521}
522
523impl ops::Mul<PllMul> for Hertz {
524    type Output = Hertz;
525    fn mul(self, rhs: PllMul) -> Hertz {
526        match rhs {
527            PllMul::MUL15 => Hertz(self.0 * 15),
528            PllMul::MUL16 => Hertz(self.0 * 16),
529            PllMul::MUL18 => Hertz(self.0 * 18),
530            #[cfg(d8c)]
531            PllMul::MUL6_5 => Hertz(self.0 * 13 / 2),
532            // All the others are covered by this case
533            _ => Hertz(self.0 * (rhs as u32 + 2)),
534        }
535    }
536}
537
538impl ops::Div<AHBPrescaler> for Hertz {
539    type Output = Hertz;
540    fn div(self, rhs: AHBPrescaler) -> Hertz {
541        match rhs {
542            AHBPrescaler::DIV1 => self,
543            AHBPrescaler::DIV2 => Hertz(self.0 >> 1),
544            AHBPrescaler::DIV4 => Hertz(self.0 >> 2),
545            AHBPrescaler::DIV8 => Hertz(self.0 >> 3),
546            AHBPrescaler::DIV16 => Hertz(self.0 >> 4),
547            AHBPrescaler::DIV64 => Hertz(self.0 >> 6),
548            AHBPrescaler::DIV128 => Hertz(self.0 >> 7),
549            AHBPrescaler::DIV256 => Hertz(self.0 >> 8),
550            AHBPrescaler::DIV512 => Hertz(self.0 >> 9),
551            _ => self,
552        }
553    }
554}
555
556impl ops::Div<APBPrescaler> for Hertz {
557    type Output = Hertz;
558    fn div(self, rhs: APBPrescaler) -> Hertz {
559        let raw = rhs as u32;
560        if raw >= 0b100 {
561            // 2, 4, 8, 16
562            let d = raw - 0b100 + 1;
563            Hertz(self.0 >> d)
564        } else {
565            // DIV1
566            self
567        }
568    }
569}