From 46e1bae9e36917c2e763082730d99df302c1c625 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Mon, 7 Jun 2021 02:30:38 -0300 Subject: [PATCH 01/15] eth-v2: Start Ethernet peripheral implementation --- embassy-net/src/lib.rs | 2 +- embassy-net/src/packet_pool.rs | 3 +- embassy-stm32/Cargo.toml | 3 + embassy-stm32/src/eth/mod.rs | 7 + embassy-stm32/src/eth/v1.rs | 1 + embassy-stm32/src/eth/v2/descriptors.rs | 371 ++++++++++++++++++++++++ embassy-stm32/src/eth/v2/mod.rs | 350 ++++++++++++++++++++++ embassy-stm32/src/lib.rs | 2 + 8 files changed, 737 insertions(+), 2 deletions(-) create mode 100644 embassy-stm32/src/eth/mod.rs create mode 100644 embassy-stm32/src/eth/v1.rs create mode 100644 embassy-stm32/src/eth/v2/descriptors.rs create mode 100644 embassy-stm32/src/eth/v2/mod.rs diff --git a/embassy-net/src/lib.rs b/embassy-net/src/lib.rs index 88dcf0aa..51eb97a2 100644 --- a/embassy-net/src/lib.rs +++ b/embassy-net/src/lib.rs @@ -13,7 +13,7 @@ pub use config::DhcpConfigurator; pub use config::{Config, Configurator, Event as ConfigEvent, StaticConfigurator}; pub use device::{Device, LinkState}; -pub use packet_pool::{Packet, PacketBox, PacketBoxExt, PacketBuf}; +pub use packet_pool::{Packet, PacketBox, PacketBoxExt, PacketBuf, MTU}; pub use stack::{init, is_config_up, is_init, is_link_up, run}; #[cfg(feature = "tcp")] diff --git a/embassy-net/src/packet_pool.rs b/embassy-net/src/packet_pool.rs index 2c27d401..0ec88e64 100644 --- a/embassy-net/src/packet_pool.rs +++ b/embassy-net/src/packet_pool.rs @@ -3,12 +3,13 @@ use core::ops::{Deref, DerefMut, Range}; use atomic_pool::{pool, Box}; -pub const MTU: usize = 1514; +pub const MTU: usize = 1516; pub const PACKET_POOL_SIZE: usize = 4; pool!(pub PacketPool: [Packet; PACKET_POOL_SIZE]); pub type PacketBox = Box; +#[repr(align(4))] pub struct Packet(pub [u8; MTU]); impl Packet { diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 682ebaef..cf45fe21 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -10,6 +10,7 @@ embassy = { version = "0.1.0", path = "../embassy" } embassy-macros = { version = "0.1.0", path = "../embassy-macros", features = ["stm32"] } embassy-extras = {version = "0.1.0", path = "../embassy-extras" } embassy-traits = {version = "0.1.0", path = "../embassy-traits" } +embassy-net = { version = "0.1.0", path = "../embassy-net", features = ["tcp", "medium-ip"] } defmt = { version = "0.2.0", optional = true } log = { version = "0.4.11", optional = true } @@ -24,6 +25,8 @@ critical-section = "0.2.1" bare-metal = "1.0.0" atomic-polyfill = "0.1.2" stm32-metapac = { version = "0.1.0", path = "../stm32-metapac", features = ["rt"] } +vcell = "0.1.3" + cfg-if = "1.0.0" [build-dependencies] diff --git a/embassy-stm32/src/eth/mod.rs b/embassy-stm32/src/eth/mod.rs new file mode 100644 index 00000000..8791e155 --- /dev/null +++ b/embassy-stm32/src/eth/mod.rs @@ -0,0 +1,7 @@ +#![macro_use] + +#[cfg_attr(eth_v1, path = "v1.rs")] +#[cfg_attr(eth_v2, path = "v2/mod.rs")] +mod _version; + +pub use _version::*; diff --git a/embassy-stm32/src/eth/v1.rs b/embassy-stm32/src/eth/v1.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/embassy-stm32/src/eth/v1.rs @@ -0,0 +1 @@ + diff --git a/embassy-stm32/src/eth/v2/descriptors.rs b/embassy-stm32/src/eth/v2/descriptors.rs new file mode 100644 index 00000000..095eef20 --- /dev/null +++ b/embassy-stm32/src/eth/v2/descriptors.rs @@ -0,0 +1,371 @@ +use core::sync::atomic::{fence, Ordering}; + +use embassy_net::{Packet, PacketBox, PacketBoxExt, PacketBuf}; +use vcell::VolatileCell; + +use crate::pac::ETH; + +#[non_exhaustive] +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + NoBufferAvailable, + // TODO: Break down this error into several others + TransmissionError, +} + +/// Transmit and Receive Descriptor fields +#[allow(dead_code)] +mod emac_consts { + pub const EMAC_DES3_OWN: u32 = 0x8000_0000; + pub const EMAC_DES3_CTXT: u32 = 0x4000_0000; + pub const EMAC_DES3_FD: u32 = 0x2000_0000; + pub const EMAC_DES3_LD: u32 = 0x1000_0000; + pub const EMAC_DES3_ES: u32 = 0x0000_8000; + pub const EMAC_DES0_BUF1AP: u32 = 0xFFFF_FFFF; + + pub const EMAC_TDES2_IOC: u32 = 0x8000_0000; + pub const EMAC_TDES2_B1L: u32 = 0x0000_3FFF; + + pub const EMAC_RDES3_IOC: u32 = 0x4000_0000; + pub const EMAC_RDES3_PL: u32 = 0x0000_7FFF; + pub const EMAC_RDES3_BUF1V: u32 = 0x0100_0000; + pub const EMAC_RDES3_PKTLEN: u32 = 0x0000_7FFF; +} +use emac_consts::*; + +/// Transmit Descriptor representation +/// +/// * tdes0: transmit buffer address +/// * tdes1: +/// * tdes2: buffer lengths +/// * tdes3: control and payload/frame length +#[repr(C)] +struct TDes { + tdes0: VolatileCell, + tdes1: VolatileCell, + tdes2: VolatileCell, + tdes3: VolatileCell, +} + +impl TDes { + pub const fn new() -> Self { + Self { + tdes0: VolatileCell::new(0), + tdes1: VolatileCell::new(0), + tdes2: VolatileCell::new(0), + tdes3: VolatileCell::new(0), + } + } + + /// Return true if this TDes is not currently owned by the DMA + pub fn available(&self) -> bool { + self.tdes3.get() & EMAC_DES3_OWN == 0 + } +} + +pub(crate) struct TDesRing { + td: [TDes; N], + buffers: [Option; N], + tdidx: usize, +} + +impl TDesRing { + pub const fn new() -> Self { + const TDES: TDes = TDes::new(); + const BUFFERS: Option = None; + + Self { + td: [TDES; N], + buffers: [BUFFERS; N], + tdidx: 0, + } + } + + /// Initialise this TDesRing. Assume TDesRing is corrupt + /// + /// The current memory address of the buffers inside this TDesRing + /// will be stored in the descriptors, so ensure the TDesRing is + /// not moved after initialisation. + pub(crate) fn init(&mut self) { + assert!(N > 0); + + for td in self.td.iter_mut() { + *td = TDes::new(); + } + self.tdidx = 0; + + // Initialize the pointers in the DMA engine. (There will be a memory barrier later + // before the DMA engine is enabled.) + // NOTE (unsafe) Used for atomic writes + unsafe { + let dma = ETH.ethernet_dma(); + + dma.dmactx_dlar() + .write(|w| w.set_tdesla(&self.td as *const _ as u32)); + dma.dmactx_rlr().write(|w| w.set_tdrl((N as u16) - 1)); + dma.dmactx_dtpr() + .write(|w| w.set_tdt(&self.td[0] as *const _ as u32)); + } + } + + /// Return true if a TDes is available for use + pub(crate) fn available(&self) -> bool { + self.td[self.tdidx].available() + } + + pub(crate) fn transmit(&mut self, pkt: PacketBuf) -> Result<(), Error> { + if !self.available() { + return Err(Error::NoBufferAvailable); + } + let x = self.tdidx; + let td = &mut self.td[x]; + + let pkt_len = pkt.len(); + assert!(pkt_len as u32 <= EMAC_TDES2_B1L); + let address = pkt.as_ptr() as u32; + + // Read format + td.tdes0.set(address); + td.tdes2 + .set(pkt_len as u32 & EMAC_TDES2_B1L | EMAC_TDES2_IOC); + + // FD: Contains first buffer of packet + // LD: Contains last buffer of packet + // Give the DMA engine ownership + td.tdes3.set(EMAC_DES3_FD | EMAC_DES3_LD | EMAC_DES3_OWN); + + self.buffers[x].replace(pkt); + + // Ensure changes to the descriptor are committed before DMA engine sees tail pointer store. + // This will generate an DMB instruction. + // "Preceding reads and writes cannot be moved past subsequent writes." + fence(Ordering::Release); + + // Move the tail pointer (TPR) to the next descriptor + let x = (x + 1) % N; + // NOTE(unsafe) Atomic write + unsafe { + ETH.ethernet_dma() + .dmactx_dtpr() + .write(|w| w.set_tdt(&self.td[x] as *const _ as u32)); + } + self.tdidx = x; + Ok(()) + } + + pub(crate) fn on_interrupt(&mut self) -> Result<(), Error> { + let previous = (self.tdidx + N - 1) % N; + let td = &self.td[previous]; + + // DMB to ensure that we are reading an updated value, probably not needed at the hardware + // level, but this is also a hint to the compiler that we're syncing on the buffer. + fence(Ordering::SeqCst); + + let tdes3 = td.tdes3.get(); + + if tdes3 & EMAC_DES3_OWN != 0 { + // Transmission isn't done yet, probably a receive interrupt that fired this + return Ok(()); + } + assert!(tdes3 & EMAC_DES3_CTXT == 0); + + // Release the buffer + self.buffers[previous].take(); + + if tdes3 & EMAC_DES3_ES != 0 { + Err(Error::TransmissionError) + } else { + Ok(()) + } + } +} + +/// Receive Descriptor representation +/// +/// * rdes0: recieve buffer address +/// * rdes1: +/// * rdes2: +/// * rdes3: OWN and Status +#[repr(C)] +struct RDes { + rdes0: VolatileCell, + rdes1: VolatileCell, + rdes2: VolatileCell, + rdes3: VolatileCell, +} + +impl RDes { + pub const fn new() -> Self { + Self { + rdes0: VolatileCell::new(0), + rdes1: VolatileCell::new(0), + rdes2: VolatileCell::new(0), + rdes3: VolatileCell::new(0), + } + } + + /// Return true if this RDes is acceptable to us + #[inline(always)] + pub fn valid(&self) -> bool { + // Write-back descriptor is valid if: + // + // Contains first buffer of packet AND contains last buf of + // packet AND no errors AND not a context descriptor + self.rdes3.get() & (EMAC_DES3_FD | EMAC_DES3_LD | EMAC_DES3_ES | EMAC_DES3_CTXT) + == (EMAC_DES3_FD | EMAC_DES3_LD) + } + + /// Return true if this RDes is not currently owned by the DMA + #[inline(always)] + pub fn available(&self) -> bool { + self.rdes3.get() & EMAC_DES3_OWN == 0 // Owned by us + } + + #[inline(always)] + pub fn set_ready(&mut self, buf_addr: u32) { + self.rdes0.set(buf_addr); + self.rdes3 + .set(EMAC_RDES3_BUF1V | EMAC_RDES3_IOC | EMAC_DES3_OWN); + } +} + +pub(crate) struct RDesRing { + rd: [RDes; N], + buffers: [Option; N], + read_idx: usize, + tail_idx: usize, +} + +impl RDesRing { + pub const fn new() -> Self { + const RDES: RDes = RDes::new(); + const BUFFERS: Option = None; + + Self { + rd: [RDES; N], + buffers: [BUFFERS; N], + read_idx: 0, + tail_idx: 0, + } + } + + pub(crate) fn init(&mut self) { + assert!(N > 1); + + for desc in self.rd.iter_mut() { + *desc = RDes::new(); + } + + let mut last_index = 0; + for (index, buf) in self.buffers.iter_mut().enumerate() { + let pkt = match PacketBox::new(Packet::new()) { + Some(p) => p, + None => { + if index == 0 { + panic!("Could not allocate at least one buffer for Ethernet receiving"); + } else { + break; + } + } + }; + let addr = pkt.as_ptr() as u32; + *buf = Some(pkt); + self.rd[index].set_ready(addr); + last_index = index; + } + self.tail_idx = (last_index + 1) % N; + + unsafe { + let dma = ETH.ethernet_dma(); + + dma.dmacrx_dlar() + .write(|w| w.set_rdesla(self.rd.as_ptr() as u32)); + dma.dmacrx_rlr().write(|w| w.set_rdrl((N as u16) - 1)); + + // We manage to allocate all buffers, set the index to the last one, that means + // that the DMA won't consider the last one as ready, because it (unfortunately) + // stops at the tail ptr and wraps at the end of the ring, which means that we + // can't tell it to stop after the last buffer. + let tail_ptr = &self.rd[last_index] as *const _ as u32; + fence(Ordering::Release); + + dma.dmacrx_dtpr().write(|w| w.set_rdt(tail_ptr)); + } + } + + pub(crate) fn on_interrupt(&mut self) { + // TODO! + } + + pub(crate) fn pop_packet(&mut self) -> Option { + // Not sure if the contents of the write buffer on the M7 can affects reads, so we are using + // a DMB here just in case, it also serves as a hint to the compiler that we're syncing the + // buffer (I think .-.) + fence(Ordering::SeqCst); + + let read_available = self.rd[self.read_idx].available(); + if !read_available && self.read_idx == self.tail_idx { + // Nothing to do + return None; + } + + let pkt = if read_available { + let pkt = self.buffers[self.read_idx].take(); + let len = (self.rd[self.read_idx].rdes3.get() & EMAC_RDES3_PKTLEN) as usize; + + assert!(pkt.is_some()); + let valid = self.rd[self.read_idx].valid(); + + self.read_idx = (self.read_idx + 1) % N; + if valid { + pkt.map(|p| p.slice(0..len)) + } else { + None + } + } else { + None + }; + + match PacketBox::new(Packet::new()) { + Some(b) => { + let addr = b.as_ptr() as u32; + self.buffers[self.tail_idx].replace(b); + self.rd[self.tail_idx].set_ready(addr); + + // "Preceding reads and writes cannot be moved past subsequent writes." + fence(Ordering::Release); + + // NOTE(unsafe) atomic write + unsafe { + ETH.ethernet_dma() + .dmacrx_dtpr() + .write(|w| w.set_rdt(&self.rd[self.read_idx] as *const _ as u32)); + } + + self.tail_idx = (self.tail_idx + 1) % N; + } + None => {} + } + pkt + } +} + +pub struct DescriptorRing { + pub(crate) tx: TDesRing, + pub(crate) rx: RDesRing, +} + +impl DescriptorRing { + pub const fn new() -> Self { + Self { + tx: TDesRing::new(), + rx: RDesRing::new(), + } + } + + pub fn init(&mut self) { + self.tx.init(); + self.rx.init(); + } +} diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs new file mode 100644 index 00000000..d54c6e85 --- /dev/null +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -0,0 +1,350 @@ +use core::marker::PhantomData; +use core::pin::Pin; +use core::sync::atomic::{fence, Ordering}; + +use embassy::util::{AtomicWaker, Unborrow}; +use embassy_extras::peripheral::{PeripheralMutex, PeripheralState}; +use embassy_extras::unborrow; +use embassy_net::MTU; + +use crate::gpio::sealed::Pin as __GpioPin; +use crate::gpio::AnyPin; +use crate::gpio::Pin as GpioPin; +use crate::interrupt::Interrupt; +use crate::pac::gpio::vals::Ospeedr; +use crate::pac::ETH; +use crate::peripherals; + +mod descriptors; +use descriptors::DescriptorRing; + +/// Station Management Interface (SMI) on an ethernet PHY +pub trait StationManagement { + /// Read a register over SMI. + fn smi_read(&mut self, reg: u8) -> u16; + /// Write a register over SMI. + fn smi_write(&mut self, reg: u8, val: u16); +} + +/// Traits for an Ethernet PHY +pub trait PHY { + /// Reset PHY and wait for it to come out of reset. + fn phy_reset(&mut self); + /// PHY initialisation. + fn phy_init(&mut self); +} + +pub struct Ethernet<'d, T: Instance, const TX: usize, const RX: usize> { + state: PeripheralMutex>, + pins: [AnyPin; 9], +} + +impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX> { + pub fn new( + peri: impl Unborrow + 'd, + interrupt: impl Unborrow + 'd, + ref_clk: impl Unborrow> + 'd, + mdio: impl Unborrow> + 'd, + mdc: impl Unborrow> + 'd, + crs: impl Unborrow> + 'd, + rx_d0: impl Unborrow> + 'd, + rx_d1: impl Unborrow> + 'd, + tx_d0: impl Unborrow> + 'd, + tx_d1: impl Unborrow> + 'd, + tx_en: impl Unborrow> + 'd, + mac_addr: [u8; 6], + ) -> Self { + unborrow!(interrupt, ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en); + + ref_clk.configure(); + mdio.configure(); + mdc.configure(); + crs.configure(); + rx_d0.configure(); + rx_d1.configure(); + tx_d0.configure(); + tx_d1.configure(); + tx_en.configure(); + + let inner = Inner::new(peri); + let state = PeripheralMutex::new(inner, interrupt); + + // NOTE(unsafe) We have exclusive access to the registers + unsafe { + let dma = ETH.ethernet_dma(); + let mac = ETH.ethernet_mac(); + let mtl = ETH.ethernet_mtl(); + + // Reset and wait + dma.dmamr().modify(|w| w.set_swr(true)); + while dma.dmamr().read().swr() {} + + // 200 MHz ? + mac.mac1ustcr().modify(|w| w.set_tic_1us_cntr(200 - 1)); + + mac.maccr().modify(|w| { + w.set_ipg(0b000); // 96 bit times + w.set_acs(true); + w.set_fes(true); + w.set_dm(true); + // TODO: Carrier sense ? ECRSFD + }); + + mac.maca0lr().write(|w| { + w.set_addrlo( + u32::from(mac_addr[0]) + | (u32::from(mac_addr[1]) << 8) + | (u32::from(mac_addr[2]) << 16) + | (u32::from(mac_addr[3]) << 24), + ) + }); + mac.maca0hr() + .modify(|w| w.set_addrhi(u16::from(mac_addr[4]) | (u16::from(mac_addr[5]) << 8))); + + // TODO: Enable filtering once we get the basics working + mac.macpfr().modify(|w| w.set_ra(true)); + mac.macqtx_fcr().modify(|w| w.set_pt(0x100)); + + mtl.mtlrx_qomr().modify(|w| w.set_rsf(true)); + mtl.mtltx_qomr().modify(|w| w.set_tsf(true)); + + // TODO: Address aligned beats plus fixed burst ? + dma.dmactx_cr().modify(|w| w.set_txpbl(1)); // 32 ? + dma.dmacrx_cr().modify(|w| { + w.set_rxpbl(1); // 32 ? + w.set_rbsz(MTU as u16); + }); + } + + let pins = [ + ref_clk.degrade(), + mdio.degrade(), + mdc.degrade(), + crs.degrade(), + rx_d0.degrade(), + rx_d1.degrade(), + tx_d0.degrade(), + tx_d1.degrade(), + tx_en.degrade(), + ]; + + Self { state, pins } + } + + pub fn init(self: Pin<&mut Self>) { + // NOTE(unsafe) We won't move this + let this = unsafe { self.get_unchecked_mut() }; + let mutex = unsafe { Pin::new_unchecked(&mut this.state) }; + + mutex.with(|s, _| { + s.desc_ring.init(); + + fence(Ordering::SeqCst); + + unsafe { + let mac = ETH.ethernet_mac(); + let mtl = ETH.ethernet_mtl(); + let dma = ETH.ethernet_dma(); + + mac.maccr().modify(|w| { + w.set_re(true); + w.set_te(true); + }); + mtl.mtltx_qomr().modify(|w| w.set_ftq(true)); + + dma.dmactx_cr().modify(|w| w.set_st(true)); + dma.dmacrx_cr().modify(|w| w.set_sr(true)); + + // Enable interrupts + dma.dmacier().modify(|w| { + w.set_nie(true); + w.set_rie(true); + w.set_tie(true); + }); + } + }); + } +} + +impl<'d, T: Instance, const TX: usize, const RX: usize> Drop for Ethernet<'d, T, TX, RX> { + fn drop(&mut self) { + for pin in self.pins.iter_mut() { + // NOTE(unsafe) Exclusive access to the regs + critical_section::with(|_| unsafe { + pin.set_as_analog(); + pin.block() + .ospeedr() + .modify(|w| w.set_ospeedr(pin.pin() as usize, Ospeedr::LOWSPEED)); + }) + } + } +} + +//---------------------------------------------------------------------- + +struct Inner<'d, T: Instance, const TX: usize, const RX: usize> { + _peri: PhantomData<&'d mut T>, + desc_ring: DescriptorRing, +} + +impl<'d, T: Instance, const TX: usize, const RX: usize> Inner<'d, T, TX, RX> { + pub fn new(_peri: impl Unborrow + 'd) -> Self { + Self { + _peri: PhantomData, + desc_ring: DescriptorRing::new(), + } + } +} + +impl<'d, T: Instance, const TX: usize, const RX: usize> PeripheralState for Inner<'d, T, TX, RX> { + type Interrupt = T::Interrupt; + + fn on_interrupt(&mut self) { + unwrap!(self.desc_ring.tx.on_interrupt()); + self.desc_ring.rx.on_interrupt(); + + T::state().wake(); + + // TODO: Check and clear more flags + unsafe { + let dma = ETH.ethernet_dma(); + + dma.dmacsr().modify(|w| { + w.set_ti(false); + w.set_ri(false); + }); + // Delay two peripheral's clock + dma.dmacsr().read(); + dma.dmacsr().read(); + } + } +} + +mod sealed { + use super::*; + + pub trait Instance { + type Interrupt: Interrupt; + + fn state() -> &'static AtomicWaker; + } + + pub trait RefClkPin: GpioPin { + fn configure(&mut self); + } + + pub trait MDIOPin: GpioPin { + fn configure(&mut self); + } + + pub trait MDCPin: GpioPin { + fn configure(&mut self); + } + + pub trait CRSPin: GpioPin { + fn configure(&mut self); + } + + pub trait RXD0Pin: GpioPin { + fn configure(&mut self); + } + + pub trait RXD1Pin: GpioPin { + fn configure(&mut self); + } + + pub trait TXD0Pin: GpioPin { + fn configure(&mut self); + } + + pub trait TXD1Pin: GpioPin { + fn configure(&mut self); + } + + pub trait TXEnPin: GpioPin { + fn configure(&mut self); + } +} + +pub trait Instance: sealed::Instance + 'static {} + +pub trait RefClkPin: sealed::RefClkPin + 'static {} + +pub trait MDIOPin: sealed::MDIOPin + 'static {} + +pub trait MDCPin: sealed::MDCPin + 'static {} + +pub trait CRSPin: sealed::CRSPin + 'static {} + +pub trait RXD0Pin: sealed::RXD0Pin + 'static {} + +pub trait RXD1Pin: sealed::RXD1Pin + 'static {} + +pub trait TXD0Pin: sealed::TXD0Pin + 'static {} + +pub trait TXD1Pin: sealed::TXD1Pin + 'static {} + +pub trait TXEnPin: sealed::TXEnPin + 'static {} + +crate::pac::peripherals!( + (eth, $inst:ident) => { + impl sealed::Instance for peripherals::$inst { + type Interrupt = crate::interrupt::$inst; + + fn state() -> &'static AtomicWaker { + static WAKER: AtomicWaker = AtomicWaker::new(); + &WAKER + } + } + + impl Instance for peripherals::$inst {} + }; +); + +macro_rules! impl_pin { + ($inst:ident, $pin:ident, $signal:ident, $af:expr) => { + impl sealed::$signal for peripherals::$pin { + fn configure(&mut self) { + // NOTE(unsafe) Exclusive access to the registers + critical_section::with(|_| unsafe { + self.set_as_af($af); + self.block() + .ospeedr() + .modify(|w| w.set_ospeedr(self.pin() as usize, Ospeedr::VERYHIGHSPEED)); + }) + } + } + + impl $signal for peripherals::$pin {} + }; +} + +crate::pac::peripheral_pins!( + ($inst:ident, eth, ETH, $pin:ident, REF_CLK, $af:expr) => { + impl_pin!($inst, $pin, RefClkPin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, MDIO, $af:expr) => { + impl_pin!($inst, $pin, MDIOPin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, MDC, $af:expr) => { + impl_pin!($inst, $pin, MDCPin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, CRS_DV, $af:expr) => { + impl_pin!($inst, $pin, CRSPin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, RXD0, $af:expr) => { + impl_pin!($inst, $pin, RXD0Pin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, RXD1, $af:expr) => { + impl_pin!($inst, $pin, RXD1Pin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, TXD0, $af:expr) => { + impl_pin!($inst, $pin, TXD0Pin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, TXD1, $af:expr) => { + impl_pin!($inst, $pin, TXD1Pin, $af); + }; + ($inst:ident, eth, ETH, $pin:ident, TX_EN, $af:expr) => { + impl_pin!($inst, $pin, TXEnPin, $af); + }; +); diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index 6a08fc58..b99751e6 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -29,6 +29,8 @@ pub mod clock; pub mod dac; #[cfg(dma)] pub mod dma; +#[cfg(eth)] +pub mod eth; #[cfg(i2c)] pub mod i2c; #[cfg(pwr)] From 4cffa200bd976fd415e3419426f5029b2c72cfd2 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Thu, 10 Jun 2021 02:38:59 -0300 Subject: [PATCH 02/15] eth: Add lan8742a PHY --- embassy-stm32/src/eth/lan8742a.rs | 103 ++++++++++++++++++++++++++++++ embassy-stm32/src/eth/mod.rs | 27 ++++++++ embassy-stm32/src/eth/v2/mod.rs | 94 +++++++++++++++++++++------ 3 files changed, 204 insertions(+), 20 deletions(-) create mode 100644 embassy-stm32/src/eth/lan8742a.rs diff --git a/embassy-stm32/src/eth/lan8742a.rs b/embassy-stm32/src/eth/lan8742a.rs new file mode 100644 index 00000000..74d0ca5d --- /dev/null +++ b/embassy-stm32/src/eth/lan8742a.rs @@ -0,0 +1,103 @@ +//! SMSC LAN8742A Ethernet PHY + +use super::{StationManagement, PHY}; + +#[allow(dead_code)] +mod phy_consts { + pub const PHY_REG_BCR: u8 = 0x00; + pub const PHY_REG_BSR: u8 = 0x01; + pub const PHY_REG_ID1: u8 = 0x02; + pub const PHY_REG_ID2: u8 = 0x03; + pub const PHY_REG_ANTX: u8 = 0x04; + pub const PHY_REG_ANRX: u8 = 0x05; + pub const PHY_REG_ANEXP: u8 = 0x06; + pub const PHY_REG_ANNPTX: u8 = 0x07; + pub const PHY_REG_ANNPRX: u8 = 0x08; + pub const PHY_REG_SSR: u8 = 0x1F; // Special Status Register + pub const PHY_REG_CTL: u8 = 0x0D; // Ethernet PHY Register Control + pub const PHY_REG_ADDAR: u8 = 0x0E; // Ethernet PHY Address or Data + + pub const PHY_REG_WUCSR: u16 = 0x8010; + + pub const PHY_REG_BCR_COLTEST: u16 = 1 << 7; + pub const PHY_REG_BCR_FD: u16 = 1 << 8; + pub const PHY_REG_BCR_ANRST: u16 = 1 << 9; + pub const PHY_REG_BCR_ISOLATE: u16 = 1 << 10; + pub const PHY_REG_BCR_POWERDN: u16 = 1 << 11; + pub const PHY_REG_BCR_AN: u16 = 1 << 12; + pub const PHY_REG_BCR_100M: u16 = 1 << 13; + pub const PHY_REG_BCR_LOOPBACK: u16 = 1 << 14; + pub const PHY_REG_BCR_RESET: u16 = 1 << 15; + + pub const PHY_REG_BSR_JABBER: u16 = 1 << 1; + pub const PHY_REG_BSR_UP: u16 = 1 << 2; + pub const PHY_REG_BSR_FAULT: u16 = 1 << 4; + pub const PHY_REG_BSR_ANDONE: u16 = 1 << 5; + + pub const PHY_REG_SSR_ANDONE: u16 = 1 << 12; + pub const PHY_REG_SSR_SPEED: u16 = 0b111 << 2; + pub const PHY_REG_SSR_10BASE_HD: u16 = 0b001 << 2; + pub const PHY_REG_SSR_10BASE_FD: u16 = 0b101 << 2; + pub const PHY_REG_SSR_100BASE_HD: u16 = 0b010 << 2; + pub const PHY_REG_SSR_100BASE_FD: u16 = 0b110 << 2; +} +use self::phy_consts::*; + +/// SMSC LAN8742A Ethernet PHY +pub struct LAN8742A; + +unsafe impl PHY for LAN8742A { + /// Reset PHY and wait for it to come out of reset. + fn phy_reset(sm: &mut S) { + sm.smi_write(PHY_REG_BCR, PHY_REG_BCR_RESET); + while sm.smi_read(PHY_REG_BCR) & PHY_REG_BCR_RESET == PHY_REG_BCR_RESET {} + } + + /// PHY initialisation. + fn phy_init(sm: &mut S) { + // Clear WU CSR + Self::smi_write_ext(sm, PHY_REG_WUCSR, 0); + + // Enable auto-negotiation + sm.smi_write( + PHY_REG_BCR, + PHY_REG_BCR_AN | PHY_REG_BCR_ANRST | PHY_REG_BCR_100M, + ); + } + + fn poll_link(sm: &mut S) -> bool { + let bsr = sm.smi_read(PHY_REG_BSR); + let ssr = sm.smi_read(PHY_REG_SSR); + + // No link without autonegotiate + if bsr & PHY_REG_BSR_ANDONE == 0 { + return false; + } + // No link if link is down + if bsr & PHY_REG_BSR_UP == 0 { + return false; + } + // No link if autonegotiate incomplete + if ssr & PHY_REG_SSR_ANDONE == 0 { + return false; + } + // No link if other side isn't 100Mbps full duplex + if ssr & PHY_REG_SSR_SPEED != PHY_REG_SSR_100BASE_FD { + return false; + } + + // Got link + true + } +} + +/// Public functions for the LAN8742A +impl LAN8742A { + // Writes a value to an extended PHY register in MMD address space + fn smi_write_ext(sm: &mut S, reg_addr: u16, reg_data: u16) { + sm.smi_write(PHY_REG_CTL, 0x0003); // set address + sm.smi_write(PHY_REG_ADDAR, reg_addr); + sm.smi_write(PHY_REG_CTL, 0x4003); // set data + sm.smi_write(PHY_REG_ADDAR, reg_data); + } +} diff --git a/embassy-stm32/src/eth/mod.rs b/embassy-stm32/src/eth/mod.rs index 8791e155..e41ebf4d 100644 --- a/embassy-stm32/src/eth/mod.rs +++ b/embassy-stm32/src/eth/mod.rs @@ -3,5 +3,32 @@ #[cfg_attr(eth_v1, path = "v1.rs")] #[cfg_attr(eth_v2, path = "v2/mod.rs")] mod _version; +pub mod lan8742a; pub use _version::*; + +/// Station Management Interface (SMI) on an ethernet PHY +/// +/// # Safety +/// +/// The methods cannot move out of self +pub unsafe trait StationManagement { + /// Read a register over SMI. + fn smi_read(&mut self, reg: u8) -> u16; + /// Write a register over SMI. + fn smi_write(&mut self, reg: u8, val: u16); +} + +/// Traits for an Ethernet PHY +/// +/// # Safety +/// +/// The methods cannot move S +pub unsafe trait PHY { + /// Reset PHY and wait for it to come out of reset. + fn phy_reset(sm: &mut S); + /// PHY initialisation. + fn phy_init(sm: &mut S); + /// Poll link to see if it is up and FD with 100Mbps + fn poll_link(sm: &mut S) -> bool; +} diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index d54c6e85..67d722d1 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -14,32 +14,21 @@ use crate::interrupt::Interrupt; use crate::pac::gpio::vals::Ospeedr; use crate::pac::ETH; use crate::peripherals; +use crate::time::Hertz; mod descriptors; +use super::{StationManagement, PHY}; use descriptors::DescriptorRing; -/// Station Management Interface (SMI) on an ethernet PHY -pub trait StationManagement { - /// Read a register over SMI. - fn smi_read(&mut self, reg: u8) -> u16; - /// Write a register over SMI. - fn smi_write(&mut self, reg: u8, val: u16); -} - -/// Traits for an Ethernet PHY -pub trait PHY { - /// Reset PHY and wait for it to come out of reset. - fn phy_reset(&mut self); - /// PHY initialisation. - fn phy_init(&mut self); -} - -pub struct Ethernet<'d, T: Instance, const TX: usize, const RX: usize> { +pub struct Ethernet<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> { state: PeripheralMutex>, pins: [AnyPin; 9], + _phy: P, + clock_range: u8, + phy_addr: u8, } -impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX> { +impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, T, P, TX, RX> { pub fn new( peri: impl Unborrow + 'd, interrupt: impl Unborrow + 'd, @@ -52,7 +41,10 @@ impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX> tx_d0: impl Unborrow> + 'd, tx_d1: impl Unborrow> + 'd, tx_en: impl Unborrow> + 'd, + phy: P, mac_addr: [u8; 6], + hclk: Hertz, + phy_addr: u8, ) -> Self { unborrow!(interrupt, ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en); @@ -116,6 +108,20 @@ impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX> }); } + // Set the MDC clock frequency in the range 1MHz - 2.5MHz + let hclk_mhz = hclk.0 / 1_000_000; + let clock_range = match hclk_mhz { + 0..=34 => 2, // Divide by 16 + 35..=59 => 3, // Divide by 26 + 60..=99 => 0, // Divide by 42 + 100..=149 => 1, // Divide by 62 + 150..=249 => 4, // Divide by 102 + 250..=310 => 5, // Divide by 124 + _ => { + panic!("HCLK results in MDC clock > 2.5MHz even for the highest CSR clock divider") + } + }; + let pins = [ ref_clk.degrade(), mdio.degrade(), @@ -128,7 +134,13 @@ impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX> tx_en.degrade(), ]; - Self { state, pins } + Self { + state, + pins, + _phy: phy, + clock_range, + phy_addr, + } } pub fn init(self: Pin<&mut Self>) { @@ -163,10 +175,52 @@ impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX> }); } }); + P::phy_reset(this); + P::phy_init(this); } } -impl<'d, T: Instance, const TX: usize, const RX: usize> Drop for Ethernet<'d, T, TX, RX> { +unsafe impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> StationManagement + for Ethernet<'d, T, P, TX, RX> +{ + fn smi_read(&mut self, reg: u8) -> u16 { + // NOTE(unsafe) These registers aren't used in the interrupt and we have `&mut self` + unsafe { + let mac = ETH.ethernet_mac(); + + mac.macmdioar().modify(|w| { + w.set_pa(self.phy_addr); + w.set_rda(reg); + w.set_goc(0b11); // read + w.set_cr(self.clock_range); + w.set_mb(true); + }); + while mac.macmdioar().read().mb() {} + mac.macmdiodr().read().md() + } + } + + fn smi_write(&mut self, reg: u8, val: u16) { + // NOTE(unsafe) These registers aren't used in the interrupt and we have `&mut self` + unsafe { + let mac = ETH.ethernet_mac(); + + mac.macmdiodr().write(|w| w.set_md(val)); + mac.macmdioar().modify(|w| { + w.set_pa(self.phy_addr); + w.set_rda(reg); + w.set_goc(0b01); // write + w.set_cr(self.clock_range); + w.set_mb(true); + }); + while mac.macmdioar().read().mb() {} + } + } +} + +impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Drop + for Ethernet<'d, T, P, TX, RX> +{ fn drop(&mut self) { for pin in self.pins.iter_mut() { // NOTE(unsafe) Exclusive access to the regs From 05a239faf6472cf1249404ac034bb527c1a941d3 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Thu, 10 Jun 2021 23:22:34 -0300 Subject: [PATCH 03/15] eth-v2: Implement embassy-net's Device Trait and fix Drop --- embassy-stm32/src/eth/v2/mod.rs | 89 ++++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index 67d722d1..7debd5a1 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -1,11 +1,12 @@ use core::marker::PhantomData; use core::pin::Pin; use core::sync::atomic::{fence, Ordering}; +use core::task::Waker; use embassy::util::{AtomicWaker, Unborrow}; use embassy_extras::peripheral::{PeripheralMutex, PeripheralState}; use embassy_extras::unborrow; -use embassy_net::MTU; +use embassy_net::{Device, DeviceCapabilities, LinkState, PacketBuf, MTU}; use crate::gpio::sealed::Pin as __GpioPin; use crate::gpio::AnyPin; @@ -26,6 +27,7 @@ pub struct Ethernet<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> { _phy: P, clock_range: u8, phy_addr: u8, + mac_addr: [u8; 6], } impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, T, P, TX, RX> { @@ -140,6 +142,7 @@ impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, T, _phy: phy, clock_range, phy_addr, + mac_addr, } } @@ -218,10 +221,94 @@ unsafe impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> StationMa } } +impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Device + for Pin<&mut Ethernet<'d, T, P, TX, RX>> +{ + fn is_transmit_ready(&mut self) -> bool { + // NOTE(unsafe) We won't move out of self + let this = unsafe { self.as_mut().get_unchecked_mut() }; + let mutex = unsafe { Pin::new_unchecked(&mut this.state) }; + + mutex.with(|s, _| s.desc_ring.tx.available()) + } + + fn transmit(&mut self, pkt: PacketBuf) { + // NOTE(unsafe) We won't move out of self + let this = unsafe { self.as_mut().get_unchecked_mut() }; + let mutex = unsafe { Pin::new_unchecked(&mut this.state) }; + + mutex.with(|s, _| unwrap!(s.desc_ring.tx.transmit(pkt))); + } + + fn receive(&mut self) -> Option { + // NOTE(unsafe) We won't move out of self + let this = unsafe { self.as_mut().get_unchecked_mut() }; + let mutex = unsafe { Pin::new_unchecked(&mut this.state) }; + + mutex.with(|s, _| s.desc_ring.rx.pop_packet()) + } + + fn register_waker(&mut self, waker: &Waker) { + T::state().register(waker); + } + + fn capabilities(&mut self) -> DeviceCapabilities { + let mut caps = DeviceCapabilities::default(); + caps.max_transmission_unit = MTU; + caps.max_burst_size = Some(TX.min(RX)); + caps + } + + fn link_state(&mut self) -> LinkState { + // NOTE(unsafe) We won't move out of self + let this = unsafe { self.as_mut().get_unchecked_mut() }; + + if P::poll_link(this) { + LinkState::Up + } else { + LinkState::Down + } + } + + fn ethernet_address(&mut self) -> [u8; 6] { + // NOTE(unsafe) We won't move out of self + let this = unsafe { self.as_mut().get_unchecked_mut() }; + + this.mac_addr + } +} + impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Drop for Ethernet<'d, T, P, TX, RX> { fn drop(&mut self) { + // NOTE(unsafe) We have `&mut self` and the interrupt doesn't use this registers + unsafe { + let dma = ETH.ethernet_dma(); + let mac = ETH.ethernet_mac(); + let mtl = ETH.ethernet_mtl(); + + // Disable the TX DMA and wait for any previous transmissions to be completed + dma.dmactx_cr().modify(|w| w.set_st(false)); + while { + let txqueue = mtl.mtltx_qdr().read(); + txqueue.trcsts() == 0b01 || txqueue.txqsts() + } {} + + // Disable MAC transmitter and receiver + mac.maccr().modify(|w| { + w.set_re(false); + w.set_te(false); + }); + + // Wait for previous receiver transfers to be completed and then disable the RX DMA + while { + let rxqueue = mtl.mtlrx_qdr().read(); + rxqueue.rxqsts() != 0b00 || rxqueue.prxq() != 0 + } {} + dma.dmacrx_cr().modify(|w| w.set_sr(false)); + } + for pin in self.pins.iter_mut() { // NOTE(unsafe) Exclusive access to the regs critical_section::with(|_| unsafe { From e039c7c42c9e9113f512f5406d68b283c329f4f8 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Thu, 10 Jun 2021 23:33:31 -0300 Subject: [PATCH 04/15] eth-v2: Remove Instance trait --- embassy-stm32/src/eth/v2/mod.rs | 140 +++++++++++++------------------- 1 file changed, 57 insertions(+), 83 deletions(-) diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index 7debd5a1..8a17ac00 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -11,7 +11,6 @@ use embassy_net::{Device, DeviceCapabilities, LinkState, PacketBuf, MTU}; use crate::gpio::sealed::Pin as __GpioPin; use crate::gpio::AnyPin; use crate::gpio::Pin as GpioPin; -use crate::interrupt::Interrupt; use crate::pac::gpio::vals::Ospeedr; use crate::pac::ETH; use crate::peripherals; @@ -21,8 +20,8 @@ mod descriptors; use super::{StationManagement, PHY}; use descriptors::DescriptorRing; -pub struct Ethernet<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> { - state: PeripheralMutex>, +pub struct Ethernet<'d, P: PHY, const TX: usize, const RX: usize> { + state: PeripheralMutex>, pins: [AnyPin; 9], _phy: P, clock_range: u8, @@ -30,19 +29,19 @@ pub struct Ethernet<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> { mac_addr: [u8; 6], } -impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, T, P, TX, RX> { +impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { pub fn new( - peri: impl Unborrow + 'd, - interrupt: impl Unborrow + 'd, - ref_clk: impl Unborrow> + 'd, - mdio: impl Unborrow> + 'd, - mdc: impl Unborrow> + 'd, - crs: impl Unborrow> + 'd, - rx_d0: impl Unborrow> + 'd, - rx_d1: impl Unborrow> + 'd, - tx_d0: impl Unborrow> + 'd, - tx_d1: impl Unborrow> + 'd, - tx_en: impl Unborrow> + 'd, + peri: impl Unborrow + 'd, + interrupt: impl Unborrow + 'd, + ref_clk: impl Unborrow + 'd, + mdio: impl Unborrow + 'd, + mdc: impl Unborrow + 'd, + crs: impl Unborrow + 'd, + rx_d0: impl Unborrow + 'd, + rx_d1: impl Unborrow + 'd, + tx_d0: impl Unborrow + 'd, + tx_d1: impl Unborrow + 'd, + tx_en: impl Unborrow + 'd, phy: P, mac_addr: [u8; 6], hclk: Hertz, @@ -183,8 +182,8 @@ impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, T, } } -unsafe impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> StationManagement - for Ethernet<'d, T, P, TX, RX> +unsafe impl<'d, P: PHY, const TX: usize, const RX: usize> StationManagement + for Ethernet<'d, P, TX, RX> { fn smi_read(&mut self, reg: u8) -> u16 { // NOTE(unsafe) These registers aren't used in the interrupt and we have `&mut self` @@ -221,9 +220,7 @@ unsafe impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> StationMa } } -impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Device - for Pin<&mut Ethernet<'d, T, P, TX, RX>> -{ +impl<'d, P: PHY, const TX: usize, const RX: usize> Device for Pin<&mut Ethernet<'d, P, TX, RX>> { fn is_transmit_ready(&mut self) -> bool { // NOTE(unsafe) We won't move out of self let this = unsafe { self.as_mut().get_unchecked_mut() }; @@ -249,7 +246,7 @@ impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Device } fn register_waker(&mut self, waker: &Waker) { - T::state().register(waker); + WAKER.register(waker); } fn capabilities(&mut self) -> DeviceCapabilities { @@ -278,9 +275,7 @@ impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Device } } -impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Drop - for Ethernet<'d, T, P, TX, RX> -{ +impl<'d, P: PHY, const TX: usize, const RX: usize> Drop for Ethernet<'d, P, TX, RX> { fn drop(&mut self) { // NOTE(unsafe) We have `&mut self` and the interrupt doesn't use this registers unsafe { @@ -323,13 +318,13 @@ impl<'d, T: Instance, P: PHY, const TX: usize, const RX: usize> Drop //---------------------------------------------------------------------- -struct Inner<'d, T: Instance, const TX: usize, const RX: usize> { - _peri: PhantomData<&'d mut T>, +struct Inner<'d, const TX: usize, const RX: usize> { + _peri: PhantomData<&'d mut peripherals::ETH>, desc_ring: DescriptorRing, } -impl<'d, T: Instance, const TX: usize, const RX: usize> Inner<'d, T, TX, RX> { - pub fn new(_peri: impl Unborrow + 'd) -> Self { +impl<'d, const TX: usize, const RX: usize> Inner<'d, TX, RX> { + pub fn new(_peri: impl Unborrow + 'd) -> Self { Self { _peri: PhantomData, desc_ring: DescriptorRing::new(), @@ -337,14 +332,14 @@ impl<'d, T: Instance, const TX: usize, const RX: usize> Inner<'d, T, TX, RX> { } } -impl<'d, T: Instance, const TX: usize, const RX: usize> PeripheralState for Inner<'d, T, TX, RX> { - type Interrupt = T::Interrupt; +impl<'d, const TX: usize, const RX: usize> PeripheralState for Inner<'d, TX, RX> { + type Interrupt = crate::interrupt::ETH; fn on_interrupt(&mut self) { unwrap!(self.desc_ring.tx.on_interrupt()); self.desc_ring.rx.on_interrupt(); - T::state().wake(); + WAKER.wake(); // TODO: Check and clear more flags unsafe { @@ -364,87 +359,66 @@ impl<'d, T: Instance, const TX: usize, const RX: usize> PeripheralState for Inne mod sealed { use super::*; - pub trait Instance { - type Interrupt: Interrupt; - - fn state() -> &'static AtomicWaker; - } - - pub trait RefClkPin: GpioPin { + pub trait RefClkPin: GpioPin { fn configure(&mut self); } - pub trait MDIOPin: GpioPin { + pub trait MDIOPin: GpioPin { fn configure(&mut self); } - pub trait MDCPin: GpioPin { + pub trait MDCPin: GpioPin { fn configure(&mut self); } - pub trait CRSPin: GpioPin { + pub trait CRSPin: GpioPin { fn configure(&mut self); } - pub trait RXD0Pin: GpioPin { + pub trait RXD0Pin: GpioPin { fn configure(&mut self); } - pub trait RXD1Pin: GpioPin { + pub trait RXD1Pin: GpioPin { fn configure(&mut self); } - pub trait TXD0Pin: GpioPin { + pub trait TXD0Pin: GpioPin { fn configure(&mut self); } - pub trait TXD1Pin: GpioPin { + pub trait TXD1Pin: GpioPin { fn configure(&mut self); } - pub trait TXEnPin: GpioPin { + pub trait TXEnPin: GpioPin { fn configure(&mut self); } } -pub trait Instance: sealed::Instance + 'static {} +pub trait RefClkPin: sealed::RefClkPin + 'static {} -pub trait RefClkPin: sealed::RefClkPin + 'static {} +pub trait MDIOPin: sealed::MDIOPin + 'static {} -pub trait MDIOPin: sealed::MDIOPin + 'static {} +pub trait MDCPin: sealed::MDCPin + 'static {} -pub trait MDCPin: sealed::MDCPin + 'static {} +pub trait CRSPin: sealed::CRSPin + 'static {} -pub trait CRSPin: sealed::CRSPin + 'static {} +pub trait RXD0Pin: sealed::RXD0Pin + 'static {} -pub trait RXD0Pin: sealed::RXD0Pin + 'static {} +pub trait RXD1Pin: sealed::RXD1Pin + 'static {} -pub trait RXD1Pin: sealed::RXD1Pin + 'static {} +pub trait TXD0Pin: sealed::TXD0Pin + 'static {} -pub trait TXD0Pin: sealed::TXD0Pin + 'static {} +pub trait TXD1Pin: sealed::TXD1Pin + 'static {} -pub trait TXD1Pin: sealed::TXD1Pin + 'static {} +pub trait TXEnPin: sealed::TXEnPin + 'static {} -pub trait TXEnPin: sealed::TXEnPin + 'static {} - -crate::pac::peripherals!( - (eth, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { - type Interrupt = crate::interrupt::$inst; - - fn state() -> &'static AtomicWaker { - static WAKER: AtomicWaker = AtomicWaker::new(); - &WAKER - } - } - - impl Instance for peripherals::$inst {} - }; -); +static WAKER: AtomicWaker = AtomicWaker::new(); macro_rules! impl_pin { - ($inst:ident, $pin:ident, $signal:ident, $af:expr) => { - impl sealed::$signal for peripherals::$pin { + ($pin:ident, $signal:ident, $af:expr) => { + impl sealed::$signal for peripherals::$pin { fn configure(&mut self) { // NOTE(unsafe) Exclusive access to the registers critical_section::with(|_| unsafe { @@ -456,36 +430,36 @@ macro_rules! impl_pin { } } - impl $signal for peripherals::$pin {} + impl $signal for peripherals::$pin {} }; } crate::pac::peripheral_pins!( ($inst:ident, eth, ETH, $pin:ident, REF_CLK, $af:expr) => { - impl_pin!($inst, $pin, RefClkPin, $af); + impl_pin!($pin, RefClkPin, $af); }; ($inst:ident, eth, ETH, $pin:ident, MDIO, $af:expr) => { - impl_pin!($inst, $pin, MDIOPin, $af); + impl_pin!($pin, MDIOPin, $af); }; ($inst:ident, eth, ETH, $pin:ident, MDC, $af:expr) => { - impl_pin!($inst, $pin, MDCPin, $af); + impl_pin!($pin, MDCPin, $af); }; ($inst:ident, eth, ETH, $pin:ident, CRS_DV, $af:expr) => { - impl_pin!($inst, $pin, CRSPin, $af); + impl_pin!($pin, CRSPin, $af); }; ($inst:ident, eth, ETH, $pin:ident, RXD0, $af:expr) => { - impl_pin!($inst, $pin, RXD0Pin, $af); + impl_pin!($pin, RXD0Pin, $af); }; ($inst:ident, eth, ETH, $pin:ident, RXD1, $af:expr) => { - impl_pin!($inst, $pin, RXD1Pin, $af); + impl_pin!($pin, RXD1Pin, $af); }; ($inst:ident, eth, ETH, $pin:ident, TXD0, $af:expr) => { - impl_pin!($inst, $pin, TXD0Pin, $af); + impl_pin!($pin, TXD0Pin, $af); }; ($inst:ident, eth, ETH, $pin:ident, TXD1, $af:expr) => { - impl_pin!($inst, $pin, TXD1Pin, $af); + impl_pin!($pin, TXD1Pin, $af); }; ($inst:ident, eth, ETH, $pin:ident, TX_EN, $af:expr) => { - impl_pin!($inst, $pin, TXEnPin, $af); + impl_pin!($pin, TXEnPin, $af); }; ); From 0c837f07c08dd5d5ea197216b17b6452eddb4cb3 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Thu, 10 Jun 2021 23:42:20 -0300 Subject: [PATCH 05/15] eth-v2: Enable clocks in new --- embassy-stm32/src/eth/v2/mod.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index 8a17ac00..a35f693f 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -12,7 +12,7 @@ use crate::gpio::sealed::Pin as __GpioPin; use crate::gpio::AnyPin; use crate::gpio::Pin as GpioPin; use crate::pac::gpio::vals::Ospeedr; -use crate::pac::ETH; +use crate::pac::{ETH, RCC, SYSCFG}; use crate::peripherals; use crate::time::Hertz; @@ -49,6 +49,20 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { ) -> Self { unborrow!(interrupt, ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en); + // Enable the necessary Clocks + // NOTE(unsafe) We have exclusive access to the registers + critical_section::with(|_| unsafe { + RCC.apb4enr().modify(|w| w.set_syscfgen(true)); + RCC.ahb1enr().modify(|w| { + w.set_eth1macen(true); + w.set_eth1txen(true); + w.set_eth1rxen(true); + }); + + // RMII + SYSCFG.pmcr().modify(|w| w.set_epis(0b100)); + }); + ref_clk.configure(); mdio.configure(); mdc.configure(); From 54ad2a41f1ee256328c03440e8767f17c0758ec5 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Fri, 11 Jun 2021 01:43:28 -0300 Subject: [PATCH 06/15] eth-v2: Work around missing AF for REF_CLK --- embassy-stm32/src/eth/v2/mod.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index a35f693f..4c68294b 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -449,31 +449,31 @@ macro_rules! impl_pin { } crate::pac::peripheral_pins!( - ($inst:ident, eth, ETH, $pin:ident, REF_CLK, $af:expr) => { - impl_pin!($pin, RefClkPin, $af); + ($inst:ident, eth, ETH, $pin:ident, REF_CLK) => { + impl_pin!($pin, RefClkPin, 11); }; - ($inst:ident, eth, ETH, $pin:ident, MDIO, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, MDIO, $af:expr) => { impl_pin!($pin, MDIOPin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, MDC, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, MDC, $af:expr) => { impl_pin!($pin, MDCPin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, CRS_DV, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, CRS_DV, $af:expr) => { impl_pin!($pin, CRSPin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, RXD0, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, RXD0, $af:expr) => { impl_pin!($pin, RXD0Pin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, RXD1, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, RXD1, $af:expr) => { impl_pin!($pin, RXD1Pin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, TXD0, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, TXD0, $af:expr) => { impl_pin!($pin, TXD0Pin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, TXD1, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, TXD1, $af:expr) => { impl_pin!($pin, TXD1Pin, $af); }; - ($inst:ident, eth, ETH, $pin:ident, TX_EN, $af:expr) => { + ($inst:ident, eth, ETH, $pin:ident, TX_EN, $af:expr) => { impl_pin!($pin, TXEnPin, $af); }; ); From 0b42e12604bace0839d488b345baea4380583351 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Fri, 11 Jun 2021 02:57:28 -0300 Subject: [PATCH 07/15] eth-v2: Fix off by one bug --- embassy-stm32/src/eth/v2/descriptors.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/embassy-stm32/src/eth/v2/descriptors.rs b/embassy-stm32/src/eth/v2/descriptors.rs index 095eef20..0c004670 100644 --- a/embassy-stm32/src/eth/v2/descriptors.rs +++ b/embassy-stm32/src/eth/v2/descriptors.rs @@ -340,7 +340,7 @@ impl RDesRing { unsafe { ETH.ethernet_dma() .dmacrx_dtpr() - .write(|w| w.set_rdt(&self.rd[self.read_idx] as *const _ as u32)); + .write(|w| w.set_rdt(&self.rd[self.tail_idx] as *const _ as u32)); } self.tail_idx = (self.tail_idx + 1) % N; From 6daa55a897ec886f34ceb9e7e7026c44c109989b Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Fri, 11 Jun 2021 11:51:51 -0300 Subject: [PATCH 08/15] eth-v2: Fix setting the registers for the descriptors Also, the interrupts are set to 1 to clear, the manual could have helped with that one... --- embassy-stm32/src/eth/v2/descriptors.rs | 13 ++++++------- embassy-stm32/src/eth/v2/mod.rs | 16 +++++++++++----- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/embassy-stm32/src/eth/v2/descriptors.rs b/embassy-stm32/src/eth/v2/descriptors.rs index 0c004670..4ce90d1b 100644 --- a/embassy-stm32/src/eth/v2/descriptors.rs +++ b/embassy-stm32/src/eth/v2/descriptors.rs @@ -102,10 +102,10 @@ impl TDesRing { let dma = ETH.ethernet_dma(); dma.dmactx_dlar() - .write(|w| w.set_tdesla(&self.td as *const _ as u32)); + .write(|w| w.0 = &self.td as *const _ as u32); dma.dmactx_rlr().write(|w| w.set_tdrl((N as u16) - 1)); dma.dmactx_dtpr() - .write(|w| w.set_tdt(&self.td[0] as *const _ as u32)); + .write(|w| w.0 = &self.td[0] as *const _ as u32); } } @@ -148,7 +148,7 @@ impl TDesRing { unsafe { ETH.ethernet_dma() .dmactx_dtpr() - .write(|w| w.set_tdt(&self.td[x] as *const _ as u32)); + .write(|w| w.0 = &self.td[x] as *const _ as u32); } self.tdidx = x; Ok(()) @@ -279,8 +279,7 @@ impl RDesRing { unsafe { let dma = ETH.ethernet_dma(); - dma.dmacrx_dlar() - .write(|w| w.set_rdesla(self.rd.as_ptr() as u32)); + dma.dmacrx_dlar().write(|w| w.0 = self.rd.as_ptr() as u32); dma.dmacrx_rlr().write(|w| w.set_rdrl((N as u16) - 1)); // We manage to allocate all buffers, set the index to the last one, that means @@ -290,7 +289,7 @@ impl RDesRing { let tail_ptr = &self.rd[last_index] as *const _ as u32; fence(Ordering::Release); - dma.dmacrx_dtpr().write(|w| w.set_rdt(tail_ptr)); + dma.dmacrx_dtpr().write(|w| w.0 = tail_ptr); } } @@ -340,7 +339,7 @@ impl RDesRing { unsafe { ETH.ethernet_dma() .dmacrx_dtpr() - .write(|w| w.set_rdt(&self.rd[self.tail_idx] as *const _ as u32)); + .write(|w| w.0 = &self.rd[self.tail_idx] as *const _ as u32); } self.tail_idx = (self.tail_idx + 1) % N; diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index 4c68294b..ce5f25eb 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -116,9 +116,13 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { mtl.mtltx_qomr().modify(|w| w.set_tsf(true)); // TODO: Address aligned beats plus fixed burst ? - dma.dmactx_cr().modify(|w| w.set_txpbl(1)); // 32 ? + dma.dmasbmr().modify(|w| { + w.set_aal(true); + w.set_fb(true); + }); + dma.dmactx_cr().modify(|w| w.set_txpbl(32)); // 32 ? dma.dmacrx_cr().modify(|w| { - w.set_rxpbl(1); // 32 ? + w.set_rxpbl(32); // 32 ? w.set_rbsz(MTU as u16); }); } @@ -162,7 +166,8 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { pub fn init(self: Pin<&mut Self>) { // NOTE(unsafe) We won't move this let this = unsafe { self.get_unchecked_mut() }; - let mutex = unsafe { Pin::new_unchecked(&mut this.state) }; + let mut mutex = unsafe { Pin::new_unchecked(&mut this.state) }; + mutex.as_mut().register_interrupt(); mutex.with(|s, _| { s.desc_ring.init(); @@ -360,8 +365,9 @@ impl<'d, const TX: usize, const RX: usize> PeripheralState for Inner<'d, TX, RX> let dma = ETH.ethernet_dma(); dma.dmacsr().modify(|w| { - w.set_ti(false); - w.set_ri(false); + w.set_ti(true); + w.set_ri(true); + w.set_nis(true); }); // Delay two peripheral's clock dma.dmacsr().read(); From ffc19a54d6bebdf90d8bd2a4d42334b36b6d22ee Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Sun, 13 Jun 2021 08:02:38 -0300 Subject: [PATCH 09/15] eth-v2: Fix bug in Rx descriptors and add docs art --- embassy-stm32/src/eth/v2/descriptors.rs | 73 +++++++++++++++++-------- 1 file changed, 49 insertions(+), 24 deletions(-) diff --git a/embassy-stm32/src/eth/v2/descriptors.rs b/embassy-stm32/src/eth/v2/descriptors.rs index 4ce90d1b..23b11857 100644 --- a/embassy-stm32/src/eth/v2/descriptors.rs +++ b/embassy-stm32/src/eth/v2/descriptors.rs @@ -230,11 +230,34 @@ impl RDes { } } +/// Rx ring of descriptors and packets +/// +/// This ring has three major locations that work in lock-step. The DMA will never write to the tail +/// index, so the `read_index` must never pass the tail index. The `next_tail_index` is always 1 +/// slot ahead of the real tail index, and it must never pass the `read_index` or it could overwrite +/// a packet still to be passed to the application. +/// +/// nt can't pass r (no alloc) +/// +---+---+---+---+ Read ok +---+---+---+---+ No Read +---+---+---+---+ +/// | | | | | ------------> | | | | | ------------> | | | | | +/// +---+---+---+---+ Allocation ok +---+---+---+---+ +---+---+---+---+ +/// ^ ^t ^t ^ ^t ^ +/// |r |r |r +/// |nt |nt |nt +/// +/// +/// +---+---+---+---+ Read ok +---+---+---+---+ Can't read +---+---+---+---+ +/// | | | | | ------------> | | | | | ------------> | | | | | +/// +---+---+---+---+ Allocation fail +---+---+---+---+ Allocation ok +---+---+---+---+ +/// ^ ^t ^ ^t ^ ^ ^ ^t +/// |r | |r | | |r +/// |nt |nt |nt +/// pub(crate) struct RDesRing { rd: [RDes; N], buffers: [Option; N], read_idx: usize, - tail_idx: usize, + next_tail_idx: usize, } impl RDesRing { @@ -246,7 +269,7 @@ impl RDesRing { rd: [RDES; N], buffers: [BUFFERS; N], read_idx: 0, - tail_idx: 0, + next_tail_idx: 0, } } @@ -274,7 +297,7 @@ impl RDesRing { self.rd[index].set_ready(addr); last_index = index; } - self.tail_idx = (last_index + 1) % N; + self.next_tail_idx = (last_index + 1) % N; unsafe { let dma = ETH.ethernet_dma(); @@ -294,7 +317,9 @@ impl RDesRing { } pub(crate) fn on_interrupt(&mut self) { - // TODO! + // XXX: Do we need to do anything here ? Maybe we should try to advance the tail ptr, but it + // would soon hit the read ptr anyway, and we will wake smoltcp's stack on the interrupt + // which should try to pop a packet... } pub(crate) fn pop_packet(&mut self) -> Option { @@ -304,12 +329,9 @@ impl RDesRing { fence(Ordering::SeqCst); let read_available = self.rd[self.read_idx].available(); - if !read_available && self.read_idx == self.tail_idx { - // Nothing to do - return None; - } + let tail_index = (self.next_tail_idx + N - 1) % N; - let pkt = if read_available { + let pkt = if read_available && self.read_idx != tail_index { let pkt = self.buffers[self.read_idx].take(); let len = (self.rd[self.read_idx].rdes3.get() & EMAC_RDES3_PKTLEN) as usize; @@ -326,25 +348,28 @@ impl RDesRing { None }; - match PacketBox::new(Packet::new()) { - Some(b) => { - let addr = b.as_ptr() as u32; - self.buffers[self.tail_idx].replace(b); - self.rd[self.tail_idx].set_ready(addr); + // Try to advance the tail_idx + if self.next_tail_idx != self.read_idx { + match PacketBox::new(Packet::new()) { + Some(b) => { + let addr = b.as_ptr() as u32; + self.buffers[self.next_tail_idx].replace(b); + self.rd[self.next_tail_idx].set_ready(addr); - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::Release); + // "Preceding reads and writes cannot be moved past subsequent writes." + fence(Ordering::Release); - // NOTE(unsafe) atomic write - unsafe { - ETH.ethernet_dma() - .dmacrx_dtpr() - .write(|w| w.0 = &self.rd[self.tail_idx] as *const _ as u32); + // NOTE(unsafe) atomic write + unsafe { + ETH.ethernet_dma() + .dmacrx_dtpr() + .write(|w| w.0 = &self.rd[self.next_tail_idx] as *const _ as u32); + } + + self.next_tail_idx = (self.next_tail_idx + 1) % N; } - - self.tail_idx = (self.tail_idx + 1) % N; + None => {} } - None => {} } pkt } From f7e1f262af5ca886e3780d92048c5dc167bef6d9 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Mon, 14 Jun 2021 16:36:48 -0300 Subject: [PATCH 10/15] eth-v2: Enable source address filtering --- embassy-stm32/src/eth/v2/mod.rs | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index ce5f25eb..b9acbf40 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -86,9 +86,6 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { dma.dmamr().modify(|w| w.set_swr(true)); while dma.dmamr().read().swr() {} - // 200 MHz ? - mac.mac1ustcr().modify(|w| w.set_tic_1us_cntr(200 - 1)); - mac.maccr().modify(|w| { w.set_ipg(0b000); // 96 bit times w.set_acs(true); @@ -108,21 +105,15 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { mac.maca0hr() .modify(|w| w.set_addrhi(u16::from(mac_addr[4]) | (u16::from(mac_addr[5]) << 8))); - // TODO: Enable filtering once we get the basics working - mac.macpfr().modify(|w| w.set_ra(true)); + mac.macpfr().modify(|w| w.set_saf(true)); mac.macqtx_fcr().modify(|w| w.set_pt(0x100)); mtl.mtlrx_qomr().modify(|w| w.set_rsf(true)); mtl.mtltx_qomr().modify(|w| w.set_tsf(true)); - // TODO: Address aligned beats plus fixed burst ? - dma.dmasbmr().modify(|w| { - w.set_aal(true); - w.set_fb(true); - }); - dma.dmactx_cr().modify(|w| w.set_txpbl(32)); // 32 ? + dma.dmactx_cr().modify(|w| w.set_txpbl(1)); // 32 ? dma.dmacrx_cr().modify(|w| { - w.set_rxpbl(32); // 32 ? + w.set_rxpbl(1); // 32 ? w.set_rbsz(MTU as u16); }); } From 6cecc6d4b54acf84cc9b22996b178cba97970374 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Mon, 14 Jun 2021 17:20:04 -0300 Subject: [PATCH 11/15] eth-v2: Get hclk frequency from clock singleton --- embassy-stm32/src/eth/v2/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index b9acbf40..a8a361df 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -14,7 +14,6 @@ use crate::gpio::Pin as GpioPin; use crate::pac::gpio::vals::Ospeedr; use crate::pac::{ETH, RCC, SYSCFG}; use crate::peripherals; -use crate::time::Hertz; mod descriptors; use super::{StationManagement, PHY}; @@ -44,7 +43,6 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { tx_en: impl Unborrow + 'd, phy: P, mac_addr: [u8; 6], - hclk: Hertz, phy_addr: u8, ) -> Self { unborrow!(interrupt, ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en); @@ -118,8 +116,11 @@ impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> { }); } - // Set the MDC clock frequency in the range 1MHz - 2.5MHz + // NOTE(unsafe) We got the peripheral singleton, which means that `rcc::init` was called + let hclk = unsafe { crate::rcc::get_freqs().ahb1 }; let hclk_mhz = hclk.0 / 1_000_000; + + // Set the MDC clock frequency in the range 1MHz - 2.5MHz let clock_range = match hclk_mhz { 0..=34 => 2, // Divide by 16 35..=59 => 3, // Divide by 26 From 3396a519389837727c17eae2ebf65d5c93f70551 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Mon, 14 Jun 2021 18:06:12 -0300 Subject: [PATCH 12/15] net: Add features for pool size and remove unwrap on smoltcp device --- embassy-net/Cargo.toml | 6 ++++++ embassy-net/src/device.rs | 2 +- embassy-net/src/packet_pool.rs | 11 +++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/embassy-net/Cargo.toml b/embassy-net/Cargo.toml index c64075b9..0f457176 100644 --- a/embassy-net/Cargo.toml +++ b/embassy-net/Cargo.toml @@ -5,6 +5,7 @@ authors = ["Dario Nieuwenhuis "] edition = "2018" [features] +default = ["pool-4"] std = [] defmt-trace = [] defmt-debug = [] @@ -17,6 +18,11 @@ dhcpv4 = ["medium-ethernet", "smoltcp/socket-dhcpv4"] medium-ethernet = ["smoltcp/medium-ethernet"] medium-ip = ["smoltcp/medium-ip"] +pool-4 = [] +pool-8 = [] +pool-16 = [] +pool-32 = [] + [dependencies] defmt = { version = "0.2.0", optional = true } diff --git a/embassy-net/src/device.rs b/embassy-net/src/device.rs index 5fcb94ac..fc9d0894 100644 --- a/embassy-net/src/device.rs +++ b/embassy-net/src/device.rs @@ -43,8 +43,8 @@ impl<'a> SmolDevice<'a> for DeviceAdapter { type TxToken = TxToken<'a>; fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> { + let tx_pkt = PacketBox::new(Packet::new())?; let rx_pkt = self.device.receive()?; - let tx_pkt = PacketBox::new(Packet::new()).unwrap(); // TODO: not sure about unwrap let rx_token = RxToken { pkt: rx_pkt }; let tx_token = TxToken { device: self.device, diff --git a/embassy-net/src/packet_pool.rs b/embassy-net/src/packet_pool.rs index 0ec88e64..b43ae2eb 100644 --- a/embassy-net/src/packet_pool.rs +++ b/embassy-net/src/packet_pool.rs @@ -4,8 +4,19 @@ use core::ops::{Deref, DerefMut, Range}; use atomic_pool::{pool, Box}; pub const MTU: usize = 1516; + +#[cfg(feature = "pool-4")] pub const PACKET_POOL_SIZE: usize = 4; +#[cfg(feature = "pool-8")] +pub const PACKET_POOL_SIZE: usize = 8; + +#[cfg(feature = "pool-16")] +pub const PACKET_POOL_SIZE: usize = 16; + +#[cfg(feature = "pool-32")] +pub const PACKET_POOL_SIZE: usize = 32; + pool!(pub PacketPool: [Packet; PACKET_POOL_SIZE]); pub type PacketBox = Box; From 598201bff3e6bb07f128d440207c547fe523f195 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Mon, 14 Jun 2021 18:30:11 -0300 Subject: [PATCH 13/15] eth-v2: Make embassy-net optional --- embassy-stm32/Cargo.toml | 3 ++- embassy-stm32/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index cf45fe21..66e2d516 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -10,7 +10,7 @@ embassy = { version = "0.1.0", path = "../embassy" } embassy-macros = { version = "0.1.0", path = "../embassy-macros", features = ["stm32"] } embassy-extras = {version = "0.1.0", path = "../embassy-extras" } embassy-traits = {version = "0.1.0", path = "../embassy-traits" } -embassy-net = { version = "0.1.0", path = "../embassy-net", features = ["tcp", "medium-ip"] } +embassy-net = { version = "0.1.0", path = "../embassy-net", features = ["tcp", "medium-ethernet"], optional = true } defmt = { version = "0.2.0", optional = true } log = { version = "0.4.11", optional = true } @@ -41,6 +41,7 @@ defmt-info = [ ] defmt-warn = [ ] defmt-error = [ ] sdmmc-rs = ["embedded-sdmmc"] +net = ["embassy-net"] # BEGIN GENERATED FEATURES # Generated by gen_features.py. DO NOT EDIT. diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index b99751e6..39ccd54f 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -29,7 +29,7 @@ pub mod clock; pub mod dac; #[cfg(dma)] pub mod dma; -#[cfg(eth)] +#[cfg(all(eth, feature = "net"))] pub mod eth; #[cfg(i2c)] pub mod i2c; From 77546825a15abb8e2fd6956adc4a5f125a0cb8cf Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Tue, 15 Jun 2021 18:12:44 -0300 Subject: [PATCH 14/15] stm32: Make vcell dependency optional --- embassy-stm32/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 66e2d516..6c49f376 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -25,7 +25,7 @@ critical-section = "0.2.1" bare-metal = "1.0.0" atomic-polyfill = "0.1.2" stm32-metapac = { version = "0.1.0", path = "../stm32-metapac", features = ["rt"] } -vcell = "0.1.3" +vcell = { version = "0.1.3", optional = true } cfg-if = "1.0.0" @@ -41,7 +41,7 @@ defmt-info = [ ] defmt-warn = [ ] defmt-error = [ ] sdmmc-rs = ["embedded-sdmmc"] -net = ["embassy-net"] +net = ["embassy-net", "vcell"] # BEGIN GENERATED FEATURES # Generated by gen_features.py. DO NOT EDIT. From 098ce6e7404f10aa6c7dd91260ca6864a92c6a59 Mon Sep 17 00:00:00 2001 From: Thales Fragoso Date: Tue, 15 Jun 2021 18:52:43 -0300 Subject: [PATCH 15/15] stm32h7: Add ethernet example --- embassy-stm32/Cargo.toml | 2 +- examples/stm32h7/.cargo/config | 10 ++ examples/stm32h7/Cargo.toml | 17 +++- examples/stm32h7/build.rs | 21 ++++ examples/stm32h7/memory.x | 2 +- examples/stm32h7/src/bin/eth.rs | 167 ++++++++++++++++++++++++++++++++ 6 files changed, 216 insertions(+), 3 deletions(-) create mode 100644 examples/stm32h7/.cargo/config create mode 100644 examples/stm32h7/build.rs create mode 100644 examples/stm32h7/src/bin/eth.rs diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 6c49f376..8163624f 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -10,7 +10,7 @@ embassy = { version = "0.1.0", path = "../embassy" } embassy-macros = { version = "0.1.0", path = "../embassy-macros", features = ["stm32"] } embassy-extras = {version = "0.1.0", path = "../embassy-extras" } embassy-traits = {version = "0.1.0", path = "../embassy-traits" } -embassy-net = { version = "0.1.0", path = "../embassy-net", features = ["tcp", "medium-ethernet"], optional = true } +embassy-net = { version = "0.1.0", path = "../embassy-net", default-features = false, optional = true } defmt = { version = "0.2.0", optional = true } log = { version = "0.4.11", optional = true } diff --git a/examples/stm32h7/.cargo/config b/examples/stm32h7/.cargo/config new file mode 100644 index 00000000..6b6a9f50 --- /dev/null +++ b/examples/stm32h7/.cargo/config @@ -0,0 +1,10 @@ +[target.thumbv7em-none-eabihf] +runner = 'probe-run --chip STM32H743ZITx' +rustflags = [ + # LLD (shipped with the Rust toolchain) is used as the default linker + "-C", "link-arg=-Tlink.x", + "-C", "link-arg=-Tdefmt.x", +] + +[build] +target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) diff --git a/examples/stm32h7/Cargo.toml b/examples/stm32h7/Cargo.toml index d7288e4c..ebaa4e5d 100644 --- a/examples/stm32h7/Cargo.toml +++ b/examples/stm32h7/Cargo.toml @@ -19,8 +19,11 @@ defmt-error = [] [dependencies] embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-trace"] } embassy-traits = { version = "0.1.0", path = "../../embassy-traits", features = ["defmt"] } -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "defmt-trace", "stm32h743zi"] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "defmt-trace", "stm32h743zi", "net"] } embassy-extras = {version = "0.1.0", path = "../../embassy-extras" } +embassy-net = { path = "../../embassy-net", default-features = false, features = ["defmt-debug", "defmt", "tcp", "medium-ethernet", "pool-16"] } +stm32-metapac = { path = "../../stm32-metapac", features = ["stm32h743zi"] } +embassy-macros = { path = "../../embassy-macros" } stm32h7 = { version = "0.13", features = ["stm32h743"]} stm32h7xx-hal = { version = "0.9.0", features = ["stm32h743"] } @@ -34,6 +37,18 @@ panic-probe = { version = "0.2.0", features= ["print-defmt"] } futures = { version = "0.3.8", default-features = false, features = ["async-await"] } rtt-target = { version = "0.3", features = ["cortex-m"] } heapless = { version = "0.7.1", default-features = false } +rand_core = { version = "0.6.2" } +critical-section = "0.2.1" micromath = "2.0.0" +[dependencies.smoltcp] +git = "https://github.com/smoltcp-rs/smoltcp" +rev = "e4241510337e095b9d21136c5f58b2eaa1b78479" +default-features = false +features = [ + "proto-ipv4", + "socket", + "async", + "defmt", +] diff --git a/examples/stm32h7/build.rs b/examples/stm32h7/build.rs new file mode 100644 index 00000000..555cdf68 --- /dev/null +++ b/examples/stm32h7/build.rs @@ -0,0 +1,21 @@ +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); +} diff --git a/examples/stm32h7/memory.x b/examples/stm32h7/memory.x index 48f58e36..ef9485d1 100644 --- a/examples/stm32h7/memory.x +++ b/examples/stm32h7/memory.x @@ -1,5 +1,5 @@ MEMORY { FLASH : ORIGIN = 0x08000000, LENGTH = 2048K - RAM : ORIGIN = 0x20000000, LENGTH = 128K + RAM : ORIGIN = 0x24000000, LENGTH = 384K } diff --git a/examples/stm32h7/src/bin/eth.rs b/examples/stm32h7/src/bin/eth.rs new file mode 100644 index 00000000..57997da0 --- /dev/null +++ b/examples/stm32h7/src/bin/eth.rs @@ -0,0 +1,167 @@ +#![no_std] +#![no_main] +#![feature(trait_alias)] +#![feature(min_type_alias_impl_trait)] +#![feature(impl_trait_in_bindings)] +#![feature(type_alias_impl_trait)] + +use core::pin::Pin; +use core::sync::atomic::{AtomicUsize, Ordering}; + +use cortex_m_rt::entry; +use defmt::{info, unwrap}; +use defmt_rtt as _; // global logger +use embassy::executor::{Executor, Spawner}; +use embassy::io::AsyncWriteExt; +use embassy::time::{Duration, Timer}; +use embassy::util::Forever; +use embassy_macros::interrupt_take; +use embassy_net::{Config as NetConfig, Ipv4Address, Ipv4Cidr, StaticConfigurator, TcpSocket}; +use embassy_stm32::clock::{Alarm, Clock}; +use embassy_stm32::eth::lan8742a::LAN8742A; +use embassy_stm32::eth::Ethernet; +use embassy_stm32::rcc::{Config as RccConfig, Rcc}; +use embassy_stm32::rng::Random; +use embassy_stm32::time::Hertz; +use embassy_stm32::{interrupt, peripherals, Config}; +use heapless::Vec; +use panic_probe as _; +use peripherals::{RNG, TIM2}; + +defmt::timestamp! {"{=u64}", { + static COUNT: AtomicUsize = AtomicUsize::new(0); + // NOTE(no-CAS) `timestamps` runs with interrupts disabled + let n = COUNT.load(Ordering::Relaxed); + COUNT.store(n + 1, Ordering::Relaxed); + n as u64 + } +} + +#[embassy::task] +async fn main_task( + device: &'static mut Pin<&'static mut Ethernet<'static, LAN8742A, 4, 4>>, + config: &'static mut StaticConfigurator, + spawner: Spawner, +) { + // Init network stack + embassy_net::init(device, config); + + // Launch network task + unwrap!(spawner.spawn(net_task())); + + info!("Network task initialized"); + + // Then we can use it! + let mut rx_buffer = [0; 1024]; + let mut tx_buffer = [0; 1024]; + let mut socket = TcpSocket::new(&mut rx_buffer, &mut tx_buffer); + + socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10))); + + let remote_endpoint = (Ipv4Address::new(192, 168, 0, 10), 8000); + let r = socket.connect(remote_endpoint).await; + if let Err(e) = r { + info!("connect error: {:?}", e); + return; + } + info!("connected!"); + loop { + let r = socket.write_all(b"Hello\n").await; + if let Err(e) = r { + info!("write error: {:?}", e); + return; + } + Timer::after(Duration::from_secs(1)).await; + } +} + +#[embassy::task] +async fn net_task() { + embassy_net::run().await +} + +#[no_mangle] +fn _embassy_rand(buf: &mut [u8]) { + use rand_core::RngCore; + + critical_section::with(|_| unsafe { + unwrap!(RNG_INST.as_mut()).fill_bytes(buf); + }); +} + +static mut RNG_INST: Option> = None; + +static EXECUTOR: Forever = Forever::new(); +static TIMER_RTC: Forever> = Forever::new(); +static ALARM: Forever> = Forever::new(); +static ETH: Forever> = Forever::new(); +static DEVICE: Forever>> = Forever::new(); +static CONFIG: Forever = Forever::new(); + +#[entry] +fn main() -> ! { + use stm32_metapac::RCC; + + info!("Hello World!"); + + info!("Setup RCC..."); + let mut rcc_config = RccConfig::default(); + rcc_config.sys_ck = Some(Hertz(400_000_000)); + rcc_config.pll1.q_ck = Some(Hertz(100_000_000)); + let config = Config::default().rcc(rcc_config); + + let mut p = embassy_stm32::init(config); + + // Constrain and Freeze clock + + let mut rcc = Rcc::new(&mut p.RCC, RccConfig::default()); + rcc.enable_debug_wfe(&mut p.DBGMCU, true); + + unsafe { + RCC.ahb4enr().modify(|w| { + w.set_gpioaen(true); + w.set_gpioben(true); + w.set_gpiocen(true); + w.set_gpioden(true); + w.set_gpioien(true); + }); + } + + let rtc_int = interrupt_take!(TIM2); + let rtc = TIMER_RTC.put(Clock::new(p.TIM2, rtc_int)); + rtc.start(); + let alarm = ALARM.put(rtc.alarm1()); + + unsafe { embassy::time::set_clock(rtc) }; + + let rng = Random::new(p.RNG); + unsafe { + RNG_INST.replace(rng); + } + + let eth_int = interrupt_take!(ETH); + let mac_addr = [0x10; 6]; + let eth = ETH.put(Ethernet::new( + p.ETH, eth_int, p.PA1, p.PA2, p.PC1, p.PA7, p.PC4, p.PC5, p.PB12, p.PB13, p.PB11, LAN8742A, + mac_addr, 1, + )); + + // NOTE(unsafe) This thing is a &'static + let net_device = DEVICE.put(unsafe { Pin::new_unchecked(eth) }); + net_device.as_mut().init(); + + let config = StaticConfigurator::new(NetConfig { + address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 0, 61), 24), + dns_servers: Vec::new(), + gateway: Some(Ipv4Address::new(192, 168, 0, 1)), + }); + + let config = CONFIG.put(config); + + let executor = EXECUTOR.put(Executor::new()); + executor.set_alarm(alarm); + + executor.run(move |spawner| { + unwrap!(spawner.spawn(main_task(net_device, config, spawner))); + }) +}