From c94ba8489289789e295a248720c96040b2dc724c Mon Sep 17 00:00:00 2001
From: Kevin Lannen <kevin@luci.com>
Date: Wed, 14 Jun 2023 10:44:51 -0600
Subject: [PATCH 1/2] stm32g4: PLL: Add support for configuring PLL_P and PLL_Q

---
 embassy-stm32/src/rcc/g4.rs     | 207 ++++++++++++++++++++++++++------
 examples/stm32g4/src/bin/pll.rs |  15 ++-
 2 files changed, 184 insertions(+), 38 deletions(-)

diff --git a/embassy-stm32/src/rcc/g4.rs b/embassy-stm32/src/rcc/g4.rs
index 2b52416b2..9401af4c3 100644
--- a/embassy-stm32/src/rcc/g4.rs
+++ b/embassy-stm32/src/rcc/g4.rs
@@ -17,7 +17,7 @@ pub const LSI_FREQ: Hertz = Hertz(32_000);
 pub enum ClockSrc {
     HSE(Hertz),
     HSI16,
-    PLLCLK(PllSrc, PllM, PllN, PllR),
+    PLL,
 }
 
 /// AHB prescaler
@@ -60,6 +60,68 @@ impl Into<Pllsrc> for PllSrc {
     }
 }
 
+seq_macro::seq!(P in 2..=31 {
+    /// Output divider for the PLL P output.
+    #[derive(Clone, Copy)]
+    pub enum PllP {
+        // Note: If PLL P is set to 0 the PLLP bit controls the output division. There does not seem to
+        // a good reason to do this so the API does not support it.
+        // Div1 is invalid
+        #(
+            Div~P,
+        )*
+    }
+
+    impl From<PllP> for u8 {
+        /// Returns the register value for the P output divider.
+        fn from(val: PllP) -> u8 {
+            match val {
+                #(
+                    PllP::Div~P => P,
+                )*
+            }
+        }
+    }
+});
+
+impl PllP {
+    /// Returns the numeric value of the P output divider.
+    pub fn to_div(self) -> u32 {
+        let val: u8 = self.into();
+        val as u32
+    }
+}
+
+/// Output divider for the PLL Q output.
+#[derive(Clone, Copy)]
+pub enum PllQ {
+    Div2,
+    Div4,
+    Div6,
+    Div8,
+}
+
+impl PllQ {
+    /// Returns the numeric value of the Q output divider.
+    pub fn to_div(self) -> u32 {
+        let val: u8 = self.into();
+        (val as u32 + 1) * 2
+    }
+}
+
+impl From<PllQ> for u8 {
+    /// Returns the register value for the Q output divider.
+    fn from(val: PllQ) -> u8 {
+        match val {
+            PllQ::Div2 => 0b00,
+            PllQ::Div4 => 0b01,
+            PllQ::Div6 => 0b10,
+            PllQ::Div8 => 0b11,
+        }
+    }
+}
+
+/// Output divider for the PLL R output.
 #[derive(Clone, Copy)]
 pub enum PllR {
     Div2,
@@ -69,6 +131,7 @@ pub enum PllR {
 }
 
 impl PllR {
+    /// Returns the numeric value of the R output divider.
     pub fn to_div(self) -> u32 {
         let val: u8 = self.into();
         (val as u32 + 1) * 2
@@ -76,6 +139,7 @@ impl PllR {
 }
 
 impl From<PllR> for u8 {
+    /// Returns the register value for the R output divider.
     fn from(val: PllR) -> u8 {
         match val {
             PllR::Div2 => 0b00,
@@ -87,6 +151,7 @@ impl From<PllR> for u8 {
 }
 
 seq_macro::seq!(N in 8..=127 {
+    /// Multiplication factor for the PLL VCO input clock.
     #[derive(Clone, Copy)]
     pub enum PllN {
         #(
@@ -95,6 +160,7 @@ seq_macro::seq!(N in 8..=127 {
     }
 
     impl From<PllN> for u8 {
+        /// Returns the register value for the N multiplication factor.
         fn from(val: PllN) -> u8 {
             match val {
                 #(
@@ -105,6 +171,7 @@ seq_macro::seq!(N in 8..=127 {
     }
 
     impl PllN {
+        /// Returns the numeric value of the N multiplication factor.
         pub fn to_mul(self) -> u32 {
             match self {
                 #(
@@ -115,7 +182,7 @@ seq_macro::seq!(N in 8..=127 {
     }
 });
 
-// Pre-division
+/// PLL Pre-division. This must be set such that the PLL input is between 2.66 MHz and 16 MHz.
 #[derive(Copy, Clone)]
 pub enum PllM {
     Div1,
@@ -137,6 +204,7 @@ pub enum PllM {
 }
 
 impl PllM {
+    /// Returns the numeric value of the M pre-division.
     pub fn to_div(self) -> u32 {
         let val: u8 = self.into();
         val as u32 + 1
@@ -144,6 +212,7 @@ impl PllM {
 }
 
 impl From<PllM> for u8 {
+    /// Returns the register value for the M pre-division.
     fn from(val: PllM) -> u8 {
         match val {
             PllM::Div1 => 0b0000,
@@ -166,6 +235,31 @@ impl From<PllM> for u8 {
     }
 }
 
+/// PLL Configuration
+///
+/// Use this struct to configure the PLL source, input frequency, multiplication factor, and output
+/// dividers. Be sure to keep check the datasheet for your specific part for the appropriate
+/// frequency ranges for each of these settings.
+pub struct Pll {
+    /// PLL Source clock selection.
+    pub source: PllSrc,
+
+    /// PLL pre-divider
+    pub prediv_m: PllM,
+
+    /// PLL multiplication factor for VCO
+    pub mul_n: PllN,
+
+    /// PLL division factor for P clock (ADC Clock)
+    pub div_p: Option<PllP>,
+
+    /// PLL division factor for Q clock (USB, I2S23, SAI1, FDCAN, QSPI)
+    pub div_q: Option<PllQ>,
+
+    /// PLL division factor for R clock (SYSCLK)
+    pub div_r: Option<PllR>,
+}
+
 impl AHBPrescaler {
     const fn div(self) -> u32 {
         match self {
@@ -229,6 +323,9 @@ pub struct Config {
     pub apb1_pre: APBPrescaler,
     pub apb2_pre: APBPrescaler,
     pub low_power_run: bool,
+    /// Iff PLL is requested as the main clock source in the `mux` field then the PLL configuration
+    /// MUST turn on the PLLR output.
+    pub pll: Option<Pll>,
 }
 
 impl Default for Config {
@@ -240,11 +337,80 @@ impl Default for Config {
             apb1_pre: APBPrescaler::NotDivided,
             apb2_pre: APBPrescaler::NotDivided,
             low_power_run: false,
+            pll: None,
         }
     }
 }
 
+pub struct PllFreq {
+    pub pll_p: Option<Hertz>,
+    pub pll_q: Option<Hertz>,
+    pub pll_r: Option<Hertz>,
+}
+
 pub(crate) unsafe fn init(config: Config) {
+    let pll_freq = config.pll.map(|pll_config| {
+        let src_freq = match pll_config.source {
+            PllSrc::HSI16 => {
+                RCC.cr().write(|w| w.set_hsion(true));
+                while !RCC.cr().read().hsirdy() {}
+
+                HSI_FREQ.0
+            }
+            PllSrc::HSE(freq) => {
+                RCC.cr().write(|w| w.set_hseon(true));
+                while !RCC.cr().read().hserdy() {}
+                freq.0
+            }
+        };
+
+        // Disable PLL before configuration
+        RCC.cr().modify(|w| w.set_pllon(false));
+        while RCC.cr().read().pllrdy() {}
+
+        let internal_freq = src_freq / pll_config.prediv_m.to_div() * pll_config.mul_n.to_mul();
+
+        RCC.pllcfgr().write(|w| {
+            w.set_plln(pll_config.mul_n.into());
+            w.set_pllm(pll_config.prediv_m.into());
+            w.set_pllsrc(pll_config.source.into());
+        });
+
+        let pll_p_freq = pll_config.div_p.map(|div_p| {
+            RCC.pllcfgr().modify(|w| {
+                w.set_pllpdiv(div_p.into());
+                w.set_pllpen(true);
+            });
+            Hertz(internal_freq / div_p.to_div())
+        });
+
+        let pll_q_freq = pll_config.div_q.map(|div_q| {
+            RCC.pllcfgr().modify(|w| {
+                w.set_pllq(div_q.into());
+                w.set_pllqen(true);
+            });
+            Hertz(internal_freq / div_q.to_div())
+        });
+
+        let pll_r_freq = pll_config.div_r.map(|div_r| {
+            RCC.pllcfgr().modify(|w| {
+                w.set_pllr(div_r.into());
+                w.set_pllren(true);
+            });
+            Hertz(internal_freq / div_r.to_div())
+        });
+
+        // Enable the PLL
+        RCC.cr().modify(|w| w.set_pllon(true));
+        while !RCC.cr().read().pllrdy() {}
+
+        PllFreq {
+            pll_p: pll_p_freq,
+            pll_q: pll_q_freq,
+            pll_r: pll_r_freq,
+        }
+    });
+
     let (sys_clk, sw) = match config.mux {
         ClockSrc::HSI16 => {
             // Enable HSI16
@@ -260,29 +426,12 @@ pub(crate) unsafe fn init(config: Config) {
 
             (freq.0, Sw::HSE)
         }
-        ClockSrc::PLLCLK(src, prediv, mul, div) => {
-            let src_freq = match src {
-                PllSrc::HSI16 => {
-                    // Enable HSI16 as clock source for PLL
-                    RCC.cr().write(|w| w.set_hsion(true));
-                    while !RCC.cr().read().hsirdy() {}
+        ClockSrc::PLL => {
+            assert!(pll_freq.is_some());
+            assert!(pll_freq.as_ref().unwrap().pll_r.is_some());
 
-                    HSI_FREQ.0
-                }
-                PllSrc::HSE(freq) => {
-                    // Enable HSE as clock source for PLL
-                    RCC.cr().write(|w| w.set_hseon(true));
-                    while !RCC.cr().read().hserdy() {}
+            let freq = pll_freq.unwrap().pll_r.unwrap().0;
 
-                    freq.0
-                }
-            };
-
-            // Make sure PLL is disabled while we configure it
-            RCC.cr().modify(|w| w.set_pllon(false));
-            while RCC.cr().read().pllrdy() {}
-
-            let freq = src_freq / prediv.to_div() * mul.to_mul() / div.to_div();
             assert!(freq <= 170_000_000);
 
             if freq >= 150_000_000 {
@@ -316,18 +465,6 @@ pub(crate) unsafe fn init(config: Config) {
                 }
             }
 
-            RCC.pllcfgr().write(move |w| {
-                w.set_plln(mul.into());
-                w.set_pllm(prediv.into());
-                w.set_pllr(div.into());
-                w.set_pllsrc(src.into());
-            });
-
-            // Enable PLL
-            RCC.cr().modify(|w| w.set_pllon(true));
-            while !RCC.cr().read().pllrdy() {}
-            RCC.pllcfgr().modify(|w| w.set_pllren(true));
-
             (freq, Sw::PLLRCLK)
         }
     };
diff --git a/examples/stm32g4/src/bin/pll.rs b/examples/stm32g4/src/bin/pll.rs
index 8cee41e9b..ef7d4800c 100644
--- a/examples/stm32g4/src/bin/pll.rs
+++ b/examples/stm32g4/src/bin/pll.rs
@@ -4,7 +4,7 @@
 
 use defmt::*;
 use embassy_executor::Spawner;
-use embassy_stm32::rcc::{ClockSrc, PllM, PllN, PllR, PllSrc};
+use embassy_stm32::rcc::{ClockSrc, Pll, PllM, PllN, PllR, PllSrc};
 use embassy_stm32::Config;
 use embassy_time::{Duration, Timer};
 use {defmt_rtt as _, panic_probe as _};
@@ -13,8 +13,17 @@ use {defmt_rtt as _, panic_probe as _};
 async fn main(_spawner: Spawner) {
     let mut config = Config::default();
 
-    // Configure PLL to max frequency of 170 MHz
-    config.rcc.mux = ClockSrc::PLLCLK(PllSrc::HSI16, PllM::Div4, PllN::Mul85, PllR::Div2);
+    config.rcc.pll = Some(Pll {
+        source: PllSrc::HSI16,
+        prediv_m: PllM::Div4,
+        mul_n: PllN::Mul85,
+        div_p: None,
+        div_q: None,
+        // Main system clock at 170 MHz
+        div_r: Some(PllR::Div2),
+    });
+
+    config.rcc.mux = ClockSrc::PLL;
 
     let _p = embassy_stm32::init(config);
     info!("Hello World!");

From 61aa6b5236b68b037db1c5f349e8183a2980ffc5 Mon Sep 17 00:00:00 2001
From: Kevin Lannen <kevin@luci.com>
Date: Wed, 14 Jun 2023 11:07:19 -0600
Subject: [PATCH 2/2] STM32G4: Add USB Serial example

---
 examples/stm32g4/Cargo.toml            |   1 +
 examples/stm32g4/src/bin/usb_serial.rs | 110 +++++++++++++++++++++++++
 2 files changed, 111 insertions(+)
 create mode 100644 examples/stm32g4/src/bin/usb_serial.rs

diff --git a/examples/stm32g4/Cargo.toml b/examples/stm32g4/Cargo.toml
index f94df2dd3..fbfbc6408 100644
--- a/examples/stm32g4/Cargo.toml
+++ b/examples/stm32g4/Cargo.toml
@@ -10,6 +10,7 @@ embassy-executor = { version = "0.2.0", path = "../../embassy-executor", feature
 embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
 embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "time-driver-any", "stm32g491re", "memory-x", "unstable-pac", "exti"]  }
 embassy-hal-common = {version = "0.1.0", path = "../../embassy-hal-common" }
+embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] }
 
 defmt = "0.3"
 defmt-rtt = "0.4"
diff --git a/examples/stm32g4/src/bin/usb_serial.rs b/examples/stm32g4/src/bin/usb_serial.rs
new file mode 100644
index 000000000..ecbe3a6e6
--- /dev/null
+++ b/examples/stm32g4/src/bin/usb_serial.rs
@@ -0,0 +1,110 @@
+#![no_std]
+#![no_main]
+#![feature(type_alias_impl_trait)]
+
+use defmt::{panic, *};
+use embassy_executor::Spawner;
+use embassy_stm32::rcc::{ClockSrc, Pll, PllM, PllN, PllQ, PllR, PllSrc};
+use embassy_stm32::time::Hertz;
+use embassy_stm32::usb::{self, Driver, Instance};
+use embassy_stm32::{bind_interrupts, pac, peripherals, Config};
+use embassy_usb::class::cdc_acm::{CdcAcmClass, State};
+use embassy_usb::driver::EndpointError;
+use embassy_usb::Builder;
+use futures::future::join;
+use {defmt_rtt as _, panic_probe as _};
+
+bind_interrupts!(struct Irqs {
+    USB_LP => usb::InterruptHandler<peripherals::USB>;
+});
+
+#[embassy_executor::main]
+async fn main(_spawner: Spawner) {
+    let mut config = Config::default();
+
+    config.rcc.pll = Some(Pll {
+        source: PllSrc::HSE(Hertz(8000000)),
+        prediv_m: PllM::Div2,
+        mul_n: PllN::Mul72,
+        div_p: None,
+        // USB and CAN at 48 MHz
+        div_q: Some(PllQ::Div6),
+        // Main system clock at 144 MHz
+        div_r: Some(PllR::Div2),
+    });
+
+    config.rcc.mux = ClockSrc::PLL;
+
+    let p = embassy_stm32::init(config);
+    info!("Hello World!");
+
+    unsafe {
+        pac::RCC.ccipr().write(|w| w.set_clk48sel(0b10));
+    }
+
+    let driver = Driver::new(p.USB, Irqs, p.PA12, p.PA11);
+
+    let mut config = embassy_usb::Config::new(0xc0de, 0xcafe);
+    config.manufacturer = Some("Embassy");
+    config.product = Some("USB-Serial Example");
+    config.serial_number = Some("123456");
+
+    config.device_class = 0xEF;
+    config.device_sub_class = 0x02;
+    config.device_protocol = 0x01;
+    config.composite_with_iads = true;
+
+    let mut device_descriptor = [0; 256];
+    let mut config_descriptor = [0; 256];
+    let mut bos_descriptor = [0; 256];
+    let mut control_buf = [0; 64];
+
+    let mut state = State::new();
+
+    let mut builder = Builder::new(
+        driver,
+        config,
+        &mut device_descriptor,
+        &mut config_descriptor,
+        &mut bos_descriptor,
+        &mut control_buf,
+    );
+
+    let mut class = CdcAcmClass::new(&mut builder, &mut state, 64);
+
+    let mut usb = builder.build();
+
+    let usb_fut = usb.run();
+
+    let echo_fut = async {
+        loop {
+            class.wait_connection().await;
+            info!("Connected");
+            let _ = echo(&mut class).await;
+            info!("Disconnected");
+        }
+    };
+
+    join(usb_fut, echo_fut).await;
+}
+
+struct Disconnected {}
+
+impl From<EndpointError> for Disconnected {
+    fn from(val: EndpointError) -> Self {
+        match val {
+            EndpointError::BufferOverflow => panic!("Buffer overflow"),
+            EndpointError::Disabled => Disconnected {},
+        }
+    }
+}
+
+async fn echo<'d, T: Instance + 'd>(class: &mut CdcAcmClass<'d, Driver<'d, T>>) -> Result<(), Disconnected> {
+    let mut buf = [0; 64];
+    loop {
+        let n = class.read_packet(&mut buf).await?;
+        let data = &buf[..n];
+        info!("data: {:x}", data);
+        class.write_packet(data).await?;
+    }
+}