1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Reset and Clock Control
//!
//! The most important function this module
//! delivers is the clock configuration.
//!
//! To configure the clock, we first have to obtain the
//! device peripherals.
//!
//! ```
//! # use cortex_m_rt::entry;
//! # use stm32f3xx_hal::prelude::*;
//! # #[entry]
//! # fn main() -> ! {
//! // Get our peripherals
//! let dp = pac::Peripherals::take().unwrap();
//!
//! let mut flash = dp.FLASH.constrain();
//! let mut rcc = dp.RCC.constrain();
//! # }
//! ```
//!
//! After that we can configure the clock
//!
//! ```
//! # use cortex_m_rt::entry;
//! # use stm32f3xx_hal::prelude::*;
//! # #[entry]
//! # fn main() -> ! {
//! # let dp = pac::Peripherals::take().unwrap();
//!
//! # let mut flash = dp.FLASH.constrain();
//! # let mut rcc = dp.RCC.constrain();
//! let clocks = rcc.cfgr
//!     // Using the external oscillator
//!     // Set the frequency to that of the external oscillator
//!     .use_hse(8.mhz())
//!     // Set the frequency for the AHB bus,
//!     // which the root of every following clock peripheral
//!     .hclk(48.mhz())
//!     // The sysclk is equivalent to the core clock
//!     .sysclk(48.mhz())
//!     // The following are peripheral clocks, which are both
//!     // needed to configure specific peripherals.
//!     // Looking at the peripheral function parameters
//!     // should give more insight, which peripheral clock is needed.
//!     .pclk1(12.mhz())
//!     .pclk2(12.mhz())
//!     // Freeze / apply the configuration and setup all clocks
//!     .freeze(&mut flash.acr);
//! # }
//! ```
//!
//! All fields can be omitted and will internally be set to a calculated default.
//! For more details read the documentation of the [`CFGR`] methods to
//! find out how to setup the clock.

use crate::pac::{
    rcc::{self, cfgr, cfgr2},
    RCC,
};

use crate::flash::ACR;
use crate::time::Hertz;

/// Extension trait that constrains the `RCC` peripheral
pub trait RccExt {
    /// Constrains the `RCC` peripheral so it plays nicely with the other abstractions
    fn constrain(self) -> Rcc;
}

impl RccExt for RCC {
    fn constrain(self) -> Rcc {
        Rcc {
            ahb: AHB { _0: () },
            apb1: APB1 { _0: () },
            apb2: APB2 { _0: () },
            bdcr: BDCR { _0: () },
            cfgr: CFGR::default(),
        }
    }
}

/// Constrained RCC peripheral
///
/// An instance of this struct is acquired by calling the
/// [`constrain`](RccExt::constrain) function on the
/// [`RCC`](crate::pac::RCC) struct.
///
/// ```
/// let dp = pac::Peripherals::take().unwrap();
/// let rcc = dp.RCC.constrain();
/// ```
pub struct Rcc {
    /// AMBA High-performance Bus (AHB) registers
    pub ahb: AHB,
    /// Advanced Peripheral Bus 1 (APB1) registers
    pub apb1: APB1,
    /// Advanced Peripheral Bus 2 (APB2) registers
    pub apb2: APB2,
    /// RCC Backup Domain
    pub bdcr: BDCR,
    /// Clock configuration
    pub cfgr: CFGR,
}

/// AMBA High-performance Bus (AHB) registers
///
/// An instance of this struct is acquired from the [`RCC`](crate::pac::RCC) struct.
///
/// ```
/// let dp = pac::Peripherals::take().unwrap();
/// let rcc = dp.RCC.constrain();
/// use_ahb(&mut rcc.ahb)
/// ```
pub struct AHB {
    _0: (),
}

impl AHB {
    pub(crate) fn enr(&mut self) -> &rcc::AHBENR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).ahbenr }
    }

    pub(crate) fn rstr(&mut self) -> &rcc::AHBRSTR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).ahbrstr }
    }
}

/// Advanced Peripheral Bus 1 (APB1) registers
///
/// An instance of this struct is acquired from the [`RCC`](crate::pac::RCC) struct.
///
/// ```
/// let dp = pac::Peripherals::take().unwrap();
/// let rcc = dp.RCC.constrain();
/// use_apb1(&mut rcc.apb1)
/// ```
pub struct APB1 {
    _0: (),
}

impl APB1 {
    pub(crate) fn enr(&mut self) -> &rcc::APB1ENR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).apb1enr }
    }

    pub(crate) fn rstr(&mut self) -> &rcc::APB1RSTR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).apb1rstr }
    }
}

/// Advanced Peripheral Bus 2 (APB2) registers
///
/// An instance of this struct is acquired from the [`RCC`](crate::pac::RCC) struct.
///
/// ```
/// let dp = pac::Peripherals::take().unwrap();
/// let rcc = dp.RCC.constrain();
/// use_apb2(&mut rcc.apb2)
/// ```
pub struct APB2 {
    _0: (),
}

impl APB2 {
    pub(crate) fn enr(&mut self) -> &rcc::APB2ENR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).apb2enr }
    }

    pub(crate) fn rstr(&mut self) -> &rcc::APB2RSTR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).apb2rstr }
    }
}

const HSI: u32 = 8_000_000; // Hz

// some microcontrollers do not have USB
#[cfg(any(feature = "stm32f301", feature = "stm32f318", feature = "stm32f334",))]
mod usb_clocking {
    use crate::rcc::PllConfig;

    pub(crate) fn is_valid(
        _sysclk: u32,
        _hse: Option<u32>,
        _pclk1: u32,
        _pll_config: &Option<PllConfig>,
    ) -> (bool, bool) {
        (false, false)
    }

    pub(crate) fn set_usbpre<W>(w: &mut W, _: bool) -> &mut W {
        w
    }
}

#[cfg(not(any(feature = "stm32f301", feature = "stm32f318", feature = "stm32f334",)))]
mod usb_clocking {
    use crate::pac::rcc::cfgr;
    use crate::rcc::PllConfig;

    /// Check for all clock options to be
    pub(crate) fn is_valid(
        sysclk: u32,
        hse: Option<u32>,
        pclk1: u32,
        pll_config: &Option<PllConfig>,
    ) -> (cfgr::USBPRE_A, bool) {
        // the USB clock is only valid if an external crystal is used, the PLL is enabled, and the
        // PLL output frequency is a supported one.
        // usbpre == false: divide clock by 1.5, otherwise no division
        let usb_ok = hse.is_some() && pll_config.is_some();
        // The APB1 clock must have a minimum frequency of 10 MHz to avoid data overrun/underrun
        // problems. [RM0316 32.5.2]
        if pclk1 >= 10_000_000 {
            match (usb_ok, sysclk) {
                (true, 72_000_000) => (cfgr::USBPRE_A::DIV1_5, true),
                (true, 48_000_000) => (cfgr::USBPRE_A::DIV1, true),
                _ => (cfgr::USBPRE_A::DIV1, false),
            }
        } else {
            (cfgr::USBPRE_A::DIV1, false)
        }
    }

    pub(crate) fn set_usbpre(w: &mut cfgr::W, usb_prescale: cfgr::USBPRE_A) -> &mut cfgr::W {
        w.usbpre().variant(usb_prescale)
    }
}

/// Backup Domain Control register (RCC_BDCR)
pub struct BDCR {
    _0: (),
}

impl BDCR {
    pub(crate) fn bdcr(&mut self) -> &rcc::BDCR {
        // NOTE(unsafe) this proxy grants exclusive access to this register
        unsafe { &(*RCC::ptr()).bdcr }
    }
}

/// Clock configuration
///
/// An instance of this struct is acquired from the [`RCC`](crate::pac::RCC) struct.
///
/// ```
/// let dp = pac::Peripherals::take().unwrap();
/// let rcc = dp.RCC.constrain();
/// use_cfgr(&mut rcc.cfgr)
/// ```
#[derive(Default)]
pub struct CFGR {
    hse: Option<u32>,
    hse_bypass: bool,
    css: bool,
    hclk: Option<u32>,
    pclk1: Option<u32>,
    pclk2: Option<u32>,
    sysclk: Option<u32>,
}

pub(crate) struct PllConfig {
    src: cfgr::PLLSRC_A,
    mul: cfgr::PLLMUL_A,
    div: Option<cfgr2::PREDIV_A>,
}

/// Determine the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor)
///
/// This function is based on the [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm).
fn gcd(mut a: u32, mut b: u32) -> u32 {
    while b != 0 {
        let r = a % b;
        a = b;
        b = r;
    }
    a
}

/// Convert pll multiplier into equivalent register field type
fn into_pll_mul(mul: u8) -> cfgr::PLLMUL_A {
    match mul {
        2 => cfgr::PLLMUL_A::MUL2,
        3 => cfgr::PLLMUL_A::MUL3,
        4 => cfgr::PLLMUL_A::MUL4,
        5 => cfgr::PLLMUL_A::MUL5,
        6 => cfgr::PLLMUL_A::MUL6,
        7 => cfgr::PLLMUL_A::MUL7,
        8 => cfgr::PLLMUL_A::MUL8,
        9 => cfgr::PLLMUL_A::MUL9,
        10 => cfgr::PLLMUL_A::MUL10,
        11 => cfgr::PLLMUL_A::MUL11,
        12 => cfgr::PLLMUL_A::MUL12,
        13 => cfgr::PLLMUL_A::MUL13,
        14 => cfgr::PLLMUL_A::MUL14,
        15 => cfgr::PLLMUL_A::MUL15,
        16 => cfgr::PLLMUL_A::MUL16,
        _ => crate::unreachable!(),
    }
}

/// Convert pll divisor into equivalent register field type
fn into_pre_div(div: u8) -> cfgr2::PREDIV_A {
    match div {
        1 => cfgr2::PREDIV_A::DIV1,
        2 => cfgr2::PREDIV_A::DIV2,
        3 => cfgr2::PREDIV_A::DIV3,
        4 => cfgr2::PREDIV_A::DIV4,
        5 => cfgr2::PREDIV_A::DIV5,
        6 => cfgr2::PREDIV_A::DIV6,
        7 => cfgr2::PREDIV_A::DIV7,
        8 => cfgr2::PREDIV_A::DIV8,
        9 => cfgr2::PREDIV_A::DIV9,
        10 => cfgr2::PREDIV_A::DIV10,
        11 => cfgr2::PREDIV_A::DIV11,
        12 => cfgr2::PREDIV_A::DIV12,
        13 => cfgr2::PREDIV_A::DIV13,
        14 => cfgr2::PREDIV_A::DIV14,
        15 => cfgr2::PREDIV_A::DIV15,
        16 => cfgr2::PREDIV_A::DIV16,
        _ => crate::unreachable!(),
    }
}

impl CFGR {
    /// Uses `HSE` (external oscillator) instead of `HSI` (internal RC oscillator) as the clock source.
    ///
    /// Will result in a hang if an external oscillator is not connected or it fails to start,
    /// unless [css](CFGR::enable_css) is enabled.
    pub fn use_hse<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.hse = Some(freq.into().0);
        self
    }

    /// Enable `HSE` bypass.
    ///
    /// Uses user provided clock signal instead of an external oscillator.
    /// `OSC_OUT` pin is free and can be used as GPIO.
    ///
    /// No effect if `HSE` is not enabled.
    pub fn bypass_hse(mut self) -> Self {
        self.hse_bypass = true;
        self
    }

    /// Enable `CSS` (Clock Security System).
    ///
    /// System clock is automatically switched to `HSI` and an interrupt (`CSSI`) is generated
    /// when `HSE` clock failure is detected.
    ///
    /// No effect if `HSE` is not enabled.
    pub fn enable_css(mut self) -> Self {
        self.css = true;
        self
    }

    /// Sets a frequency for the AHB bus
    pub fn hclk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.hclk = Some(freq.into().0);
        self
    }

    /// Sets a frequency for the `APB1` bus
    ///
    /// - Maximal supported frequency: 36 Mhz
    ///
    /// If not manually set, it will be set to [`CFGR::sysclk`] frequency
    /// or [`CFGR::sysclk`] frequency / 2, if [`CFGR::sysclk`] > 36 Mhz
    pub fn pclk1<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.pclk1 = Some(freq.into().0);
        self
    }

    /// Sets a frequency for the `APB2` bus
    ///
    /// # Resolution and Limits
    ///
    /// - Maximal supported frequency with HSE: 72 Mhz
    /// - Maximal supported frequency without HSE: 64 Mhz
    ///
    /// This is true for devices **except** the following devices,
    /// as these allow finer resolutions
    /// even when using the internal oscillator:
    ///
    ///     [stm32f302xd,stm32f302xe,stm32f303xd,stm32f303xe,stm32f398]
    ///
    pub fn pclk2<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.pclk2 = Some(freq.into().0);
        self
    }

    /// Sets the system (core) frequency
    ///
    /// # Resolution and Limits
    ///
    /// - Maximal supported frequency with `HSE`: 72 Mhz
    /// - Maximal supported frequency without `HSE`: 64 Mhz
    ///
    /// If [`CFGR::hse`] is not used, therefor `HSI / 2` is used.
    /// Only multiples of (HSI / 2) (4 Mhz) are allowed.
    ///
    /// This is true for devices **except** the following devices,
    /// as these allow finer resolutions
    /// even when using the internal oscillator:
    ///
    ///     [stm32f302xd,stm32f302xe,stm32f303xd,stm32f303xe,stm32f398]
    pub fn sysclk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.sysclk = Some(freq.into().0);
        self
    }

    /// Calculate the values for the pll multiplier (`PLLMUL`) and the pll divisior (`PLLDIV`).
    ///
    /// These values are chosen depending on the chosen system clock (SYSCLK) and the frequency of the
    /// oscillator clock (`HSE` / `HSI`).
    ///
    /// For these devices, `PLL_SRC` can selected between the internal oscillator (`HSI`) and
    /// the external oscillator (`HSE`).
    ///
    /// HSI is divided by 2 before its transferred to `PLL_SRC`.
    /// HSE can be divided between `1..16`, before it is transferred to `PLL_SRC`.
    /// After this system clock frequency (`SYSCLK`) can be changed via multiplier.
    /// The value can be multiplied with `2..16`.
    ///
    /// To determine the optimal values, if `HSE` is chosen as `PLL_SRC`, the greatest common divisor
    /// is calculated and the limitations of the possible values are taken into consideration.
    ///
    /// `HSI` is simpler to calculate, but the possible system clocks are less than `HSE`, because the
    /// division is not configurable.
    #[cfg(not(any(
        feature = "stm32f302xd",
        feature = "stm32f302xe",
        feature = "stm32f303xd",
        feature = "stm32f303xe",
        feature = "stm32f398"
    )))]
    fn calc_pll(&self, sysclk: u32) -> (u32, PllConfig) {
        let pllsrcclk = self.hse.unwrap_or(HSI / 2);
        // Get the optimal value for the pll divisor (PLL_DIV) and multiplier (PLL_MUL)
        // Only for HSE PLL_DIV can be changed
        let (pll_mul, pll_div): (u32, Option<u32>) = if self.hse.is_some() {
            // Get the optimal value for the pll divisor (PLL_DIV) and multiplier (PLL_MUL)
            // with the greatest common divisor calculation.
            let common_divisor = gcd(sysclk, pllsrcclk);
            let mut multiplier = sysclk / common_divisor;
            let mut divisor = pllsrcclk / common_divisor;

            // Check if the multiplier can be represented by PLL_MUL
            if multiplier == 1 {
                // PLL_MUL minimal value is 2
                multiplier *= 2;
                divisor *= 2;
            }

            // PLL_MUL maximal value is 16
            crate::assert!(multiplier <= 16);

            // PRE_DIV maximal value is 16
            crate::assert!(divisor <= 16);

            (multiplier, Some(divisor))
        }
        // HSI division is always divided by 2 and has no adjustable division
        else {
            let pll_mul = sysclk / pllsrcclk;
            crate::assert!(pll_mul <= 16);
            (pll_mul, None)
        };

        let sysclk = (pllsrcclk / pll_div.unwrap_or(1)) * pll_mul;
        crate::assert!(sysclk <= 72_000_000);

        let pll_src = if self.hse.is_some() {
            cfgr::PLLSRC_A::HSE_DIV_PREDIV
        } else {
            cfgr::PLLSRC_A::HSI_DIV2
        };

        // Convert into register bit field types
        let pll_mul_bits = into_pll_mul(pll_mul as u8);
        let pll_div_bits = pll_div.map(|pll_div| into_pre_div(pll_div as u8));

        (
            sysclk,
            PllConfig {
                src: pll_src,
                mul: pll_mul_bits,
                div: pll_div_bits,
            },
        )
    }

    /// Calculate the values for the pll multiplier (`PLLMUL`) and the pll divisor (`PLLDIV`).
    ///
    /// These values are chosen depending on the chosen system clock (`SYSCLK`) and the frequency of the oscillator
    /// clk (`HSI` / `HSE`).
    ///
    /// For these devices, `PLL_SRC` can be set to choose between the internal oscillator (HSI) and
    /// the external oscillator (`HSE`).
    /// After this the system clock frequency (`SYSCLK`) can be changed via a division and a
    /// multiplication block.
    /// It can be divided from with values `1..16`  and multiplied from `2..16`.
    ///
    /// To determine the optimal values, the greatest common divisor is calculated and the
    /// limitations of the possible values are taken into considiration.
    #[cfg(any(
        feature = "stm32f302xd",
        feature = "stm32f302xe",
        feature = "stm32f303xd",
        feature = "stm32f303xe",
        feature = "stm32f398",
    ))]
    fn calc_pll(&self, sysclk: u32) -> (u32, PllConfig) {
        let pllsrcclk = self.hse.unwrap_or(HSI);

        let (pll_mul, pll_div) = {
            // Get the optimal value for the pll divisor (PLL_DIV) and multiplcator (PLL_MUL)
            // with the greatest common divisor calculation.
            let common_divisor = gcd(sysclk, pllsrcclk);
            let mut multiplier = sysclk / common_divisor;
            let mut divisor = pllsrcclk / common_divisor;

            // Check if the multiplier can be represented by PLL_MUL
            if multiplier == 1 {
                // PLL_MUL minimal value is 2
                multiplier *= 2;
                divisor *= 2;
            }

            // PLL_MUL maximal value is 16
            crate::assert!(multiplier <= 16);

            // PRE_DIV maximal value is 16
            crate::assert!(divisor <= 16);

            (multiplier, divisor)
        };

        let sysclk = (pllsrcclk / pll_div) * pll_mul;
        crate::assert!(sysclk <= 72_000_000);

        // Select hardware clock source of the PLL
        // TODO Check whether HSI_DIV2 could be useful
        let pll_src = if self.hse.is_some() {
            cfgr::PLLSRC_A::HSE_DIV_PREDIV
        } else {
            cfgr::PLLSRC_A::HSI_DIV_PREDIV
        };

        // Convert into register bit field types
        let pll_mul_bits = into_pll_mul(pll_mul as u8);
        let pll_div_bits = into_pre_div(pll_div as u8);

        (
            sysclk,
            PllConfig {
                src: pll_src,
                mul: pll_mul_bits,
                div: Some(pll_div_bits),
            },
        )
    }

    /// Get the system clock, the system clock source and the pll_options, if needed.
    ///
    /// The system clock source is determined by the chosen system clock and the provided hardware
    /// clock.
    /// This function does only chose the PLL if needed, otherwise it will use the oscillator clock as system clock.
    ///
    /// Calls [`CFGR::calc_pll`] internally.
    fn get_sysclk(&self) -> (u32, cfgr::SW_A, Option<PllConfig>) {
        // If a sysclk is given, check if the PLL has to be used,
        // else select the system clock source, which is either HSI or HSE.
        match (self.sysclk, self.hse) {
            // No need to use the PLL
            // PLL is needed for USB, but we can make this assumption, to not use PLL here,
            // because the two valid USB clocks, 72 Mhz and 48 Mhz, can't be generated
            // directly from neither the internal rc (8 Mhz)  nor the external
            // Oscillator (max 32 Mhz), without using the PLL.
            (Some(sysclk), Some(hse)) if sysclk == hse => (hse, cfgr::SW_A::HSE, None),
            // No need to use the PLL
            (Some(sysclk), None) if sysclk == HSI => (HSI, cfgr::SW_A::HSI, None),
            (Some(sysclk), _) => {
                let (sysclk, pll_config) = self.calc_pll(sysclk);
                (sysclk, cfgr::SW_A::PLL, Some(pll_config))
            }
            // Use HSE as system clock
            (None, Some(hse)) => (hse, cfgr::SW_A::HSE, None),
            // Use HSI as system clock
            (None, None) => (HSI, cfgr::SW_A::HSI, None),
        }
    }

    /// Freezes the clock configuration, making it effective
    ///
    /// This function internally calculates the specific.
    /// divisors for the different clock peripheries.
    ///
    /// # Panics
    ///
    /// If any of the set frequencies via [`sysclk`](CFGR::sysclk), [`hclk`](CFGR::hclk), [`pclk1`](CFGR::pclk1) or [`pclk2`](CFGR::pclk2)
    /// are invalid or can not be reached because of e.g. to low frequencies
    /// of the former, as [`sysclk`](CFGR::sysclk) depends on the configuration of [`hclk`](CFGR::hclk)
    /// this function will panic.
    pub fn freeze(self, acr: &mut ACR) -> Clocks {
        let (sysclk, sysclk_source, pll_config) = self.get_sysclk();

        let (hpre_bits, hpre) =
            self.hclk
                .map_or((cfgr::HPRE_A::DIV1, 1), |hclk| match sysclk / hclk {
                    0 => crate::unreachable!(),
                    1 => (cfgr::HPRE_A::DIV1, 1),
                    2 => (cfgr::HPRE_A::DIV2, 2),
                    3..=5 => (cfgr::HPRE_A::DIV4, 4),
                    6..=11 => (cfgr::HPRE_A::DIV8, 8),
                    12..=39 => (cfgr::HPRE_A::DIV16, 16),
                    40..=95 => (cfgr::HPRE_A::DIV64, 64),
                    96..=191 => (cfgr::HPRE_A::DIV128, 128),
                    192..=383 => (cfgr::HPRE_A::DIV256, 256),
                    _ => (cfgr::HPRE_A::DIV512, 512),
                });

        let hclk: u32 = sysclk / hpre;

        crate::assert!(hclk <= 72_000_000);

        let (mut ppre1_bits, mut ppre1) =
            self.pclk1
                .map_or((cfgr::PPRE1_A::DIV1, 1), |pclk1| match hclk / pclk1 {
                    0 => crate::unreachable!(),
                    1 => (cfgr::PPRE1_A::DIV1, 1),
                    2 => (cfgr::PPRE1_A::DIV2, 2),
                    3..=5 => (cfgr::PPRE1_A::DIV4, 4),
                    6..=11 => (cfgr::PPRE1_A::DIV8, 8),
                    _ => (cfgr::PPRE1_A::DIV16, 16),
                });

        let mut pclk1 = hclk / u32::from(ppre1);

        // This ensures, that no panic happens, when
        // pclk1 is not manually set.
        // As hclk highest value is 72.mhz()
        // dividing by 2 should always be sufficient
        if self.pclk1.is_none() && pclk1 > 36_000_000 {
            ppre1_bits = cfgr::PPRE1_A::DIV2;
            ppre1 = 2;
            pclk1 = hclk / u32::from(ppre1);
        }

        crate::assert!(pclk1 <= 36_000_000);

        let (ppre2_bits, ppre2) =
            self.pclk2
                .map_or((cfgr::PPRE2_A::DIV1, 1), |pclk2| match hclk / pclk2 {
                    0 => crate::unreachable!(),
                    1 => (cfgr::PPRE2_A::DIV1, 1),
                    2 => (cfgr::PPRE2_A::DIV2, 2),
                    3..=5 => (cfgr::PPRE2_A::DIV4, 4),
                    6..=11 => (cfgr::PPRE2_A::DIV8, 8),
                    _ => (cfgr::PPRE2_A::DIV16, 16),
                });

        let pclk2 = hclk / u32::from(ppre2);

        crate::assert!(pclk2 <= 72_000_000);

        // Adjust flash wait states according to the
        // HCLK frequency (cpu core clock)
        acr.acr().modify(|_, w| {
            if hclk <= 24_000_000 {
                w.latency().ws0()
            } else if hclk <= 48_000_000 {
                w.latency().ws1()
            } else {
                w.latency().ws2()
            }
        });

        let (usbpre, usbclk_valid) = usb_clocking::is_valid(sysclk, self.hse, pclk1, &pll_config);

        let rcc = unsafe { &*RCC::ptr() };

        // enable HSE and wait for it to be ready
        if self.hse.is_some() {
            rcc.cr.modify(|_, w| {
                w.hsebyp().bit(self.hse_bypass);
                w.csson().bit(self.css);
                w.hseon().on()
            });

            while rcc.cr.read().hserdy().is_not_ready() {}
        }

        // enable PLL and wait for it to be ready
        if let Some(pll_config) = pll_config {
            rcc.cfgr.modify(|_, w| {
                w.pllmul()
                    .variant(pll_config.mul)
                    .pllsrc()
                    .variant(pll_config.src)
            });

            if let Some(pll_div) = pll_config.div {
                rcc.cfgr2.modify(|_, w| w.prediv().variant(pll_div));
            };

            rcc.cr.modify(|_, w| w.pllon().on());

            while rcc.cr.read().pllrdy().is_not_ready() {}
        };

        // set prescalers and clock source
        rcc.cfgr.modify(|_, w| {
            usb_clocking::set_usbpre(w, usbpre);

            w.ppre2()
                .variant(ppre2_bits)
                .ppre1()
                .variant(ppre1_bits)
                .hpre()
                .variant(hpre_bits)
                .sw()
                .variant(sysclk_source)
        });

        Clocks {
            hclk: Hertz(hclk),
            pclk1: Hertz(pclk1),
            pclk2: Hertz(pclk2),
            ppre1,
            ppre2,
            sysclk: Hertz(sysclk),
            usbclk_valid,
        }
    }
}

/// Frozen clock frequencies
///
/// The existence of this value indicates that the clock configuration can no longer be changed.
/// This struct can be obtained via the [freeze](CFGR::freeze) method of the [CFGR](CFGR) struct.
#[derive(Clone, Copy)]
pub struct Clocks {
    pub(crate) hclk: Hertz,
    pub(crate) pclk1: Hertz,
    pub(crate) pclk2: Hertz,
    pub(crate) ppre1: u8,
    pub(crate) ppre2: u8,
    pub(crate) sysclk: Hertz,
    pub(crate) usbclk_valid: bool,
}

impl Clocks {
    /// Returns the frequency of the AHB
    pub fn hclk(&self) -> Hertz {
        self.hclk
    }

    /// Returns the frequency of the APB1
    pub fn pclk1(&self) -> Hertz {
        self.pclk1
    }

    /// Returns the frequency of the APB2
    pub fn pclk2(&self) -> Hertz {
        self.pclk2
    }

    pub(crate) fn ppre1(&self) -> u8 {
        self.ppre1
    }

    // TODO remove `allow`
    #[allow(dead_code)]
    pub(crate) fn ppre2(&self) -> u8 {
        self.ppre2
    }

    /// Returns the system (core) frequency
    pub fn sysclk(&self) -> Hertz {
        self.sysclk
    }

    /// Returns whether the USBCLK clock frequency is valid for the USB peripheral
    ///
    /// If the microcontroller does support USB, 48 Mhz or 72 Mhz have to be used
    /// and the [`CFGR::hse`] must be used.
    ///
    /// The APB1 / [`CFGR::pclk1`] clock must have a minimum frequency of 10 MHz to avoid data
    /// overrun/underrun problems. [RM0316 32.5.2][RM0316]
    ///
    /// [RM0316]: https://www.st.com/resource/en/reference_manual/dm00043574.pdf
    pub fn usbclk_valid(&self) -> bool {
        self.usbclk_valid
    }
}