Skip to main content

ch32_hal/spi/
slave.rs

1//! SPI slave streaming over circular DMA, in halves and in place.
2//!
3//! For a master that clocks continuous bursts (e.g. an FPGA streaming audio frames): RX and
4//! TX each run a circular DMA over a buffer of two halves. When RX completes a half, that
5//! half holds received words and the same half of the TX buffer has gone out (TX runs a
6//! word or two ahead of RX), so the owner can refill it -- it goes out one pass later.
7//!
8//! Hardware NSS: each burst starts on a word boundary as long as the slave was enabled
9//! while NSS was high. [`SpiSlaveRing::start`] waits for a pause between bursts to do that.
10//! If the stream ever slips (a mis-aligned word), [`SpiSlaveRing::restart`] resets the
11//! peripheral and starts again in a pause.
12
13use core::future::poll_fn;
14use core::marker::PhantomData;
15use core::task::Poll;
16
17use embedded_hal::spi::Mode;
18
19use super::{BitOrder, CsPin, Instance, MisoPin, MosiPin, RxDma, SckPin, TxDma, Word};
20use crate::dma::{CircularTransfer, Priority, Request, RingPositionReader};
21use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin, Speed};
22use crate::Peri;
23
24/// Slave configuration. The clock comes from the master.
25#[non_exhaustive]
26#[derive(Copy, Clone)]
27pub struct SlaveConfig {
28    pub mode: Mode,
29    pub bit_order: BitOrder,
30    /// DMA priority of both channels
31    pub priority: Priority,
32}
33
34impl Default for SlaveConfig {
35    fn default() -> Self {
36        Self {
37            mode: embedded_hal::spi::MODE_0,
38            bit_order: BitOrder::MsbFirst,
39            priority: Priority::VeryHigh,
40        }
41    }
42}
43
44/// Slave streaming errors. After any of them, [`SpiSlaveRing::restart`].
45#[derive(Debug, Copy, Clone, PartialEq, Eq)]
46#[cfg_attr(feature = "defmt", derive(defmt::Format))]
47pub enum SlaveError {
48    /// The SPI overran (a word arrived before the last one was taken). It stops receiving
49    /// until reset.
50    Overrun,
51    /// A DMA transfer error stopped a channel.
52    Dma,
53    /// NSS stayed low: no pause between bursts to start in.
54    NoPause,
55    /// The RX position went backwards: the DMA interrupt was held off for more than a pass
56    /// and counted the passes it missed as one, and [`SpiSlaveRing::next_half`] was polled
57    /// in between (by a wake-up from elsewhere, e.g. inside a `select`). Without such a poll
58    /// the same hold-off shows up only as a short [`Half::missed`]. Run the DMA interrupt
59    /// above code that can take that long.
60    LostLap,
61}
62
63/// A completed half.
64#[derive(Debug, Copy, Clone, PartialEq, Eq)]
65#[cfg_attr(feature = "defmt", derive(defmt::Format))]
66pub struct Half {
67    /// 0 or 1: read [`SpiSlaveRing::rx_half`], refill [`SpiSlaveRing::tx_half_mut`]
68    pub index: usize,
69    /// halves completed since the last [`SpiSlaveRing::next_half`] that weren't returned (the
70    /// owner was late; their RX data is lost and their TX half went out again unchanged).
71    /// A lower bound: whole passes during which the DMA interrupt was held off aren't
72    /// counted (see [`SlaveError::LostLap`]); `index` is right either way.
73    pub missed: u32,
74}
75
76/// Spins on NSS while waiting for a pause: generously more than one frame period at the
77/// slowest rate a master is expected to use.
78const NSS_SPIN: u32 = 100_000;
79
80/// SPI slave with RX and TX on circular DMA (see the module docs).
81pub struct SpiSlaveRing<'d, T: Instance, W: Word> {
82    _peri: Peri<'d, T>,
83    nss: Peri<'d, AnyPin>,
84    _sck: Peri<'d, AnyPin>,
85    _mosi: Peri<'d, AnyPin>,
86    _miso: Peri<'d, AnyPin>,
87    rx: CircularTransfer<'d>,
88    tx: CircularTransfer<'d>,
89    rx_request: Request,
90    tx_request: Request,
91    rx_buf: *mut [W],
92    tx_buf: *mut [W],
93    /// set by `set_half_len`, used from the next `start`
94    half_len: usize,
95    /// what the DMA runs with
96    active_half_len: usize,
97    delivered: u32,
98    config: SlaveConfig,
99    _phantom: PhantomData<&'d mut [W]>,
100}
101
102// SAFETY: the buffers are borrowed exclusively for 'd; the raw pointers only avoid aliasing
103// the halves the DMA is using
104unsafe impl<'d, T: Instance, W: Word + Send> Send for SpiSlaveRing<'d, T, W> {}
105
106impl<'d, T: Instance, W: Word> SpiSlaveRing<'d, T, W> {
107    /// `rx_buf` and `tx_buf` are the same length; each pass uses 2 x `half_len` words of
108    /// them (all of them by default). Nothing runs until [`start`](Self::start).
109    #[allow(clippy::too_many_arguments)]
110    pub fn new<#[cfg(not(afio_h4))] const REMAP: u8>(
111        peri: Peri<'d, T>,
112        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
113        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
114        miso: Peri<'d, if_remap!(impl MisoPin<T, REMAP>)>,
115        nss: Peri<'d, if_remap!(impl CsPin<T, REMAP>)>,
116        rx_dma: Peri<'d, impl RxDma<T>>,
117        tx_dma: Peri<'d, impl TxDma<T>>,
118        rx_buf: &'d mut [W],
119        tx_buf: &'d mut [W],
120        config: SlaveConfig,
121    ) -> Self {
122        assert!(rx_buf.len() == tx_buf.len() && rx_buf.len() >= 2 && rx_buf.len() <= 0xFFFF);
123        apply_remap!();
124
125        // master-driven inputs; NSS pulled high so an unpowered master reads as a pause
126        set_as_af!(sck, AfType::input(Pull::None));
127        set_as_af!(mosi, AfType::input(Pull::None));
128        set_as_af!(nss, AfType::input(Pull::Up));
129        set_as_af!(miso, AfType::output(OutputType::PushPull, Speed::High));
130
131        // clocked from here on, so that `stop` (in drop) never writes an unclocked peripheral
132        T::enable_and_reset();
133
134        let half_len = rx_buf.len() / 2;
135        Self {
136            _peri: peri,
137            nss: nss.into(),
138            _sck: sck.into(),
139            _mosi: mosi.into(),
140            _miso: miso.into(),
141            rx_request: rx_dma.request(),
142            tx_request: tx_dma.request(),
143            rx: CircularTransfer::new(rx_dma),
144            tx: CircularTransfer::new(tx_dma),
145            rx_buf,
146            tx_buf,
147            half_len,
148            active_half_len: half_len,
149            delivered: 0,
150            config,
151            _phantom: PhantomData,
152        }
153    }
154
155    /// Words per half. Safe to call while running: the halves keep their current length
156    /// until the next [`start`](Self::start) / [`restart`](Self::restart).
157    pub fn set_half_len(&mut self, words: usize) {
158        assert!(words > 0 && 2 * words <= self.rx_buf.len());
159        self.half_len = words;
160    }
161
162    /// Words per half in use (since the last [`start`](Self::start)).
163    pub fn half_len(&self) -> usize {
164        self.active_half_len
165    }
166
167    /// Set up SPI and both DMA channels and enable the slave in a pause between bursts
168    /// (NSS high). TX starts with whatever is in the TX buffer.
169    pub fn start(&mut self) -> Result<(), SlaveError> {
170        let regs = T::REGS;
171        T::enable_and_reset();
172        regs.ctlr1().write(|w| {
173            w.set_cpha(self.config.mode.phase == embedded_hal::spi::Phase::CaptureOnSecondTransition);
174            w.set_cpol(self.config.mode.polarity == embedded_hal::spi::Polarity::IdleHigh);
175            w.set_mstr(false);
176            w.set_lsbfirst(self.config.bit_order_lsb());
177            w.set_ssm(false); // hardware NSS
178            w.set_dff(W::size() == crate::dma::word::WordSize::TwoBytes);
179            w.set_spe(false);
180        });
181
182        self.active_half_len = self.half_len;
183        let n = 2 * self.active_half_len;
184        let dr = regs.datar().as_ptr() as *mut W;
185        // SAFETY: the buffers are ours for 'd; the DMA is stopped before they're reconfigured
186        unsafe {
187            let rx = core::ptr::slice_from_raw_parts_mut(self.rx_buf as *mut W, n);
188            let tx = core::ptr::slice_from_raw_parts(self.tx_buf as *const W, n);
189            self.rx
190                .configure_read(self.rx_request, dr, rx, self.config.priority, true);
191            self.tx
192                .configure_write(self.tx_request, tx, dr, self.config.priority, false);
193        }
194        self.delivered = 0;
195
196        // RM order: RX DMA request, channels, TX DMA request (preloads DR), then SPE
197        regs.ctlr2().modify(|w| w.set_rxdmaen(true));
198        self.rx.start();
199        self.tx.start();
200        regs.ctlr2().modify(|w| w.set_txdmaen(true));
201
202        self.enable_in_pause()
203    }
204
205    /// Stop both channels and the slave.
206    pub fn stop(&mut self) {
207        let regs = T::REGS;
208        regs.ctlr1().modify(|w| w.set_spe(false));
209        self.rx.stop();
210        self.tx.stop();
211        regs.ctlr2().modify(|w| {
212            w.set_rxdmaen(false);
213            w.set_txdmaen(false);
214        });
215    }
216
217    /// After a slip or an error: stop, reset the peripheral (clears the shift register,
218    /// the data register and OVR) and start again in a pause.
219    pub fn restart(&mut self) -> Result<(), SlaveError> {
220        self.stop();
221        self.start()
222    }
223
224    /// Wait for the next completed RX half.
225    pub async fn next_half(&mut self) -> Result<Half, SlaveError> {
226        poll_fn(|cx| {
227            self.rx.register_waker(cx.waker());
228            // the TX channel has no half / complete interrupts: this wakes only on its errors
229            self.tx.register_waker(cx.waker());
230            if let Some(e) = self.error() {
231                return Poll::Ready(Err(e));
232            }
233            let pos = self.rx.position();
234            let done = pos
235                .laps
236                .wrapping_mul(2)
237                .wrapping_add((pos.index / self.active_half_len) as u32);
238            let new = done.wrapping_sub(self.delivered);
239            if new == 0 {
240                return Poll::Pending;
241            }
242            if new > u32::MAX / 2 {
243                return Poll::Ready(Err(SlaveError::LostLap));
244            }
245            self.delivered = done;
246            Poll::Ready(Ok(Half {
247                index: (done.wrapping_sub(1) % 2) as usize,
248                missed: new - 1,
249            }))
250        })
251        .await
252    }
253
254    fn error(&self) -> Option<SlaveError> {
255        if self.rx.take_error() | self.tx.take_error() {
256            return Some(SlaveError::Dma);
257        }
258        // with the DMA reading DATAR, this STATR read completes OVR's clear sequence, so an
259        // overrun is reported once; `restart` resets the peripheral either way
260        if T::REGS.statr().read().ovr() {
261            return Some(SlaveError::Overrun);
262        }
263        None
264    }
265
266    /// Received words of half `index` (complete once [`next_half`](Self::next_half)
267    /// returned it, until the DMA comes back to it one pass later).
268    pub fn rx_half(&self, index: usize) -> &[W] {
269        assert!(index < 2);
270        // SAFETY: inside the buffer; the DMA is writing the other half
271        unsafe {
272            core::slice::from_raw_parts(
273                (self.rx_buf as *const W).add(index * self.active_half_len),
274                self.active_half_len,
275            )
276        }
277    }
278
279    /// TX half `index`, free to refill after [`next_half`](Self::next_half) returned it.
280    pub fn tx_half_mut(&mut self, index: usize) -> &mut [W] {
281        assert!(index < 2);
282        // SAFETY: inside the buffer; the DMA is reading the other half
283        unsafe {
284            core::slice::from_raw_parts_mut(
285                (self.tx_buf as *mut W).add(index * self.active_half_len),
286                self.active_half_len,
287            )
288        }
289    }
290
291    /// [`rx_half`](Self::rx_half) and [`tx_half_mut`](Self::tx_half_mut) of the same half,
292    /// together.
293    pub fn half_mut(&mut self, index: usize) -> (&[W], &mut [W]) {
294        assert!(index < 2);
295        // SAFETY: as in `rx_half` and `tx_half_mut`; RX and TX are separate buffers
296        unsafe {
297            (
298                core::slice::from_raw_parts(
299                    (self.rx_buf as *const W).add(index * self.active_half_len),
300                    self.active_half_len,
301                ),
302                core::slice::from_raw_parts_mut(
303                    (self.tx_buf as *mut W).add(index * self.active_half_len),
304                    self.active_half_len,
305                ),
306            )
307        }
308    }
309
310    /// Reads the RX position from anywhere (e.g. a USB SOF interrupt measuring the
311    /// master's clock). It borrows the RX channel for `'d`, so it can't outlive it, but
312    /// it reads the transfer set up by the last [`start`](Self::start) /
313    /// [`restart`](Self::restart): take a new one after each.
314    pub fn rx_position(&self) -> RingPositionReader<'d> {
315        self.rx.reader()
316    }
317
318    fn nss_high(&self) -> bool {
319        self.nss.block().indr().read().idr(self.nss._pin() as usize)
320    }
321
322    /// Set SPE right after NSS rises, so the slave starts at the next burst's first bit.
323    /// A bus that stays idle (NSS high) for `NSS_SPIN` counts as a pause.
324    ///
325    /// NSS merely reading high isn't enough: SPE set a few cycles after a read that came at
326    /// the very end of a pause lands inside the burst, and the stream starts mis-aligned.
327    /// Right after the rising edge the whole pause is margin. On an idle bus this costs
328    /// `NSS_SPIN` polls (a few ms) before enabling.
329    fn enable_in_pause(&mut self) -> Result<(), SlaveError> {
330        let regs = T::REGS;
331        let mut n = 0;
332        while self.nss_high() {
333            n += 1;
334            if n == NSS_SPIN {
335                let idle = critical_section::with(|_| {
336                    let high = self.nss_high();
337                    if high {
338                        regs.ctlr1().modify(|w| w.set_spe(true));
339                    }
340                    high
341                });
342                if idle {
343                    return Ok(());
344                }
345                break;
346            }
347        }
348        // in a burst: catch its end with nothing in between (a burst is a few us)
349        critical_section::with(|_| {
350            let mut n = 0;
351            while !self.nss_high() {
352                n += 1;
353                if n == NSS_SPIN {
354                    return Err(SlaveError::NoPause);
355                }
356            }
357            regs.ctlr1().modify(|w| w.set_spe(true));
358            Ok(())
359        })
360    }
361}
362
363impl<'d, T: Instance, W: Word> Drop for SpiSlaveRing<'d, T, W> {
364    fn drop(&mut self) {
365        self.stop();
366        T::disable();
367    }
368}
369
370impl SlaveConfig {
371    fn bit_order_lsb(&self) -> bool {
372        match self.bit_order {
373            #[cfg(not(spi_v0))]
374            BitOrder::LsbFirst => true,
375            BitOrder::MsbFirst => false,
376        }
377    }
378}