Skip to main content

ch32_hal/eth/v1/
mod.rs

1//! Synopsys DWC Ethernet MAC driver for CH32V305/V307.
2//!
3//! This driver supports the 10/100M Ethernet MAC found on CH32V305 and CH32V307
4//! microcontrollers. The MAC uses the Synopsys DesignWare Cores (DWC) IP, which
5//! is register-compatible with STM32's ETH v1a peripheral.
6//!
7//! The driver uses DMA descriptor rings for zero-copy TX/RX and implements
8//! the `embassy-net-driver` traits for integration with `embassy-net`.
9//!
10//! # Hardware
11//!
12//! Use [`Ethernet::new_internal`] for the built-in PHY, or
13//! [`Ethernet::new_rmii`] for an external PHY. RMII pins are configured and
14//! retained by the driver.
15//!
16//! With the built-in PHY the driver retries the receive-pair polarity while the
17//! link stays down (with the `embassy` feature), as WCH's driver does. The
18//! PHY's automatic detection does not catch every cable, and a forced polarity
19//! that does not link would otherwise keep the link down until a power cycle.
20//!
21//! ## RMII mode pins (default mapping)
22//!
23//! | Signal           | Pin  | Direction |
24//! |------------------|------|-----------|
25//! | RMII_REF_CLK     | PA1  | Input     |
26//! | MDIO             | PA2  | Bidir     |
27//! | RMII_CRS_DV      | PA7  | Input     |
28//! | MDC              | PC1  | Output    |
29//! | RMII_RXD0        | PC4  | Input     |
30//! | RMII_RXD1        | PC5  | Input     |
31//! | RMII_TX_EN       | PB11 | Output    |
32//! | RMII_TXD0        | PB12 | Output    |
33//! | RMII_TXD1        | PB13 | Output    |
34
35use core::marker::PhantomData;
36use core::sync::atomic::{fence, Ordering};
37use core::task::Context;
38
39use embassy_net_driver::{Capabilities, HardwareAddress, LinkState};
40use embassy_sync::waitqueue::AtomicWaker;
41
42use crate::{pac, Peri};
43
44mod dma;
45mod phy;
46mod pins;
47mod smi;
48
49use dma::MTU;
50
51/// Time the driver waits before retrying the opposite receive polarity while
52/// the link is down: long enough for one auto-negotiation to complete.
53#[cfg(feature = "embassy")]
54const POLARITY_RETRY: embassy_time::Duration = embassy_time::Duration::from_millis(2000);
55pub use dma::{PacketQueue, RDes, RDesRing, RxToken, TDes, TDesRing, TxToken};
56pub use phy::{GenericPhy, InternalPhy, Phy};
57use pins::HeldPins;
58pub use pins::{
59    CrsDvPin, MdcPin, MdioPin, RefClkPin, RmiiDataPins, RmiiPins, Rxd0Pin, Rxd1Pin, TxEnPin, Txd0Pin, Txd1Pin,
60};
61pub use smi::{Smi, SmiError};
62
63struct State {
64    waker: AtomicWaker,
65}
66
67impl State {
68    const fn new() -> Self {
69        Self {
70            waker: AtomicWaker::new(),
71        }
72    }
73}
74
75// ============================================================================
76// Driver
77// ============================================================================
78
79// Internal setup and shutdown selection; callers select a constructor.
80#[derive(Clone, Copy, PartialEq, Eq)]
81enum PhyInterface {
82    Rmii,
83    Internal10M,
84}
85
86/// Maximum RCC_CTLR reads while waiting for PLL3 to lock.
87const PLL3_POLL_LIMIT: u32 = 1_000_000;
88
89/// Counts kept by the driver since initialization, wrapping.
90///
91/// Each receive or transmit call reads and clears DMAMFBOCR, adding each of its
92/// frame counts to the matching field. Counts beyond what the hardware counters
93/// hold between two calls are lost.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub struct Stats {
96    /// Frames the MAC dropped for want of a free receive descriptor.
97    pub missed_frames: u32,
98    /// Frames the MAC dropped because its receive FIFO overflowed.
99    pub overflow_frames: u32,
100    /// Completed MAC/DMA recovery resets.
101    pub resets: u32,
102}
103
104/// An error while initializing the Ethernet MAC or PHY.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum InitError {
107    /// The DMA software reset did not complete within the polling budget.
108    DmaResetTimeout,
109    /// PLL3, which clocks the built-in PHY from the HSE, did not lock within
110    /// the polling budget.
111    Pll3Timeout,
112    /// A PHY management transaction failed.
113    Smi(SmiError),
114}
115
116impl From<SmiError> for InitError {
117    fn from(error: SmiError) -> Self {
118        Self::Smi(error)
119    }
120}
121
122/// Ethernet MAC driver.
123///
124/// `TX` and `RX` are the number of DMA descriptors (and buffers) in each ring.
125pub struct Ethernet<'d, T: Instance, const TX: usize, const RX: usize, P: Phy> {
126    tx: TDesRing<'d, T, TX>,
127    rx: RDesRing<'d, T, RX>,
128    phy: P,
129    smi: Smi,
130    mac_addr: [u8; 6],
131    phy_interface: PhyInterface,
132    /// A MAC/DMA recovery did not complete and must be retried.
133    recovery_pending: bool,
134    /// Link state at the last `link_state()` poll.
135    link_up: bool,
136    /// MAC duplex mode, from the PHY at link-up.
137    full_duplex: bool,
138    /// MAC speed, from the PHY at link-up.
139    speed_100m: bool,
140    /// Frames for every destination are received (`set_promiscuous`).
141    promiscuous: bool,
142    /// Counts for the application (`stats`).
143    stats: Stats,
144    /// The link dropped at this time, if it is down.
145    #[cfg(feature = "embassy")]
146    down_since: Option<embassy_time::Instant>,
147    /// Time of the last receive-polarity retry while the link was down.
148    #[cfg(feature = "embassy")]
149    polarity_changed_at: Option<embassy_time::Instant>,
150    _pins: Option<HeldPins<'d>>,
151    _phantom: PhantomData<T>,
152}
153
154impl<'d, T: Instance, const TX: usize, const RX: usize> Ethernet<'d, T, TX, RX, InternalPhy> {
155    /// Initialize Ethernet using the built-in 10M PHY at its fixed SMI address.
156    /// No external MII/RMII pins are needed. The PHY is clocked from the HSE
157    /// through PLL3.
158    ///
159    /// # Errors
160    ///
161    /// Returns an error if PLL3 does not lock, or if DMA reset or a PHY
162    /// management transaction times out.
163    pub fn new_internal(
164        peri: Peri<'d, T>,
165        irqs: impl crate::interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
166        queue: &'d mut PacketQueue<TX, RX>,
167        mac_addr: [u8; 6],
168    ) -> Result<Self, InitError> {
169        Self::new_inner(
170            peri,
171            irqs,
172            queue,
173            InternalPhy::new(),
174            mac_addr,
175            PhyInterface::Internal10M,
176            None,
177        )
178    }
179}
180
181impl<'d, T: Instance, const TX: usize, const RX: usize, P: Phy> Ethernet<'d, T, TX, RX, P> {
182    /// Initialize Ethernet using an external PHY connected through RMII.
183    /// The driver configures and retains the supplied pins using the default mapping.
184    ///
185    /// # Errors
186    ///
187    /// Returns an error if DMA reset or a PHY management transaction times out.
188    pub fn new_rmii(
189        peri: Peri<'d, T>,
190        irqs: impl crate::interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
191        queue: &'d mut PacketQueue<TX, RX>,
192        pins: RmiiPins<
193            'd,
194            impl RefClkPin<T>,
195            impl MdioPin<T>,
196            impl MdcPin<T>,
197            impl CrsDvPin<T>,
198            impl Rxd0Pin<T>,
199            impl Rxd1Pin<T>,
200            impl TxEnPin<T>,
201            impl Txd0Pin<T>,
202            impl Txd1Pin<T>,
203        >,
204        phy: P,
205        mac_addr: [u8; 6],
206    ) -> Result<Self, InitError> {
207        Self::new_inner(
208            peri,
209            irqs,
210            queue,
211            phy,
212            mac_addr,
213            PhyInterface::Rmii,
214            Some(HeldPins::Rmii(pins.configure())),
215        )
216    }
217
218    /// Initialize Ethernet using an external PHY connected through RMII, without MDIO and
219    /// MDC: the application manages the PHY on a bus of its own (for example MDIO driven
220    /// by GPIO, as it may need to keep managing the PHY across a MAC reset). The driver
221    /// configures and retains the seven data pins using the default mapping.
222    ///
223    /// The driver does not configure or retain MDIO and MDC, but still calls every
224    /// [`Phy`] method: the implementation must ignore the [`Smi`] it gets and report
225    /// what the application learnt from the PHY. [`GenericPhy`] and [`InternalPhy`]
226    /// are not suitable.
227    ///
228    /// # Errors
229    ///
230    /// Returns an error if DMA reset times out or a `phy` method returns an error.
231    pub fn new_rmii_without_smi(
232        peri: Peri<'d, T>,
233        irqs: impl crate::interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
234        queue: &'d mut PacketQueue<TX, RX>,
235        pins: RmiiDataPins<
236            'd,
237            impl RefClkPin<T>,
238            impl CrsDvPin<T>,
239            impl Rxd0Pin<T>,
240            impl Rxd1Pin<T>,
241            impl TxEnPin<T>,
242            impl Txd0Pin<T>,
243            impl Txd1Pin<T>,
244        >,
245        phy: P,
246        mac_addr: [u8; 6],
247    ) -> Result<Self, InitError> {
248        Self::new_inner(
249            peri,
250            irqs,
251            queue,
252            phy,
253            mac_addr,
254            PhyInterface::Rmii,
255            Some(HeldPins::RmiiData(pins.configure())),
256        )
257    }
258
259    fn new_inner(
260        _peri: Peri<'d, T>,
261        _irqs: impl crate::interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
262        queue: &'d mut PacketQueue<TX, RX>,
263        mut phy: P,
264        mac_addr: [u8; 6],
265        phy_interface: PhyInterface,
266        pins: Option<HeldPins<'d>>,
267    ) -> Result<Self, InitError> {
268        // ETH needs separate MAC, TX, and RX clocks.
269        critical_section::with(|_| {
270            pac::RCC.ahbpcenr().modify(|w| {
271                w.set_ethmacen(true);
272                w.set_ethmactxen(true);
273                w.set_ethmacrxen(true);
274            });
275        });
276
277        // 2. Interface-specific setup
278        if phy_interface == PhyInterface::Internal10M {
279            // Configure PLL3 to 60MHz for the 10M PHY clock.
280            // HSE=8MHz → PREDIV2=/2 → 4MHz → PLL3*15 → 60MHz.
281            // This clock is required for the built-in 10M PHY to operate.
282            pac::RCC.ctlr().modify(|w| w.set_pll3on(false));
283            pac::RCC.cfgr2().modify(|w| {
284                w.set_prediv2(pac::rcc::vals::Prediv::DIV2);
285                w.set_pll3mul(pac::rcc::vals::PllxMul::MUL15);
286            });
287            pac::RCC.ctlr().modify(|w| w.set_pll3on(true));
288            // PLL3 runs from the HSE: it never locks if the HSE is not running.
289            if !(0..PLL3_POLL_LIMIT).any(|_| pac::RCC.ctlr().read().pll3rdy()) {
290                return Err(InitError::Pll3Timeout);
291            }
292
293            // Enable the built-in 10M PHY via EXTEND register
294            pac::EXTEND.ctr().modify(|w| w.set_eth_10m_en(true));
295
296            // Reset the MAC while the PHY is on, as WCH's `ETH_DeInit()` does.
297            // The reset also makes the internal PHY advertise 10BASE-T full
298            // duplex (0x0c61); without it the PHY powers up advertising half
299            // duplex only (0x0c21), so every cold boot links half duplex. No
300            // MAC register is configured yet, so the reset undoes nothing.
301            pac::RCC.ahbrstr().modify(|w| w.set_ethmacrst(true));
302            pac::RCC.ahbrstr().modify(|w| w.set_ethmacrst(false));
303        } else {
304            // Select RMII via AFIO for the external PHY.
305            #[cfg(afio_v3)]
306            {
307                pac::AFIO.pcfr1().modify(|w| {
308                    w.set_mii_rmii_sel(true);
309                });
310            }
311        }
312
313        // 3.-11. Soft reset and MAC/DMA configuration
314        // Start at 100M for RMII and adjust to the link after negotiation.
315        let speed_100m = phy_interface == PhyInterface::Rmii;
316        let clock_range = configure_mac_dma::<T>(phy_interface, mac_addr, true, speed_100m, false)?;
317        let mut smi = Smi::new(T::regs(), clock_range);
318
319        // Complete fallible PHY setup before DMA can access the packet queue.
320        phy.phy_reset(&mut smi)?;
321        phy.phy_init(&mut smi)?;
322
323        // 12. Initialize DMA descriptor rings
324        let tx = TDesRing::new(&mut queue.tx_desc, &mut queue.tx_buf);
325        let rx = RDesRing::new(&mut queue.rx_desc, &mut queue.rx_buf);
326
327        fence(Ordering::SeqCst);
328
329        // 13.-15. Start MAC, DMA and interrupts
330        start_mac_dma::<T>();
331
332        // 17. Enable ETH interrupt in PFIC
333        unsafe {
334            qingke::pfic::enable_interrupt(pac::Interrupt::ETH as u8);
335        }
336
337        Ok(Self {
338            tx,
339            rx,
340            phy,
341            smi,
342            mac_addr,
343            phy_interface,
344            recovery_pending: false,
345            link_up: false,
346            full_duplex: true,
347            speed_100m,
348            promiscuous: false,
349            stats: Stats::default(),
350            #[cfg(feature = "embassy")]
351            down_since: None,
352            #[cfg(feature = "embassy")]
353            polarity_changed_at: None,
354            _pins: pins,
355            _phantom: PhantomData,
356        })
357    }
358
359    /// Apply the speed and duplex of the new link.
360    fn on_link_up(&mut self) {
361        let e = T::regs();
362        let full = self.phy.full_duplex(&mut self.smi).unwrap_or(true);
363        let speed_100m = self.phy.speed_100m(&mut self.smi).unwrap_or(self.speed_100m);
364        if full != self.full_duplex || speed_100m != self.speed_100m {
365            e.maccr().modify(|w| {
366                w.set_dm(full);
367                w.set_fes(if speed_100m { 1 } else { 0 });
368            });
369            self.full_duplex = full;
370            self.speed_100m = speed_100m;
371        }
372    }
373
374    /// Retry the receive polarity while the link stays down.
375    ///
376    /// The built-in PHY's automatic detection does not cover every cable. A
377    /// forced polarity that does not link drops the link and leaves it there,
378    /// so the only safe moment to try another one is while the link is down:
379    /// each attempt restarts auto-negotiation, and the PHY either links with
380    /// the new polarity or stays down for the next attempt. Pacing needs a
381    /// clock, so this only runs with the `embassy` feature; without it the PHY
382    /// keeps its automatic polarity.
383    fn retry_polarity_while_down(&mut self) {
384        #[cfg(feature = "embassy")]
385        {
386            let now = embassy_time::Instant::now();
387            let down_since = *self.down_since.get_or_insert(now);
388            let last = self.polarity_changed_at.unwrap_or(down_since);
389            if now - down_since < POLARITY_RETRY || now - last < POLARITY_RETRY {
390                return;
391            }
392            self.polarity_changed_at = Some(now);
393            let _ = self.phy.next_polarity(&mut self.smi);
394        }
395    }
396
397    /// Reset and reconfigure the MAC and DMA after an RX FIFO overflow, or when
398    /// the TX DMA left its ring (see `TDesRing::derailed`).
399    ///
400    /// On the CH32V307 (seen with the built-in 10M PHY), an RX FIFO overflow
401    /// leaves the MAC reporting a stale frame length (the previous frame's) for
402    /// every later frame whose length including FCS is a multiple of 4, so those
403    /// frames are truncated. Only a MAC/DMA software reset clears it; toggling the
404    /// receiver, restarting DMA or resetting the PHY does not.
405    ///
406    /// After the reset both descriptor rings restart from scratch, so the DMA
407    /// and driver agree on their positions. Queued frames and FIFO contents
408    /// are lost.
409    fn recover_dma(&mut self, cx: &mut Context) {
410        // The CH32V307 does not set DMASR.ROS on an RX FIFO overflow; it only
411        // counts the dropped frames in DMAMFBOCR (cleared on read).
412        let e = T::regs();
413        let missed = e.dmamfbocr().read();
414        // The read cleared both counters: keep them for `stats`.
415        self.stats.missed_frames = self.stats.missed_frames.wrapping_add(u32::from(missed.mfc()));
416        self.stats.overflow_frames = self.stats.overflow_frames.wrapping_add(u32::from(missed.mfa()));
417        if missed.mfa() == 0 && !missed.ofoc() && !self.recovery_pending && !self.tx.derailed() {
418            return;
419        }
420        self.recovery_pending = false;
421
422        // Stop TX DMA, then MAC TX/RX, then RX DMA.
423        e.dmaomr().modify(|w| w.set_st(false));
424        e.maccr().modify(|w| {
425            w.set_te(false);
426            w.set_re(false);
427        });
428        e.dmaomr().modify(|w| w.set_sr(false));
429
430        if configure_mac_dma::<T>(
431            self.phy_interface,
432            self.mac_addr,
433            self.full_duplex,
434            self.speed_100m,
435            self.promiscuous,
436        )
437        .is_err()
438        {
439            // Do not touch descriptors or issue tokens until reset completes.
440            // Poll again instead of waiting for an interrupt that cannot come.
441            self.recovery_pending = true;
442            cx.waker().wake_by_ref();
443            return;
444        }
445        // Clearing ST/SR only asks DMA to stop after its current frame; its
446        // cursors can still advance before the soft reset takes effect. Start
447        // both rings afresh only after reset has completed, rather than
448        // restoring cursors that may point at an already completed descriptor.
449        self.tx.reset();
450        self.rx.reset();
451        fence(Ordering::SeqCst);
452        start_mac_dma::<T>();
453        self.stats.resets = self.stats.resets.wrapping_add(1);
454    }
455
456    /// Get the SMI interface for direct PHY register access.
457    pub fn smi(&mut self) -> &mut Smi {
458        &mut self.smi
459    }
460
461    /// Get the configured MAC address.
462    pub fn mac_addr(&self) -> [u8; 6] {
463        self.mac_addr
464    }
465
466    /// Receive frames for every destination address, not only this MAC's, its
467    /// multicast and broadcast: what a bridge needs. The setting survives the
468    /// driver's own MAC/DMA resets.
469    pub fn set_promiscuous(&mut self, on: bool) {
470        self.promiscuous = on;
471        T::regs().macffr().modify(|w| w.set_pm(on));
472    }
473
474    /// Receive one frame whatever the transmit ring holds.
475    ///
476    /// `receive()` of `embassy_net_driver::Driver` also needs a free transmit
477    /// descriptor, as the stack may answer at once. A bridge forwards frames to
478    /// another interface instead: it must keep receiving while its own transmit
479    /// ring is full. The token tells the frame's length before it is consumed,
480    /// so a frame with nowhere to go yet can be left in the ring.
481    pub fn receive_frame(&mut self, cx: &mut Context) -> Option<RxToken<'_, 'd, T, RX>> {
482        T::state().waker.register(cx.waker());
483        self.recover_dma(cx);
484        if self.recovery_pending {
485            return None;
486        }
487        let len = self.rx.available()?.len();
488        Some(RxToken { rx: &mut self.rx, len })
489    }
490
491    /// Counts since initialization, wrapping. This does not read the hardware:
492    /// the counts are as of the last receive or transmit call.
493    pub fn stats(&self) -> Stats {
494        self.stats
495    }
496}
497
498/// DMA soft reset and MAC/DMA configuration (steps 3-11). Shared by
499/// initialization and recovery. Returns the SMI clock range.
500fn configure_mac_dma<T: Instance>(
501    phy_interface: PhyInterface,
502    mac_addr: [u8; 6],
503    full_duplex: bool,
504    speed_100m: bool,
505    promiscuous: bool,
506) -> Result<u8, InitError> {
507    let e = T::regs();
508
509    // 3. DMA soft reset
510    e.dmabmr().write(|w| w.set_sr(true));
511    let mut timeout = 10_000u32;
512    while e.dmabmr().read().sr() {
513        for _ in 0..1000 {
514            qingke::riscv::asm::nop();
515        }
516        timeout -= 1;
517        if timeout == 0 {
518            return Err(InitError::DmaResetTimeout);
519        }
520    }
521
522    // MMC counters raise ETH interrupts at half range. We do not service
523    // those sources, so mask them after every reset (including recovery) to
524    // prevent a persistent interrupt from starving the executor.
525    // TODO: use PAC accessors once emac_v1 describes the MMC registers.
526    // SAFETY: these aligned offsets from the MAC base are MMCRIMR and
527    // MMCTIMR, documented in the CH32V307 reference manual, section 27.1.8.2.
528    unsafe {
529        let mac = e.as_ptr().cast::<u8>();
530        core::ptr::write_volatile(mac.add(0x10c).cast::<u32>(), (1 << 17) | (1 << 5));
531        core::ptr::write_volatile(mac.add(0x110).cast::<u32>(), 1 << 21);
532    }
533
534    // 4. Select SMI clock divider — 0b000 divides by 58 on a CH32V307 (measured; the RM says 42),
535    // so MDC is 2.48 MHz at 144 MHz
536    let hclk = crate::rcc::clocks().hclk.0;
537    let clock_range: u8 = if hclk < 35_000_000 {
538        0b010 // div16
539    } else if hclk < 60_000_000 {
540        0b011 // div26
541    } else {
542        0b000 // div58
543    };
544    e.macmiiar().write(|w| w.set_cr(clock_range));
545
546    // 5. Configure MAC
547    //
548    // IPv4 checksum offload stays off: nothing reads the per-frame checksum
549    // status, and while it is on the DMA drops frames whose header fails the
550    // check unless `DMAOMR.DTCEFD` is set. WCH's reference driver leaves it
551    // off too.
552    e.maccr().write(|w| {
553        w.set_dm(full_duplex);
554
555        if phy_interface == PhyInterface::Internal10M {
556            w.set_ire(true); // Internal 50-ohm pull-up (10M PHY only)
557        } else {
558            w.set_fes(if speed_100m { 1 } else { 0 }); // Link speed
559
560            // `RDesRing` takes the FCS off every frame. With APCS set, the MAC
561            // already strips pad and FCS from frames with a length field, so
562            // their end would be cut.
563            w.set_apcs(false);
564            w.set_rd(true); // Retry disable
565        }
566    });
567
568    // 6. Frame filter
569    // No receive-all mode: the built-in PHY handles the cable polarity itself
570    // (automatic PN polarity, see `InternalPhy`). Frames for other hosts are
571    // only received when asked for (`set_promiscuous`).
572    e.macffr().write(|w| {
573        w.set_pam(true); // Pass all multicast (needed for ARP/DHCP)
574        w.set_pm(promiscuous);
575    });
576
577    // 7. Hash table (unused, zero)
578    e.machthr().write(|w| w.set_hth(0));
579    e.machtlr().write(|w| w.set_htl(0));
580
581    // 8. Flow control: pause time 0x100
582    e.macfcr().write(|w| w.set_pt(0x100));
583
584    // 9. Set MAC address
585    // MACA0HR: bytes [5:4], MACA0LR: bytes [3:0]
586    let mac_high = ((mac_addr[5] as u16) << 8) | (mac_addr[4] as u16);
587    let mac_low = ((mac_addr[3] as u32) << 24)
588        | ((mac_addr[2] as u32) << 16)
589        | ((mac_addr[1] as u32) << 8)
590        | (mac_addr[0] as u32);
591    e.maca0hr().write(|w| w.set_maca0h(mac_high));
592    e.maca0lr().write(|w| w.set_maca0l(mac_low)); // LR write triggers sync
593
594    // 10. DMA bus mode: 32-beat burst length
595    e.dmabmr().write(|w| w.set_pbl(32));
596
597    // 11. DMA operation mode
598    //
599    // Store-and-forward in both directions: a frame only reaches memory once it
600    // is complete, so a receive overrun truncates at a frame boundary and the
601    // recovery below sees whole frames. Unlike WCH's reference driver, error
602    // frames are not forwarded (`FEF`/`FUGF` clear): they cost descriptors and
603    // the stack would drop them anyway.
604    e.dmaomr().write(|w| {
605        w.set_rsf(true);
606        w.set_tsf(true);
607    });
608
609    Ok(clock_range)
610}
611
612/// Enable MAC RX/TX, start DMA and enable DMA interrupts (steps 13-15).
613fn start_mac_dma<T: Instance>() {
614    let e = T::regs();
615
616    // 13. Enable MAC receiver and transmitter
617    e.maccr().modify(|w| {
618        w.set_re(true);
619        w.set_te(true);
620    });
621
622    // 14. Start DMA: flush TX FIFO, then start TX and RX
623    e.dmaomr().modify(|w| w.set_ftf(true));
624    e.dmaomr().modify(|w| {
625        w.set_st(true);
626        w.set_sr(true);
627    });
628
629    // Demand poll RX to start receiving
630    e.dmarpdr().write(|w| w.set_rpd(0));
631
632    // 15. Enable DMA interrupts
633    e.dmaier().write(|w| {
634        w.set_tie(true); // TX complete
635        w.set_rie(true); // RX complete
636        w.set_nise(true); // Normal interrupt summary
637        w.set_aise(true); // Abnormal interrupt summary
638        w.set_rbuie(true); // RX buffer unavailable
639    });
640}
641
642impl<'d, T: Instance, const TX: usize, const RX: usize, P: Phy> Drop for Ethernet<'d, T, TX, RX, P> {
643    fn drop(&mut self) {
644        let e = T::regs();
645
646        // Stop DMA TX
647        e.dmaomr().modify(|w| w.set_st(false));
648        // Disable MAC TX/RX
649        e.maccr().modify(|w| {
650            w.set_te(false);
651            w.set_re(false);
652        });
653        // Stop DMA RX
654        e.dmaomr().modify(|w| w.set_sr(false));
655
656        // Disable ETH interrupt
657        unsafe {
658            qingke::pfic::disable_interrupt(pac::Interrupt::ETH as u8);
659        }
660
661        // Disable built-in 10M PHY if it was enabled
662        if self.phy_interface == PhyInterface::Internal10M {
663            pac::EXTEND.ctr().modify(|w| w.set_eth_10m_en(false));
664        }
665
666        // Disable RCC clocks
667        critical_section::with(|_| {
668            pac::RCC.ahbpcenr().modify(|w| {
669                w.set_ethmacen(false);
670                w.set_ethmactxen(false);
671                w.set_ethmacrxen(false);
672            });
673        });
674    }
675}
676
677trait SealedInstance {
678    fn regs() -> pac::emac::Eth;
679    fn state() -> &'static State;
680}
681
682#[allow(private_bounds)]
683pub trait Instance: SealedInstance + embassy_hal_internal::PeripheralType + 'static {
684    /// Interrupt for this instance
685    type Interrupt: crate::interrupt::typelevel::Interrupt;
686}
687
688foreach_peripheral!(
689    (emac, $inst:ident) => {
690        impl SealedInstance for crate::peripherals::$inst {
691            fn regs() -> pac::emac::Eth {
692                pac::$inst
693            }
694
695            fn state() -> &'static State {
696                static STATE: State = State::new();
697                &STATE
698            }
699        }
700
701        impl Instance for crate::peripherals::$inst {
702            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
703        }
704    };
705);
706
707pub struct InterruptHandler<T: Instance> {
708    _phantom: PhantomData<T>,
709}
710
711impl<T: Instance> crate::interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
712    unsafe fn on_interrupt() {
713        let r = T::regs();
714        let s = T::state();
715        let status = r.dmasr().read();
716        // Descriptor processing and RX recovery run in the executor.
717        let wake = status.ts() || status.rs() || status.rbus();
718
719        // Acknowledge observed sources and their summaries (W1C).
720        // These correspond to the DMA interrupt sources enabled during setup.
721        r.dmasr().write(|w| {
722            w.set_ts(status.ts());
723            w.set_rs(status.rs());
724            w.set_rbus(status.rbus());
725            w.set_nis(status.nis());
726            w.set_ais(status.ais());
727        });
728
729        // Two dummy reads for peripheral clock sync (per reference manual)
730        r.dmasr().read();
731        r.dmasr().read();
732
733        if wake {
734            s.waker.wake();
735        }
736    }
737}
738
739// ============================================================================
740// embassy-net-driver integration
741// ============================================================================
742
743impl<'d, T: Instance, const TX: usize, const RX: usize, P: Phy> embassy_net_driver::Driver
744    for Ethernet<'d, T, TX, RX, P>
745{
746    type RxToken<'a>
747        = RxToken<'a, 'd, T, RX>
748    where
749        Self: 'a;
750    type TxToken<'a>
751        = TxToken<'a, 'd, T, TX>
752    where
753        Self: 'a;
754
755    fn receive(&mut self, cx: &mut Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
756        let s = T::state();
757        s.waker.register(cx.waker());
758        self.recover_dma(cx);
759        if self.recovery_pending {
760            return None;
761        }
762        // RX first, as before: `available()` also resumes a suspended RX DMA.
763        let len = self.rx.available()?.len();
764        self.tx.available()?;
765        // rx and tx are disjoint struct fields, Rust permits simultaneous &mut borrows.
766        Some((RxToken { rx: &mut self.rx, len }, TxToken { tx: &mut self.tx }))
767    }
768
769    fn transmit(&mut self, cx: &mut Context) -> Option<Self::TxToken<'_>> {
770        let s = T::state();
771        s.waker.register(cx.waker());
772        self.recover_dma(cx);
773        if !self.recovery_pending && self.tx.available().is_some() {
774            Some(TxToken { tx: &mut self.tx })
775        } else {
776            None
777        }
778    }
779
780    fn capabilities(&self) -> Capabilities {
781        let mut caps = Capabilities::default();
782        caps.max_transmission_unit = MTU;
783        caps.max_burst_size = Some(self.tx.len());
784        caps
785    }
786
787    fn link_state(&mut self, cx: &mut Context) -> LinkState {
788        let up = self.phy.poll_link(&mut self.smi, cx).unwrap_or(false);
789        if up && !self.link_up {
790            self.on_link_up();
791        }
792        self.link_up = up;
793        if up {
794            #[cfg(feature = "embassy")]
795            {
796                self.down_since = None;
797                self.polarity_changed_at = None;
798            }
799            LinkState::Up
800        } else {
801            self.retry_polarity_while_down();
802            LinkState::Down
803        }
804    }
805
806    fn hardware_address(&self) -> HardwareAddress {
807        HardwareAddress::Ethernet(self.mac_addr)
808    }
809}