Skip to main content

esp_hal/ethernet/phy/
generic.rs

1//! Generic PHY driver.
2//!
3//! Standard IEEE 802.3 Clause 22 PHYs with auto-negotiation support.
4
5use core::task::Context;
6
7use crate::{
8    asynch::wake_at,
9    ethernet::{
10        mac::{Duplex, LinkState, Speed},
11        phy::{
12            ANAR,
13            ANLPAR,
14            BMCR,
15            BMSR,
16            EXSR,
17            GBCR,
18            GBSR,
19            MdioBus,
20            PHYIDR1,
21            PHYIDR2,
22            Phy,
23            PhyError,
24            an,
25            bmcr,
26            bmsr,
27            exsr,
28            gbcr,
29            gbsr,
30        },
31    },
32    time::{Duration, Instant},
33};
34
35/// Interval between link polls in async mode.
36const LINK_POLL_INTERVAL: Duration = Duration::from_millis(500);
37
38const LINK_STATE_DOWN: LinkState = LinkState {
39    up: false,
40    speed: Speed::_100M,
41    duplex: Duplex::Full,
42};
43
44/// Maximum iterations to wait for the PHY reset bit to self-clear.
45const RESET_POLL_LIMIT: u32 = 500_000; // us
46
47/// Motorcomm YT8531 identifier (`PHYIDR1`/`PHYIDR2`).
48const YT8531_ID: (u16, u16) = (0x4F51, 0xE91B);
49
50/// Extended-register address window (Motorcomm).
51const REG_EXT_ADDR: u8 = 0x1E;
52/// Extended-register data window (Motorcomm).
53const REG_EXT_DATA: u8 = 0x1F;
54
55/// Chip config (extended). Bit 8 adds a coarse ~1.9 ns RXC delay.
56const EXT_CHIP_CFG: u16 = 0xA001;
57const RXC_DLY_EN: u16 = 1 << 8;
58
59/// RGMII delay config (extended).
60/// `[13:10]` RX, `[7:4]` 100M TX, `[3:0]` 1000M TX. Unit 150 ps; 13 ≈ 1.95 ns.
61const EXT_RGMII_CFG1: u16 = 0xA003;
62const RGMII_TX_DLY_MASK: u16 = 0x00FF;
63const RGMII_DLY_2NS: u16 = 13;
64
65fn ext_read<M: MdioBus>(mdio: &mut M, addr: u8, ext: u16) -> u16 {
66    mdio.write(addr, REG_EXT_ADDR, ext);
67    mdio.read(addr, REG_EXT_DATA)
68}
69
70fn ext_write<M: MdioBus>(mdio: &mut M, addr: u8, ext: u16, val: u16) {
71    mdio.write(addr, REG_EXT_ADDR, ext);
72    mdio.write(addr, REG_EXT_DATA, val);
73}
74
75/// Generic PHY driver.
76///
77/// Initialization and link handling follow IEEE 802.3 Clause 22, matching
78/// esp-idf `esp_eth_phy_802_3`. PHYs that need chip-specific setup get it
79/// applied from [`Phy::init`] based on their identifier.
80///
81/// Can be constructed with a fixed address ([`GenericPhy::new`]) or with
82/// automatic address discovery ([`GenericPhy::new_auto`]).  When using
83/// `new_auto`, the MDIO bus is scanned during [`Phy::init`] and the first
84/// responding PHY address is adopted.
85#[derive(Clone, Copy, Debug)]
86pub struct GenericPhy {
87    /// `Some(addr)` for a fixed address; `None` until auto-discovery runs.
88    addr: Option<u8>,
89    /// Link state from the last read in async mode.
90    link: LinkState,
91    /// Earliest time of the next read in async mode.
92    next_poll: Instant,
93}
94
95impl GenericPhy {
96    /// Creates a new driver instance for the given MDIO bus address.
97    pub const fn new(addr: u8) -> Self {
98        Self::with_addr(Some(addr))
99    }
100
101    /// Creates a new driver instance that discovers the PHY address automatically
102    /// by scanning the MDIO bus during [`Phy::init`].
103    ///
104    /// Returns [`PhyError::NotFound`] from `init` if no PHY responds.
105    pub const fn new_auto() -> Self {
106        Self::with_addr(None)
107    }
108
109    const fn with_addr(addr: Option<u8>) -> Self {
110        Self {
111            addr,
112            link: LINK_STATE_DOWN,
113            next_poll: Instant::EPOCH,
114        }
115    }
116
117    /// Scans all 32 Clause 22 addresses and returns the first one that holds a
118    /// valid `PHYIDR1` value (not 0x0000 or 0xFFFF).
119    ///
120    /// The scan is repeated up to 3 times to handle transient bus noise,
121    /// matching the esp-idf `esp_eth_phy_802_3_detect_phy_addr` strategy.
122    fn discover<M: MdioBus>(mdio: &mut M) -> Option<u8> {
123        for _ in 0..3 {
124            for addr in 0..32_u8 {
125                let id = mdio.read(addr, PHYIDR1);
126                if id != 0x0000 && id != 0xFFFF {
127                    debug!("phy found at addr {} - id: {:x}", addr, id);
128                    return Some(addr);
129                }
130            }
131        }
132        None
133    }
134
135    /// Removes advertisements faster than `max_speed`.
136    ///
137    /// A gigabit PHY wired to an RMII or MII MAC would otherwise negotiate 1000
138    /// Mbps with the link partner and the MAC could not carry it. Returns
139    /// whether an advertisement was withdrawn, in which case auto-negotiation
140    /// has to be restarted to take effect.
141    fn limit_advertisement<M: MdioBus>(mdio: &mut M, addr: u8, max_speed: Speed) -> bool {
142        let mut changed = false;
143
144        if max_speed != Speed::_1000M {
145            let gbcr_val = mdio.read(addr, GBCR);
146            if gbcr_val != 0xFFFF {
147                let limited = gbcr_val & !(gbcr::ADV_1000_FULL | gbcr::ADV_1000_HALF);
148                if limited != gbcr_val {
149                    mdio.write(addr, GBCR, limited);
150                    changed = true;
151                }
152            }
153        }
154
155        if max_speed == Speed::_10M {
156            let anar_val = mdio.read(addr, ANAR);
157            let limited = anar_val & !(an::BASE_100_FULL | an::BASE_100_HALF);
158            if limited != anar_val {
159                mdio.write(addr, ANAR, limited);
160                changed = true;
161            }
162        }
163
164        changed
165    }
166
167    /// Programs the Motorcomm YT8531 RGMII clock delays.
168    ///
169    /// RGMII needs roughly 2 ns of delay on both paths. Do not write the YT8521 `0xA000` UTP/fiber
170    /// page select: the YT8531 is UTP-only and that write maps the Clause 22 registers to dead
171    /// space.
172    fn init_yt8531<M: MdioBus>(mdio: &mut M, addr: u8) {
173        let chip = ext_read(mdio, addr, EXT_CHIP_CFG);
174        ext_write(mdio, addr, EXT_CHIP_CFG, chip | RXC_DLY_EN);
175
176        let mut rgmii = ext_read(mdio, addr, EXT_RGMII_CFG1);
177        rgmii = (rgmii & !RGMII_TX_DLY_MASK) | (RGMII_DLY_2NS << 4) | RGMII_DLY_2NS;
178        ext_write(mdio, addr, EXT_RGMII_CFG1, rgmii);
179
180        // Restart auto-negotiation so the delays are in force before it resolves.
181        let ctrl = mdio.read(addr, BMCR);
182        mdio.write(addr, BMCR, ctrl | bmcr::RESTART_AN);
183    }
184}
185
186impl Phy for GenericPhy {
187    fn address(&self) -> u8 {
188        self.addr
189            .expect("GenericPhy address not yet resolved — call init() first")
190    }
191
192    fn init<M: MdioBus>(&mut self, mdio: &mut M, max_speed: Speed) -> Result<(), PhyError> {
193        // Resolve address if auto-discovery was requested.
194        if self.addr.is_none() {
195            self.addr = Some(Self::discover(mdio).ok_or(PhyError::NotFound)?);
196        }
197        let addr = self.addr.unwrap();
198
199        // Match esp-idf `esp_eth_phy_802_3_basic_phy_init`: power up, then
200        // software reset. ANAR/GBCR keep their post-reset defaults except for
201        // abilities the MAC interface cannot carry.
202        let ctrl = mdio.read(addr, BMCR);
203        if ctrl & bmcr::POWER_DOWN != 0 {
204            mdio.write(addr, BMCR, ctrl & !bmcr::POWER_DOWN);
205            for _ in 0..RESET_POLL_LIMIT {
206                if mdio.read(addr, BMCR) & bmcr::POWER_DOWN == 0 {
207                    break;
208                }
209                crate::rom::ets_delay_us(1);
210            }
211        }
212
213        mdio.write(addr, BMCR, bmcr::RESET);
214        for _ in 0..RESET_POLL_LIMIT {
215            if mdio.read(addr, BMCR) & bmcr::RESET == 0 {
216                // Some PHYs clear ANEN across a reset. Only restore the bit;
217                // advertisements stay at their post-reset defaults.
218                let ctrl = mdio.read(addr, BMCR);
219                if ctrl & bmcr::ANEN == 0 {
220                    mdio.write(addr, BMCR, (ctrl & !bmcr::POWER_DOWN) | bmcr::ANEN);
221                }
222
223                let restart_an = Self::limit_advertisement(mdio, addr, max_speed);
224
225                let id = (mdio.read(addr, PHYIDR1), mdio.read(addr, PHYIDR2));
226                if id == YT8531_ID {
227                    // Also restarts auto-negotiation.
228                    Self::init_yt8531(mdio, addr);
229                } else if restart_an {
230                    let ctrl = mdio.read(addr, BMCR);
231                    mdio.write(addr, BMCR, ctrl | bmcr::RESTART_AN);
232                }
233
234                return Ok(());
235            }
236            crate::rom::ets_delay_us(1);
237        }
238
239        Err(PhyError::Timeout)
240    }
241
242    fn poll_link<M: MdioBus>(&mut self, mdio: &mut M, cx: Option<&mut Context<'_>>) -> LinkState {
243        let Some(cx) = cx else {
244            return self.read_link(mdio);
245        };
246
247        // The task may be polled for other reasons (other wakers, joined or
248        // selected futures), so only read the PHY once the interval has passed.
249        let now = Instant::now();
250        if now >= self.next_poll {
251            self.link = self.read_link(mdio);
252            self.next_poll = now + LINK_POLL_INTERVAL;
253        }
254
255        // No PHY interrupt is available. Without the `embassy-time-05` feature
256        // this wakes immediately and busy-polls.
257        wake_at(self.next_poll, cx);
258        self.link
259    }
260}
261
262impl GenericPhy {
263    /// Reads the current link state from the PHY registers.
264    fn read_link<M: MdioBus>(&self, mdio: &mut M) -> LinkState {
265        let Some(addr) = self.addr else {
266            debug!("poll_link called before init");
267            return LINK_STATE_DOWN;
268        };
269
270        // Read BMSR twice: first read clears the latch-low LINK_STATUS bit on
271        // some PHYs; the second read gives the real state.
272        let _ = mdio.read(addr, BMSR);
273        let bmsr_val = mdio.read(addr, BMSR);
274
275        trace!("bmsr_val: {:x}", bmsr_val);
276
277        // Link is BMSR.LINK_STATUS alone, as in IDF
278        // `esp_eth_phy_802_3_updt_link_dup_spd`. AN_COMPLETE may still be clear
279        // while Clause 40 finishes even though copper is already up.
280        if bmsr_val & bmsr::LINK_STATUS == 0 {
281            return LINK_STATE_DOWN;
282        }
283
284        let bmcr_val = mdio.read(addr, BMCR);
285        if bmcr_val & bmcr::ANEN == 0 {
286            let speed = if bmcr_val & bmcr::SPEED_1000 != 0 {
287                Speed::_1000M
288            } else if bmcr_val & bmcr::SPEED_100 != 0 {
289                Speed::_100M
290            } else {
291                Speed::_10M
292            };
293            let duplex = if bmcr_val & bmcr::FULL_DUPLEX != 0 {
294                Duplex::Full
295            } else {
296                Duplex::Half
297            };
298            return LinkState {
299                up: true,
300                speed,
301                duplex,
302            };
303        }
304
305        if bmsr_val & bmsr::EXTENDED_STATUS != 0 {
306            let exsr_val = mdio.read(addr, EXSR);
307            if exsr_val != 0xFFFF && (exsr_val & (exsr::BASE1000_T_HD | exsr::BASE1000_T_FD) != 0) {
308                let gbcr_val = mdio.read(addr, GBCR);
309                let gbsr_val = mdio.read(addr, GBSR);
310                if gbcr_val != 0xFFFF && gbsr_val != 0xFFFF {
311                    if gbcr_val & gbcr::ADV_1000_FULL != 0 && gbsr_val & gbsr::LP_1000_FULL != 0 {
312                        return LinkState {
313                            up: true,
314                            speed: Speed::_1000M,
315                            duplex: Duplex::Full,
316                        };
317                    }
318                    if gbcr_val & gbcr::ADV_1000_HALF != 0 && gbsr_val & gbsr::LP_1000_HALF != 0 {
319                        return LinkState {
320                            up: true,
321                            speed: Speed::_1000M,
322                            duplex: Duplex::Half,
323                        };
324                    }
325                }
326            }
327        }
328
329        // IDF: resolved mode is ANAR ∩ ANLPAR, highest common ability first.
330        let anar_val = mdio.read(addr, ANAR);
331        let anlpar_val = mdio.read(addr, ANLPAR);
332        let common = anar_val & anlpar_val;
333        let (speed, duplex) = if common & an::BASE_100_FULL != 0 {
334            (Speed::_100M, Duplex::Full)
335        } else if common & an::BASE_100_HALF != 0 {
336            (Speed::_100M, Duplex::Half)
337        } else if common & an::BASE_10_FULL != 0 {
338            (Speed::_10M, Duplex::Full)
339        } else if common & an::BASE_10_HALF != 0 {
340            (Speed::_10M, Duplex::Half)
341        } else {
342            (Speed::_100M, Duplex::Full)
343        };
344
345        LinkState {
346            up: true,
347            speed,
348            duplex,
349        }
350    }
351}