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::MUL6,
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#[allow(unused_variables)]
215pub(crate) unsafe fn init(config: Config) {
216    // Configure HSI
217    while !RCC.ctlr().read().hsirdy() {}
218    let hsi = Some(HSI_FREQUENCY);
219
220    // Configure HSE
221    let hse = match config.hse {
222        None => {
223            RCC.ctlr().modify(|w| w.set_hseon(false));
224            None
225        }
226        Some(hse) => {
227            RCC.ctlr().modify(|w| w.set_hsebyp(hse.mode != super::HseMode::Oscillator));
228            RCC.ctlr().modify(|w| w.set_hseon(true));
229            while !RCC.ctlr().read().hserdy() {}
230            Some(hse.freq)
231        }
232    };
233
234    // Configure PLLs.
235    //
236    // TODO: Configure PLL2 and PLL3
237    #[cfg(d8c)]
238    let (pll2_clk, pll3_clk): (Option<Hertz>, Option<Hertz>) = if let Some(_pllx) = config.pllx {
239        todo!()
240    } else {
241        (None, None)
242    };
243    // Configure PLL
244    let pll_clk = {
245        // Disable PLL
246        RCC.ctlr().modify(|w| w.set_pllon(false));
247        if let Some(pll) = config.pll {
248            let pll_src = match config.pll_src {
249                PllSource::HSI => hsi.unwrap(),
250                PllSource::HSE => hse.unwrap(),
251                #[cfg(d8c)]
252                PllSource::PLL2 => todo!(),
253            };
254            let in_freq = pll_src / pll.prediv;
255            let vco_freq = in_freq * pll.mul;
256
257            // Usb clock must be 48MHz
258            let usb_pre = calc_usbpre(vco_freq);
259            if let Some(usb_pre) = usb_pre {
260                RCC.cfgr0().modify(|w| w.set_usbpre(usb_pre));
261            }
262            // TODO: handle USBHS clk
263
264            RCC.cfgr0().modify(|w| w.set_pllmul(pll.mul));
265
266            match config.pll_src {
267                PllSource::HSI => {
268                    RCC.cfgr0().modify(|w| w.set_pllsrc(false)); // use HSI or HSI/2
269                    match pll.prediv {
270                        PllPreDiv::DIV1 => EXTEND.ctr().modify(|w| w.set_pll_hsi_pre(true)), // set no divided
271                        PllPreDiv::DIV2 => EXTEND.ctr().modify(|w| w.set_pll_hsi_pre(false)),
272                        _ => panic!(
273                            "If HSI is selected as the PLL source (PLLSRC), only dividers DIV1 and DIV2 are available"
274                        ),
275                    }
276                }
277                #[cfg(d8c)]
278                PllSource::HSE => {
279                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
280                    RCC.cfgr2().modify(|w| {
281                        w.set_prediv1src(false); // HSE
282                        w.set_prediv1(pll.prediv);
283                    });
284                }
285                #[cfg(d8c)]
286                PllSource::PLL2 => {
287                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
288                    RCC.cfgr2().modify(|w| {
289                        w.set_prediv1src(true); // PLL2
290                        w.set_prediv1(pll.prediv);
291                    });
292                }
293                // FV203/V303
294                #[cfg(any(d6, d8))]
295                PllSource::HSE => {
296                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
297                    match pll.prediv {
298                        PllPreDiv::DIV1 => RCC.cfgr0().modify(|w| w.set_pllxtpre(false)),
299                        PllPreDiv::DIV2 => RCC.cfgr0().modify(|w| w.set_pllxtpre(true)),
300                        _ => panic!(),
301                    }
302                }
303                // CH32V20x_D8
304                #[cfg(all(ch32v2, d8))]
305                PllSource::HSE => {
306                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
307                    match pll.prediv {
308                        PllPreDiv::DIV4 => RCC.cfgr0().modify(|w| w.set_pllxtpre(false)),
309                        PllPreDiv::DIV8 => RCC.cfgr0().modify(|w| w.set_pllxtpre(true)),
310                        _ => panic!(),
311                    }
312                }
313                // CH32F20x_D8W、、CH32V20x_D8W
314                #[cfg(d8w)]
315                PllSource::HSE => {
316                    RCC.cfgr0().modify(|w| w.set_pllsrc(true));
317                    match pll.prediv {
318                        // When using USB and ETH together, the HSE frequency must be 32MHz
319                        PllPreDiv::DIV2 if usb_pre == Some(Usbpre::DIV5) => {}
320                        PllPreDiv::DIV4 => RCC.cfgr0().modify(|w| w.set_pllxtpre(false)),
321                        PllPreDiv::DIV8 => RCC.cfgr0().modify(|w| w.set_pllxtpre(true)),
322                        _ => panic!(),
323                    }
324                }
325            }
326
327            // Enable PLL
328            RCC.ctlr().modify(|w| w.set_pllon(true));
329            while !RCC.ctlr().read().pllrdy() {}
330
331            Some(vco_freq)
332        } else {
333            None
334        }
335    };
336
337    // Configure HSPLL for USBHS
338
339    #[cfg(d8c)]
340    if let Some(hspll) = config.hspll {
341        // Disable HSPLL
342        RCC.cfgr2().modify(|w| w.set_usbhs_pllalive(false));
343        let hspll_src = match config.hspll_src {
344            HsPllSource::HSI => hsi.unwrap(),
345            HsPllSource::HSE => hse.unwrap(),
346        };
347        let in_freq = hspll_src / hspll.pre;
348        let ref_clk = match in_freq {
349            Hertz(3_000_000) => HsPllRef::_3M,
350            Hertz(4_000_000) => HsPllRef::_4M,
351            Hertz(8_000_000) => HsPllRef::_8M,
352            Hertz(5_000_000) => HsPllRef::_5M,
353            _ => panic!(),
354        };
355
356        RCC.cfgr2().modify(|w| {
357            w.set_usbhs_prediy(hspll.pre as u8);
358            w.set_usbhs_ckpef_sel(ref_clk as u8);
359            w.set_usbhs_pll_src(if config.hspll_src == HsPllSource::HSI {
360                true
361            } else {
362                false
363            });
364            w.set_usbhs_clk_src(true);
365        });
366        RCC.cfgr2().modify(|w| w.set_usbhs_pllalive(true));
367    };
368
369    // Configure sysclk
370    let sys = match config.sys {
371        Sysclk::HSI => hsi.unwrap(),
372        Sysclk::HSE => hse.unwrap(),
373        Sysclk::PLL => pll_clk.unwrap(),
374        _ => unreachable!(),
375    };
376    let hclk = sys / config.ahb_pre;
377    let (pclk1, pclk1_tim) = calc_pclk(hclk, config.apb1_pre);
378    let (pclk2, pclk2_tim) = calc_pclk(hclk, config.apb2_pre);
379
380    // 当 AHB 时钟来源的预分频系数大于 1 时,必须开启预取缓冲器
381
382    FLASH.ctlr().modify(|w| {
383        w.set_sckmode(sys.0 <= 72_000_000);
384        w.set_enhancemode(true);
385    });
386
387    RCC.cfgr0().modify(|w| {
388        w.set_sw(config.sys);
389        w.set_hpre(config.ahb_pre);
390        w.set_ppre1(config.apb1_pre);
391        w.set_ppre2(config.apb2_pre);
392    });
393    while RCC.cfgr0().read().sws() != config.sys {}
394
395    refresh_clocks(config.hse.map(|h| h.freq));
396}
397
398pub(crate) unsafe fn refresh_clocks(hse: Option<Hertz>) {
399    super::set_clocks(clocks_from_registers(hse));
400}
401
402fn clocks_from_registers(hse: Option<Hertz>) -> super::Clocks {
403    let cfgr = RCC.cfgr0().read();
404    let sys = sysclk_hz(cfgr.sws(), hse);
405    let hclk = sys / cfgr.hpre();
406    let (pclk1, pclk1_tim) = calc_pclk(hclk, cfgr.ppre1());
407    let (pclk2, pclk2_tim) = calc_pclk(hclk, cfgr.ppre2());
408    super::Clocks {
409        sysclk: sys,
410        hclk,
411        pclk1,
412        pclk2,
413        pclk1_tim,
414        pclk2_tim,
415    }
416}
417
418fn sysclk_hz(sw: Sysclk, hse: Option<Hertz>) -> Hertz {
419    let cfgr = RCC.cfgr0().read();
420    match sw {
421        Sysclk::HSI => HSI_FREQUENCY,
422        Sysclk::HSE => hse.expect("RCC: HSE frequency required"),
423        Sysclk::PLL => {
424            let pll_src = if cfgr.pllsrc() {
425                PllSource::HSE
426            } else {
427                PllSource::HSI
428            };
429            let input = match pll_src {
430                PllSource::HSI => {
431                    if EXTEND.ctr().read().pll_hsi_pre() {
432                        HSI_FREQUENCY
433                    } else {
434                        HSI_FREQUENCY / 2u32
435                    }
436                }
437                PllSource::HSE => {
438                    let hse = hse.expect("RCC: HSE frequency required");
439                    #[cfg(d8c)]
440                    {
441                        let pre = RCC.cfgr2().read().prediv1();
442                        hse / pre
443                    }
444                    #[cfg(any(d6, d8))]
445                    {
446                        if cfgr.pllxtpre() {
447                            hse / 2u32
448                        } else {
449                            hse
450                        }
451                    }
452                    #[cfg(all(ch32v2, d8))]
453                    {
454                        if cfgr.pllxtpre() {
455                            hse / 8u32
456                        } else {
457                            hse / 4u32
458                        }
459                    }
460                    #[cfg(d8w)]
461                    {
462                        if cfgr.pllxtpre() {
463                            hse / 8u32
464                        } else {
465                            hse / 4u32
466                        }
467                    }
468                }
469                #[cfg(d8c)]
470                PllSource::PLL2 => todo!("PLL2 clock measure"),
471            };
472            input * cfgr.pllmul()
473        }
474        _ => HSI_FREQUENCY,
475    }
476}
477
478fn calc_pclk<D>(hclk: Hertz, ppre: D) -> (Hertz, Hertz)
479where
480    Hertz: ops::Div<D, Output = Hertz>,
481{
482    let pclk = hclk / ppre;
483    let pclk_tim = super::apb_timer_clk(hclk, pclk, true);
484    (pclk, pclk_tim)
485}
486
487fn calc_usbpre(pllclk: Hertz) -> Option<Usbpre> {
488    // output 48MHz
489    match pllclk.0 {
490        48_000_000 => Some(Usbpre::DIV1),
491        96_000_000 => Some(Usbpre::DIV2),
492        144_000_000 => Some(Usbpre::DIV3),
493        #[cfg(d8w)]
494        240_000_000 => Some(Usbpre::DIV5),
495        _ => None,
496    }
497}
498
499impl ops::Div<PllPreDiv> for Hertz {
500    type Output = Hertz;
501    fn div(self, rhs: PllPreDiv) -> Hertz {
502        Hertz(self.0 / (rhs as u32 + 1))
503    }
504}
505
506impl ops::Mul<PllMul> for Hertz {
507    type Output = Hertz;
508    fn mul(self, rhs: PllMul) -> Hertz {
509        match rhs {
510            PllMul::MUL15 => Hertz(self.0 * 15),
511            PllMul::MUL16 => Hertz(self.0 * 16),
512            PllMul::MUL18 => Hertz(self.0 * 18),
513            #[cfg(d8c)]
514            PllMul::MUL6_5 => Hertz(self.0 * 13 / 2),
515            // All the others are covered by this case
516            _ => Hertz(self.0 * (rhs as u32 + 2)),
517        }
518    }
519}
520
521impl ops::Div<AHBPrescaler> for Hertz {
522    type Output = Hertz;
523    fn div(self, rhs: AHBPrescaler) -> Hertz {
524        let raw = rhs as u32;
525        if raw >= 0b1000 {
526            // 2, 4, 8
527            let d = raw - 0b1000 + 1;
528            Hertz(self.0 >> d)
529        } else {
530            // DIV1
531            self
532        }
533    }
534}
535
536impl ops::Div<APBPrescaler> for Hertz {
537    type Output = Hertz;
538    fn div(self, rhs: APBPrescaler) -> Hertz {
539        let raw = rhs as u32;
540        if raw >= 0b100 {
541            // 2, 4, 8, 16
542            let d = raw - 0b100 + 1;
543            Hertz(self.0 >> d)
544        } else {
545            // DIV1
546            self
547        }
548    }
549}