1use 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#[non_exhaustive]
26#[derive(Copy, Clone)]
27pub struct SlaveConfig {
28 pub mode: Mode,
29 pub bit_order: BitOrder,
30 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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
46#[cfg_attr(feature = "defmt", derive(defmt::Format))]
47pub enum SlaveError {
48 Overrun,
51 Dma,
53 NoPause,
55 LostLap,
61}
62
63#[derive(Debug, Copy, Clone, PartialEq, Eq)]
65#[cfg_attr(feature = "defmt", derive(defmt::Format))]
66pub struct Half {
67 pub index: usize,
69 pub missed: u32,
74}
75
76const NSS_SPIN: u32 = 100_000;
79
80pub 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 half_len: usize,
95 active_half_len: usize,
97 delivered: u32,
98 config: SlaveConfig,
99 _phantom: PhantomData<&'d mut [W]>,
100}
101
102unsafe 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 #[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 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 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 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 pub fn half_len(&self) -> usize {
164 self.active_half_len
165 }
166
167 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); 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 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 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 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 pub fn restart(&mut self) -> Result<(), SlaveError> {
220 self.stop();
221 self.start()
222 }
223
224 pub async fn next_half(&mut self) -> Result<Half, SlaveError> {
226 poll_fn(|cx| {
227 self.rx.register_waker(cx.waker());
228 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 if T::REGS.statr().read().ovr() {
261 return Some(SlaveError::Overrun);
262 }
263 None
264 }
265
266 pub fn rx_half(&self, index: usize) -> &[W] {
269 assert!(index < 2);
270 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 pub fn tx_half_mut(&mut self, index: usize) -> &mut [W] {
281 assert!(index < 2);
282 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 pub fn half_mut(&mut self, index: usize) -> (&[W], &mut [W]) {
294 assert!(index < 2);
295 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 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 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 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}