commit
0d1ae0a01e
@ -5,6 +5,7 @@ authors = ["Dario Nieuwenhuis <dirbaio@dirbaio.net>"]
|
||||
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 }
|
||||
|
@ -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,
|
||||
|
@ -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")]
|
||||
|
@ -3,12 +3,24 @@ use core::ops::{Deref, DerefMut, Range};
|
||||
|
||||
use atomic_pool::{pool, Box};
|
||||
|
||||
pub const MTU: usize = 1514;
|
||||
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<PacketPool>;
|
||||
|
||||
#[repr(align(4))]
|
||||
pub struct Packet(pub [u8; MTU]);
|
||||
|
||||
impl Packet {
|
||||
|
@ -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", default-features = false, optional = true }
|
||||
|
||||
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 = { version = "0.1.3", optional = true }
|
||||
|
||||
cfg-if = "1.0.0"
|
||||
|
||||
[build-dependencies]
|
||||
@ -38,6 +41,7 @@ defmt-info = [ ]
|
||||
defmt-warn = [ ]
|
||||
defmt-error = [ ]
|
||||
sdmmc-rs = ["embedded-sdmmc"]
|
||||
net = ["embassy-net", "vcell"]
|
||||
|
||||
# BEGIN GENERATED FEATURES
|
||||
# Generated by gen_features.py. DO NOT EDIT.
|
||||
|
103
embassy-stm32/src/eth/lan8742a.rs
Normal file
103
embassy-stm32/src/eth/lan8742a.rs
Normal file
@ -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<S: StationManagement>(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<S: StationManagement>(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<S: StationManagement>(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<S: StationManagement>(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);
|
||||
}
|
||||
}
|
34
embassy-stm32/src/eth/mod.rs
Normal file
34
embassy-stm32/src/eth/mod.rs
Normal file
@ -0,0 +1,34 @@
|
||||
#![macro_use]
|
||||
|
||||
#[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<S: StationManagement>(sm: &mut S);
|
||||
/// PHY initialisation.
|
||||
fn phy_init<S: StationManagement>(sm: &mut S);
|
||||
/// Poll link to see if it is up and FD with 100Mbps
|
||||
fn poll_link<S: StationManagement>(sm: &mut S) -> bool;
|
||||
}
|
1
embassy-stm32/src/eth/v1.rs
Normal file
1
embassy-stm32/src/eth/v1.rs
Normal file
@ -0,0 +1 @@
|
||||
|
395
embassy-stm32/src/eth/v2/descriptors.rs
Normal file
395
embassy-stm32/src/eth/v2/descriptors.rs
Normal file
@ -0,0 +1,395 @@
|
||||
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<u32>,
|
||||
tdes1: VolatileCell<u32>,
|
||||
tdes2: VolatileCell<u32>,
|
||||
tdes3: VolatileCell<u32>,
|
||||
}
|
||||
|
||||
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<const N: usize> {
|
||||
td: [TDes; N],
|
||||
buffers: [Option<PacketBuf>; N],
|
||||
tdidx: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> TDesRing<N> {
|
||||
pub const fn new() -> Self {
|
||||
const TDES: TDes = TDes::new();
|
||||
const BUFFERS: Option<PacketBuf> = 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.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.0 = &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.0 = &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<u32>,
|
||||
rdes1: VolatileCell<u32>,
|
||||
rdes2: VolatileCell<u32>,
|
||||
rdes3: VolatileCell<u32>,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<const N: usize> {
|
||||
rd: [RDes; N],
|
||||
buffers: [Option<PacketBox>; N],
|
||||
read_idx: usize,
|
||||
next_tail_idx: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> RDesRing<N> {
|
||||
pub const fn new() -> Self {
|
||||
const RDES: RDes = RDes::new();
|
||||
const BUFFERS: Option<PacketBox> = None;
|
||||
|
||||
Self {
|
||||
rd: [RDES; N],
|
||||
buffers: [BUFFERS; N],
|
||||
read_idx: 0,
|
||||
next_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.next_tail_idx = (last_index + 1) % N;
|
||||
|
||||
unsafe {
|
||||
let dma = ETH.ethernet_dma();
|
||||
|
||||
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
|
||||
// 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.0 = tail_ptr);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_interrupt(&mut self) {
|
||||
// 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<PacketBuf> {
|
||||
// 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();
|
||||
let tail_index = (self.next_tail_idx + N - 1) % N;
|
||||
|
||||
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;
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
// 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);
|
||||
|
||||
// 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;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
pkt
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DescriptorRing<const T: usize, const R: usize> {
|
||||
pub(crate) tx: TDesRing<T>,
|
||||
pub(crate) rx: RDesRing<R>,
|
||||
}
|
||||
|
||||
impl<const T: usize, const R: usize> DescriptorRing<T, R> {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
tx: TDesRing::new(),
|
||||
rx: RDesRing::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(&mut self) {
|
||||
self.tx.init();
|
||||
self.rx.init();
|
||||
}
|
||||
}
|
477
embassy-stm32/src/eth/v2/mod.rs
Normal file
477
embassy-stm32/src/eth/v2/mod.rs
Normal file
@ -0,0 +1,477 @@
|
||||
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::{Device, DeviceCapabilities, LinkState, PacketBuf, MTU};
|
||||
|
||||
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, RCC, SYSCFG};
|
||||
use crate::peripherals;
|
||||
|
||||
mod descriptors;
|
||||
use super::{StationManagement, PHY};
|
||||
use descriptors::DescriptorRing;
|
||||
|
||||
pub struct Ethernet<'d, P: PHY, const TX: usize, const RX: usize> {
|
||||
state: PeripheralMutex<Inner<'d, TX, RX>>,
|
||||
pins: [AnyPin; 9],
|
||||
_phy: P,
|
||||
clock_range: u8,
|
||||
phy_addr: u8,
|
||||
mac_addr: [u8; 6],
|
||||
}
|
||||
|
||||
impl<'d, P: PHY, const TX: usize, const RX: usize> Ethernet<'d, P, TX, RX> {
|
||||
pub fn new(
|
||||
peri: impl Unborrow<Target = peripherals::ETH> + 'd,
|
||||
interrupt: impl Unborrow<Target = crate::interrupt::ETH> + 'd,
|
||||
ref_clk: impl Unborrow<Target = impl RefClkPin> + 'd,
|
||||
mdio: impl Unborrow<Target = impl MDIOPin> + 'd,
|
||||
mdc: impl Unborrow<Target = impl MDCPin> + 'd,
|
||||
crs: impl Unborrow<Target = impl CRSPin> + 'd,
|
||||
rx_d0: impl Unborrow<Target = impl RXD0Pin> + 'd,
|
||||
rx_d1: impl Unborrow<Target = impl RXD1Pin> + 'd,
|
||||
tx_d0: impl Unborrow<Target = impl TXD0Pin> + 'd,
|
||||
tx_d1: impl Unborrow<Target = impl TXD1Pin> + 'd,
|
||||
tx_en: impl Unborrow<Target = impl TXEnPin> + 'd,
|
||||
phy: P,
|
||||
mac_addr: [u8; 6],
|
||||
phy_addr: u8,
|
||||
) -> 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();
|
||||
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() {}
|
||||
|
||||
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)));
|
||||
|
||||
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));
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
// 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
|
||||
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(),
|
||||
mdc.degrade(),
|
||||
crs.degrade(),
|
||||
rx_d0.degrade(),
|
||||
rx_d1.degrade(),
|
||||
tx_d0.degrade(),
|
||||
tx_d1.degrade(),
|
||||
tx_en.degrade(),
|
||||
];
|
||||
|
||||
Self {
|
||||
state,
|
||||
pins,
|
||||
_phy: phy,
|
||||
clock_range,
|
||||
phy_addr,
|
||||
mac_addr,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(self: Pin<&mut Self>) {
|
||||
// NOTE(unsafe) We won't move this
|
||||
let this = unsafe { self.get_unchecked_mut() };
|
||||
let mut mutex = unsafe { Pin::new_unchecked(&mut this.state) };
|
||||
mutex.as_mut().register_interrupt();
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
});
|
||||
P::phy_reset(this);
|
||||
P::phy_init(this);
|
||||
}
|
||||
}
|
||||
|
||||
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`
|
||||
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, 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() };
|
||||
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<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, _| s.desc_ring.rx.pop_packet())
|
||||
}
|
||||
|
||||
fn register_waker(&mut self, waker: &Waker) {
|
||||
WAKER.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, 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 {
|
||||
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 {
|
||||
pin.set_as_analog();
|
||||
pin.block()
|
||||
.ospeedr()
|
||||
.modify(|w| w.set_ospeedr(pin.pin() as usize, Ospeedr::LOWSPEED));
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
struct Inner<'d, const TX: usize, const RX: usize> {
|
||||
_peri: PhantomData<&'d mut peripherals::ETH>,
|
||||
desc_ring: DescriptorRing<TX, RX>,
|
||||
}
|
||||
|
||||
impl<'d, const TX: usize, const RX: usize> Inner<'d, TX, RX> {
|
||||
pub fn new(_peri: impl Unborrow<Target = peripherals::ETH> + 'd) -> Self {
|
||||
Self {
|
||||
_peri: PhantomData,
|
||||
desc_ring: DescriptorRing::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
WAKER.wake();
|
||||
|
||||
// TODO: Check and clear more flags
|
||||
unsafe {
|
||||
let dma = ETH.ethernet_dma();
|
||||
|
||||
dma.dmacsr().modify(|w| {
|
||||
w.set_ti(true);
|
||||
w.set_ri(true);
|
||||
w.set_nis(true);
|
||||
});
|
||||
// Delay two peripheral's clock
|
||||
dma.dmacsr().read();
|
||||
dma.dmacsr().read();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod sealed {
|
||||
use super::*;
|
||||
|
||||
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 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 {}
|
||||
|
||||
static WAKER: AtomicWaker = AtomicWaker::new();
|
||||
|
||||
macro_rules! impl_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 {
|
||||
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) => {
|
||||
impl_pin!($pin, RefClkPin, 11);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, MDIO, $af:expr) => {
|
||||
impl_pin!($pin, MDIOPin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, MDC, $af:expr) => {
|
||||
impl_pin!($pin, MDCPin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, CRS_DV, $af:expr) => {
|
||||
impl_pin!($pin, CRSPin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, RXD0, $af:expr) => {
|
||||
impl_pin!($pin, RXD0Pin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, RXD1, $af:expr) => {
|
||||
impl_pin!($pin, RXD1Pin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, TXD0, $af:expr) => {
|
||||
impl_pin!($pin, TXD0Pin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, TXD1, $af:expr) => {
|
||||
impl_pin!($pin, TXD1Pin, $af);
|
||||
};
|
||||
($inst:ident, eth, ETH, $pin:ident, TX_EN, $af:expr) => {
|
||||
impl_pin!($pin, TXEnPin, $af);
|
||||
};
|
||||
);
|
@ -29,6 +29,8 @@ pub mod clock;
|
||||
pub mod dac;
|
||||
#[cfg(dma)]
|
||||
pub mod dma;
|
||||
#[cfg(all(eth, feature = "net"))]
|
||||
pub mod eth;
|
||||
#[cfg(i2c)]
|
||||
pub mod i2c;
|
||||
#[cfg(pwr)]
|
||||
|
10
examples/stm32h7/.cargo/config
Normal file
10
examples/stm32h7/.cargo/config
Normal file
@ -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)
|
@ -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",
|
||||
]
|
||||
|
21
examples/stm32h7/build.rs
Normal file
21
examples/stm32h7/build.rs
Normal file
@ -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");
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
MEMORY
|
||||
{
|
||||
FLASH : ORIGIN = 0x08000000, LENGTH = 2048K
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 128K
|
||||
RAM : ORIGIN = 0x24000000, LENGTH = 384K
|
||||
}
|
||||
|
167
examples/stm32h7/src/bin/eth.rs
Normal file
167
examples/stm32h7/src/bin/eth.rs
Normal file
@ -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<Random<RNG>> = None;
|
||||
|
||||
static EXECUTOR: Forever<Executor> = Forever::new();
|
||||
static TIMER_RTC: Forever<Clock<TIM2>> = Forever::new();
|
||||
static ALARM: Forever<Alarm<TIM2>> = Forever::new();
|
||||
static ETH: Forever<Ethernet<'static, LAN8742A, 4, 4>> = Forever::new();
|
||||
static DEVICE: Forever<Pin<&'static mut Ethernet<'static, LAN8742A, 4, 4>>> = Forever::new();
|
||||
static CONFIG: Forever<StaticConfigurator> = 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)));
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user