Skip to main content

ch32_hal/eth/v1/
dma.rs

1use core::marker::PhantomData;
2use core::sync::atomic::{fence, Ordering};
3
4use super::Instance;
5
6// ============================================================================
7// DMA descriptors
8// ============================================================================
9
10pub(super) const MTU: usize = 1514;
11// A VLAN-tagged frame is up to 1518 bytes without its FCS (IEEE 802.3, 3.2.7): a bridge
12// forwards them. The IP stack still sends at most MTU.
13const TX_BUF_SIZE: usize = 1518;
14const RX_BUF_SIZE: usize = 1536;
15
16// TX descriptor word 0 (TDES0) bits
17const TDES0_OWN: u32 = 1 << 31;
18const TDES0_IC: u32 = 1 << 30; // Interrupt on completion
19const TDES0_LS: u32 = 1 << 29; // Last segment
20const TDES0_FS: u32 = 1 << 28; // First segment
21const TDES0_TCH: u32 = 1 << 20; // Second address chained
22
23// RX descriptor word 0 (RDES0) bits
24const RDES0_OWN: u32 = 1 << 31;
25const RDES0_FS: u32 = 1 << 9; // First descriptor
26const RDES0_LS: u32 = 1 << 8; // Last descriptor
27const RDES0_ES: u32 = 1 << 15; // Error summary
28const RDES0_FL_MASK: u32 = 0x3FFF0000; // Frame length mask
29const RDES0_FL_SHIFT: u32 = 16;
30
31// RX descriptor word 1 (RDES1) bits
32const RDES1_RCH: u32 = 1 << 14; // Second address chained
33
34/// A single TX DMA descriptor (4 x 32-bit words).
35#[repr(C, align(4))]
36pub struct TDes {
37    tdes0: u32,
38    tdes1: u32,
39    tdes2: u32,
40    tdes3: u32,
41}
42
43impl TDes {
44    pub const fn new() -> Self {
45        Self {
46            tdes0: 0,
47            tdes1: 0,
48            tdes2: 0,
49            tdes3: 0,
50        }
51    }
52
53    #[inline]
54    fn tdes0(&self) -> u32 {
55        unsafe { core::ptr::read_volatile(&self.tdes0) }
56    }
57
58    #[inline]
59    fn set_tdes0(&mut self, val: u32) {
60        unsafe { core::ptr::write_volatile(&mut self.tdes0, val) }
61    }
62
63    #[inline]
64    fn set_tdes1(&mut self, val: u32) {
65        unsafe { core::ptr::write_volatile(&mut self.tdes1, val) }
66    }
67
68    #[inline]
69    fn set_tdes2(&mut self, val: u32) {
70        unsafe { core::ptr::write_volatile(&mut self.tdes2, val) }
71    }
72
73    #[inline]
74    fn set_tdes3(&mut self, val: u32) {
75        unsafe { core::ptr::write_volatile(&mut self.tdes3, val) }
76    }
77}
78
79/// A single RX DMA descriptor (4 x 32-bit words).
80#[repr(C, align(4))]
81pub struct RDes {
82    rdes0: u32,
83    rdes1: u32,
84    rdes2: u32,
85    rdes3: u32,
86}
87
88impl RDes {
89    pub const fn new() -> Self {
90        Self {
91            rdes0: 0,
92            rdes1: 0,
93            rdes2: 0,
94            rdes3: 0,
95        }
96    }
97
98    #[inline]
99    fn rdes0(&self) -> u32 {
100        unsafe { core::ptr::read_volatile(&self.rdes0) }
101    }
102
103    #[inline]
104    fn set_rdes0(&mut self, val: u32) {
105        unsafe { core::ptr::write_volatile(&mut self.rdes0, val) }
106    }
107
108    #[inline]
109    fn set_rdes1(&mut self, val: u32) {
110        unsafe { core::ptr::write_volatile(&mut self.rdes1, val) }
111    }
112
113    #[inline]
114    fn set_rdes2(&mut self, val: u32) {
115        unsafe { core::ptr::write_volatile(&mut self.rdes2, val) }
116    }
117
118    #[inline]
119    fn set_rdes3(&mut self, val: u32) {
120        unsafe { core::ptr::write_volatile(&mut self.rdes3, val) }
121    }
122}
123
124// ============================================================================
125// DMA descriptor rings
126// ============================================================================
127
128/// A TX DMA descriptor ring.
129pub struct TDesRing<'d, T: Instance, const N: usize> {
130    desc: &'d mut [TDes; N],
131    buf: &'d mut [[u8; TX_BUF_SIZE]; N],
132    index: usize,
133    _phantom: PhantomData<T>,
134}
135
136impl<'d, T: Instance, const N: usize> TDesRing<'d, T, N> {
137    pub(super) fn new(desc: &'d mut [TDes; N], buf: &'d mut [[u8; TX_BUF_SIZE]; N]) -> Self {
138        // Set up chained descriptors
139        for i in 0..N {
140            let next = if i + 1 < N {
141                &desc[i + 1] as *const TDes as u32
142            } else {
143                &desc[0] as *const TDes as u32
144            };
145
146            desc[i].set_tdes2(buf[i].as_ptr() as u32);
147            desc[i].set_tdes3(next);
148        }
149        // Last descriptor chains back to first (already set in loop above).
150
151        let mut ring = Self {
152            desc,
153            buf,
154            index: 0,
155            _phantom: PhantomData,
156        };
157        ring.reset();
158        ring
159    }
160
161    /// Discard pending frames and restart the ring. DMA must be stopped, either
162    /// before its first start or after a completed MAC/DMA software reset.
163    pub(super) fn reset(&mut self) {
164        for d in self.desc.iter_mut() {
165            d.set_tdes0(TDES0_TCH | TDES0_IC | TDES0_FS | TDES0_LS);
166            d.set_tdes1(0);
167        }
168        self.index = 0;
169        T::regs()
170            .dmatdlar()
171            .write(|w| w.set_stl(&self.desc[0] as *const TDes as u32));
172    }
173
174    /// Returns a mutable slice of the next available TX buffer, or None if DMA owns it.
175    pub fn available(&mut self) -> Option<&mut [u8]> {
176        let d = &self.desc[self.index];
177        if d.tdes0() & TDES0_OWN == 0 {
178            Some(&mut self.buf[self.index][..])
179        } else {
180            None
181        }
182    }
183
184    /// Submit the current TX buffer to the DMA for transmission.
185    pub fn transmit(&mut self, len: usize) {
186        let d = &mut self.desc[self.index];
187
188        // Set buffer pointer and length
189        d.set_tdes2(self.buf[self.index].as_ptr() as u32);
190        d.set_tdes1(len as u32);
191
192        // Set ownership to DMA with fence
193        fence(Ordering::Release);
194        let base = d.tdes0() & !TDES0_OWN;
195        d.set_tdes0(base | TDES0_OWN);
196
197        // Advance ring index
198        self.index = (self.index + 1) % N;
199
200        // Poll transmit demand
201        T::regs().dmatpdr().write(|w| w.set_tpd(0));
202    }
203
204    /// Number of descriptors in the ring.
205    pub fn len(&self) -> usize {
206        N
207    }
208
209    /// Whether the TX DMA left its ring.
210    ///
211    /// On the CH32V307, after a frame is aborted for excessive collisions
212    /// (half duplex), the TX DMA can take the start of a TX buffer for its next
213    /// descriptor. Reading frame bytes as descriptors then leaves it suspended
214    /// or stuck reading data, and TX stops. Writing DMATDLAR while it is
215    /// stopped does not bring it back: it resumes from the position it kept. A
216    /// DMA software reset restarts it from the ring.
217    pub(super) fn derailed(&self) -> bool {
218        let regs = T::regs();
219        // Any state but stopped: it was seen suspended (TPS 6) and reading (TPS 3).
220        regs.dmasr().read().tps() != 0 && {
221            let current = regs.dmachtdr().read().htdap() as usize;
222            let offset = current.wrapping_sub(self.desc.as_ptr() as usize);
223            offset >= core::mem::size_of::<[TDes; N]>() || offset % core::mem::size_of::<TDes>() != 0
224        }
225    }
226}
227
228/// An RX DMA descriptor ring.
229pub struct RDesRing<'d, T: Instance, const N: usize> {
230    desc: &'d mut [RDes; N],
231    buf: &'d mut [[u8; RX_BUF_SIZE]; N],
232    index: usize,
233    _phantom: PhantomData<T>,
234}
235
236impl<'d, T: Instance, const N: usize> RDesRing<'d, T, N> {
237    pub(super) fn new(desc: &'d mut [RDes; N], buf: &'d mut [[u8; RX_BUF_SIZE]; N]) -> Self {
238        for i in 0..N {
239            let next = if i + 1 < N {
240                &desc[i + 1] as *const RDes as u32
241            } else {
242                &desc[0] as *const RDes as u32
243            };
244
245            desc[i].set_rdes1(RDES1_RCH | (RX_BUF_SIZE as u32 & 0x1FFF));
246            desc[i].set_rdes2(buf[i].as_ptr() as u32);
247            desc[i].set_rdes3(next);
248        }
249        // Last descriptor chains back to first (already set in loop above).
250
251        let mut ring = Self {
252            desc,
253            buf,
254            index: 0,
255            _phantom: PhantomData,
256        };
257        ring.reset();
258        ring
259    }
260
261    /// Discard received frames and restart the ring. DMA must be stopped,
262    /// either before its first start or after a completed MAC/DMA software reset.
263    pub(super) fn reset(&mut self) {
264        for d in self.desc.iter_mut() {
265            d.set_rdes0(RDES0_OWN);
266        }
267        self.index = 0;
268        T::regs()
269            .dmardlar()
270            .write(|w| w.set_srl(&self.desc[0] as *const RDes as u32));
271    }
272
273    /// Returns a reference to the received frame data if a complete frame is available.
274    pub fn available(&mut self) -> Option<&mut [u8]> {
275        // A buffer released just before DMA suspended needs a demand poll.
276        // On a full ring that would only raise RBUS again, waking the driver
277        // in a loop until a buffer is released.
278        if T::regs().dmasr().read().rps() == 0b100 && self.dma_owns_current() {
279            self.resume_rx();
280        }
281
282        // Skip frames spanning several descriptors and erroneous frames, so
283        // that good frames queued behind them are not delayed until the next
284        // interrupt. Ends at a good frame or at a descriptor the DMA owns
285        // (every skipped descriptor is given back to the DMA).
286        let rdes0 = loop {
287            let rdes0 = self.desc[self.index].rdes0();
288            if rdes0 & RDES0_OWN != 0 {
289                self.release_stuck_descriptor();
290                return None;
291            }
292            let single = rdes0 & (RDES0_FS | RDES0_LS) == (RDES0_FS | RDES0_LS);
293            if single && rdes0 & RDES0_ES == 0 {
294                break rdes0;
295            }
296            self.pop_packet();
297        };
298
299        // Extract frame length (includes CRC, subtract 4)
300        let len = ((rdes0 & RDES0_FL_MASK) >> RDES0_FL_SHIFT) as usize;
301        let len = if len >= 4 { len - 4 } else { len };
302        let len = len.min(RX_BUF_SIZE);
303
304        fence(Ordering::Acquire);
305
306        Some(&mut self.buf[self.index][..len])
307    }
308
309    /// Release the current RX descriptor back to DMA ownership.
310    pub fn pop_packet(&mut self) {
311        let d = &mut self.desc[self.index];
312
313        fence(Ordering::Release);
314        d.set_rdes0(RDES0_OWN);
315
316        // Publish ownership before notifying DMA that buffers are available.
317        fence(Ordering::SeqCst);
318        self.resume_rx();
319        self.index = (self.index + 1) % N;
320    }
321
322    /// Recover the CH32V307 rev 0x10 RX stall after the DMA runs out of
323    /// descriptors (`RBUS`).
324    ///
325    /// On that silicon the DMA can stop with `DMACHRDR` on a descriptor it
326    /// owns while the next one stays with the CPU, and a demand poll does not
327    /// move it. Giving that next descriptor back to the DMA loses its frame
328    /// but lets reception continue. In a healthy ring a DMA-owned descriptor
329    /// is never followed by a CPU-owned one, so this cannot fire elsewhere.
330    fn release_stuck_descriptor(&mut self) {
331        let next = (self.index + 1) % N;
332        if next == self.index {
333            return;
334        }
335        let d = &mut self.desc[next];
336        if d.rdes0() & RDES0_OWN != 0 {
337            return;
338        }
339        fence(Ordering::Release);
340        d.set_rdes0(RDES0_OWN);
341        fence(Ordering::SeqCst);
342        self.demand_poll();
343    }
344
345    fn resume_rx(&self) {
346        let r = T::regs();
347        let status = r.dmasr().read();
348
349        // The interrupt handler may already have cleared RBUS. The process
350        // state still tells us whether RX DMA is suspended waiting for buffers.
351        if status.rps() == 0b100 {
352            r.dmasr().write(|w| w.set_rbus(status.rbus()));
353            self.demand_poll();
354        }
355    }
356
357    /// Whether the descriptor at the DMA's cursor belongs to DMA. An off-ring
358    /// cursor does not prevent a demand poll, so recovery can still proceed.
359    fn dma_owns_current(&self) -> bool {
360        let current = T::regs().dmachrdr().read().hrdap();
361        self.desc
362            .iter()
363            .find(|d| *d as *const RDes as u32 == current)
364            .map_or(true, |d| d.rdes0() & RDES0_OWN != 0)
365    }
366
367    fn demand_poll(&self) {
368        T::regs().dmarpdr().write(|w| w.set_rpd(0));
369    }
370}
371
372// ============================================================================
373// Packet buffer queue (static allocation)
374// ============================================================================
375
376/// Static storage for DMA descriptors and packet buffers.
377///
378/// `TX` and `RX` are the number of descriptors (and buffers) in each ring.
379/// Typical values: 2-4 for TX, 4-8 for RX.
380///
381/// # Usage
382///
383/// ```ignore
384/// static QUEUE: StaticCell<PacketQueue<4, 4>> = StaticCell::new();
385/// let queue = QUEUE.init(PacketQueue::new());
386/// ```
387pub struct PacketQueue<const TX: usize, const RX: usize> {
388    pub(super) tx_desc: [TDes; TX],
389    pub(super) rx_desc: [RDes; RX],
390    pub(super) tx_buf: [[u8; TX_BUF_SIZE]; TX],
391    pub(super) rx_buf: [[u8; RX_BUF_SIZE]; RX],
392}
393
394impl<const TX: usize, const RX: usize> PacketQueue<TX, RX> {
395    /// Create a new zeroed packet queue.
396    pub const fn new() -> Self {
397        Self {
398            tx_desc: [const { TDes::new() }; TX],
399            rx_desc: [const { RDes::new() }; RX],
400            tx_buf: [[0u8; TX_BUF_SIZE]; TX],
401            rx_buf: [[0u8; RX_BUF_SIZE]; RX],
402        }
403    }
404}
405
406/// Token for receiving a single packet from the DMA ring.
407///
408/// Dropped without `consume()`, it leaves the frame in its descriptor, unless a
409/// later recovery reset discards it.
410pub struct RxToken<'a, 'd, T: Instance, const N: usize> {
411    pub(super) rx: &'a mut RDesRing<'d, T, N>,
412    pub(super) len: usize,
413}
414
415impl<T: Instance, const N: usize> RxToken<'_, '_, T, N> {
416    /// Length of the frame, without its FCS.
417    pub fn len(&self) -> usize {
418        self.len
419    }
420}
421
422/// Token for transmitting a single packet via the DMA ring.
423pub struct TxToken<'a, 'd, T: Instance, const N: usize> {
424    pub(super) tx: &'a mut TDesRing<'d, T, N>,
425}
426
427impl<'a, 'd, T: Instance, const N: usize> embassy_net_driver::RxToken for RxToken<'a, 'd, T, N> {
428    fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, f: F) -> R {
429        let pkt = self.rx.available().expect("RxToken created without available packet");
430        let r = f(pkt);
431        self.rx.pop_packet();
432        r
433    }
434}
435
436impl<'a, 'd, T: Instance, const N: usize> embassy_net_driver::TxToken for TxToken<'a, 'd, T, N> {
437    fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
438        let pkt = self.tx.available().expect("TxToken created without available buffer");
439        let r = f(&mut pkt[..len]);
440        self.tx.transmit(len);
441        r
442    }
443}