Skip to main content

ch32_hal/eth/v1/
phy.rs

1use core::task::Context;
2
3use super::{Smi, SmiError};
4
5// ============================================================================
6// PHY trait
7// ============================================================================
8
9/// Trait for Ethernet PHY drivers.
10///
11/// Methods propagate errors from PHY management transactions.
12pub trait Phy {
13    /// Reset the PHY and wait for it to come out of reset.
14    fn phy_reset(&mut self, smi: &mut Smi) -> Result<(), SmiError>;
15    /// Initialize the PHY (enable autonegotiation, etc).
16    fn phy_init(&mut self, smi: &mut Smi) -> Result<(), SmiError>;
17    /// Poll the link state. Returns true if link is up.
18    fn poll_link(&mut self, smi: &mut Smi, cx: &mut Context) -> Result<bool, SmiError>;
19    /// Duplex mode of the established link (called on each link-up).
20    /// Returns true for full duplex. The default keeps the MAC in full duplex.
21    fn full_duplex(&mut self, _smi: &mut Smi) -> Result<bool, SmiError> {
22        Ok(true)
23    }
24    /// Speed of the established link (called on each link-up).
25    /// Returns true for 100 Mbit/s. The default keeps the MAC at 100 Mbit/s.
26    fn speed_100m(&mut self, _smi: &mut Smi) -> Result<bool, SmiError> {
27        Ok(true)
28    }
29    /// Switch to the next receive-pair polarity and restart auto-negotiation.
30    ///
31    /// Called while the link is down, so a polarity that does not link is
32    /// retried on a later poll instead of leaving the link unusable. Returns
33    /// true if the PHY reconfigured itself. The default leaves the PHY alone.
34    fn next_polarity(&mut self, _smi: &mut Smi) -> Result<bool, SmiError> {
35        Ok(false)
36    }
37}
38
39/// Reads of BCR while waiting for a PHY reset to complete. A PHY finishes its
40/// reset within 0.5 s (IEEE 802.3 22.2.4.1.1). Over external SMI, at the fastest
41/// configured MDC (144 MHz / 58), 30 000 reads of 64 cycles take at least 770 ms.
42const RESET_POLL_LIMIT: usize = 30_000;
43
44/// MII PHY register constants.
45mod phy_regs {
46    pub const BCR: u8 = 0x00;
47    pub const BSR: u8 = 0x01;
48    pub const ANLPAR: u8 = 0x05;
49    pub const ANLPAR_SELECTOR: u16 = 0x1F;
50    pub const ANLPAR_SELECTOR_IEEE802_3: u16 = 0x01;
51
52    pub const BCR_RESET: u16 = 1 << 15;
53    pub const BCR_AUTONEG: u16 = 1 << 12;
54    pub const BCR_AUTONEG_RESTART: u16 = 1 << 9;
55
56    pub const BSR_LINK_UP: u16 = 1 << 2;
57}
58
59/// Generic PHY driver that works with IEEE 802.3 compliant PHYs.
60///
61/// For the CH32V307 built-in 10M PHY, use [`InternalPhy`] instead.
62pub struct GenericPhy {
63    phy_addr: u8,
64}
65
66impl GenericPhy {
67    /// Create a new generic PHY driver.
68    ///
69    /// `phy_addr` is the SMI address of the PHY (0-31).
70    pub fn new(phy_addr: u8) -> Self {
71        Self { phy_addr }
72    }
73}
74
75impl Phy for GenericPhy {
76    fn phy_reset(&mut self, smi: &mut Smi) -> Result<(), SmiError> {
77        smi.write(self.phy_addr, phy_regs::BCR, phy_regs::BCR_RESET)?;
78        // Wait for the reset bit to self-clear. Without a PHY at this address
79        // MDIO reads all ones, so the bit never clears: bound the wait.
80        for _ in 0..RESET_POLL_LIMIT {
81            if smi.read(self.phy_addr, phy_regs::BCR)? & phy_regs::BCR_RESET == 0 {
82                return Ok(());
83            }
84        }
85        Err(SmiError::Timeout)
86    }
87
88    fn phy_init(&mut self, smi: &mut Smi) -> Result<(), SmiError> {
89        // Start auto-negotiation
90        smi.write(
91            self.phy_addr,
92            phy_regs::BCR,
93            phy_regs::BCR_AUTONEG | phy_regs::BCR_AUTONEG_RESTART,
94        )
95    }
96
97    fn poll_link(&mut self, smi: &mut Smi, _cx: &mut Context) -> Result<bool, SmiError> {
98        let bsr = smi.read(self.phy_addr, phy_regs::BSR)?;
99        Ok(bsr & phy_regs::BSR_LINK_UP != 0)
100    }
101}
102
103/// Driver for the CH32V307 built-in 10M PHY at SMI address 1.
104pub struct InternalPhy {
105    phy: GenericPhy,
106}
107
108impl InternalPhy {
109    const PHY_ADDR: u8 = 1;
110    /// WCH internal 10M PHY MDIX/polarity control register.
111    const MDIX: u8 = 0x1E;
112    /// WCH internal 10M PHY status register; bit 2 = full duplex.
113    const STATUS: u8 = 0x10;
114    const STATUS_FULL_DUPLEX: u16 = 1 << 2;
115    /// Auto PN polarity detection (bits 3:2 = 0b10).
116    const MDIX_PN_AUTO: u16 = 2 << 2;
117    /// Receive polarity field (bits 3:2): 0b00 normal, 0b01 reversed.
118    const MDIX_PN_MASK: u16 = 3 << 2;
119    const MDIX_PN_REVERSED: u16 = 1 << 2;
120
121    /// Create a driver for the built-in PHY.
122    pub fn new() -> Self {
123        Self {
124            phy: GenericPhy::new(Self::PHY_ADDR),
125        }
126    }
127}
128
129impl Phy for InternalPhy {
130    fn phy_reset(&mut self, smi: &mut Smi) -> Result<(), SmiError> {
131        self.phy.phy_reset(smi)
132    }
133
134    fn phy_init(&mut self, smi: &mut Smi) -> Result<(), SmiError> {
135        // Auto PN polarity detection is required for reliable link establishment.
136        smi.write(Self::PHY_ADDR, Self::MDIX, Self::MDIX_PN_AUTO)?;
137        self.phy.phy_init(smi)
138    }
139
140    fn poll_link(&mut self, smi: &mut Smi, cx: &mut Context) -> Result<bool, SmiError> {
141        self.phy.poll_link(smi, cx)
142    }
143
144    fn full_duplex(&mut self, smi: &mut Smi) -> Result<bool, SmiError> {
145        // As in WCH's driver (ETH_PHYLink): full duplex if the PHY reports it.
146        // Otherwise half duplex if the partner auto-negotiated, full duplex if
147        // it did not (no valid base page).
148        if smi.read(Self::PHY_ADDR, Self::STATUS)? & Self::STATUS_FULL_DUPLEX != 0 {
149            return Ok(true);
150        }
151        let anlpar = smi.read(Self::PHY_ADDR, phy_regs::ANLPAR)?;
152        Ok(anlpar & phy_regs::ANLPAR_SELECTOR != phy_regs::ANLPAR_SELECTOR_IEEE802_3)
153    }
154
155    fn speed_100m(&mut self, _smi: &mut Smi) -> Result<bool, SmiError> {
156        // The built-in PHY is 10BASE-T only.
157        Ok(false)
158    }
159
160    fn next_polarity(&mut self, smi: &mut Smi) -> Result<bool, SmiError> {
161        // Toggle between forced normal (00) and forced reversed (01), as WCH
162        // does in `WCHNET_PhyPNProcess`. Automatic detection (10) is treated
163        // as "try reversed next": if it failed, that is the other setting.
164        let mdix = smi.read(Self::PHY_ADDR, Self::MDIX)?;
165        let mdix = if mdix & Self::MDIX_PN_REVERSED != 0 {
166            mdix & !Self::MDIX_PN_MASK
167        } else {
168            (mdix & !Self::MDIX_PN_MASK) | Self::MDIX_PN_REVERSED
169        };
170        smi.write(Self::PHY_ADDR, Self::MDIX, mdix)?;
171        // The PHY only applies the new polarity when it negotiates again.
172        self.phy.phy_init(smi)?;
173        Ok(true)
174    }
175}