atsamd_hal/dmac/
transfer.rs

1//! # DMA transfer abstractions
2//!
3//! # Transfer types
4//!
5//! Four basic transfer types are supported:
6//!
7//! * Incrementing-source to incrementing-destination (normally used for
8//!   memory-to-memory transfers)
9//!
10//! * Incrementing-source to fixed-destination (normally used for
11//!   memory-to-peripheral transfers)
12//!
13//! * Fixed-source to incrementing-destination (normally used for
14//!   peripheral-to-memory transfers)
15//!
16//! * Fixed-source to fixed-destination (normally used for
17//!   peripheral-to-peripheral transfers)
18//!
19//! # Beat sizes
20//!
21//! A beat is an atomic, uninterruptible transfer size.Three beat sizes are
22//! supported:
23//!
24//! * Byte-per-byte (8 bit beats);
25//!
26//! * Halfword-per-halfword (16 bit beats);
27//!
28//! * Word-per-word (32 bit beats);
29//!
30//! The correct beat size will automatically be selected in function of the type
31//! of the source and destination buffers.
32//!
33//! # One-shot vs circular transfers
34//!
35//! If the transfer is setup as one-shot (`circular == false`), the
36//! transfer will run once and stop. Otherwise, if `circular == true`, then the
37//! transfer will be set as circular, meaning it will restart a new, identical
38//! block transfer when the current block transfer is complete. This is
39//! particularly useful when combined with a TC/TCC trigger source, for instance
40//! to periodically retreive a sample from an ADC and send it to a circular
41//! buffer, or send a sample to a DAC.
42//!
43//! # Starting a transfer
44//!
45//! A transfer is started by calling [`Transfer::begin`]. You will be
46//! required to supply a trigger source and a trigger action.
47//!
48//! # Waiting for a transfer to complete
49//!
50//! A transfer can waited upon by calling [`wait`](Transfer::wait). This is a
51//! _blocking_ method, meaning it will busy-wait until the transfer is
52//! completed. When it returns, it will release the source and destination
53//! buffers, as well as the DMA channel.
54//!
55//! # Interrupting (stopping) a transfer
56//!
57//! A transfer can be stopped (regardless of whether it has completed or not) by
58//! calling [`stop`](Transfer::stop). This is _not_ a blocking method,
59//! meaning it will stop the transfer and immediately return. When it returns,
60//! it will release the source and destination buffers, as well as the DMA
61//! channel.
62//!
63//! # Trigger sources
64//!
65//! Most peripherals can issue triggers to a DMA channel. A software trigger is
66//! also available (see [`trigger`](Transfer::software_trigger)). See
67//! ATSAMD21 datasheet, table 19-8 for all available trigger sources.
68//!
69//! # Trigger actions
70//!
71//! Three trigger actions are available:
72//!
73//! * BLOCK: One trigger required for each block transfer. In the context of
74//!   this driver, one Transfer is equivalent to one Block transfer.
75//!
76//! * BEAT: One trigger required for each beat transfer. In the context of this
77//!   driver, the beat size will depend on the type of buffer used (8, 16 or 32
78//!   bits).
79//!
80//! * TRANSACTION: One trigger required for a full DMA transaction. this is
81//!   useful for circular transfers in the context of this driver. One trigger
82//!   will set off the transaction, that will now run uninterrupted until it is
83//!   stopped.
84
85use super::{
86    channel::{AnyChannel, Busy, Channel, ChannelId, InterruptFlags, Ready},
87    dma_controller::{TriggerAction, TriggerSource},
88    Error, ReadyChannel, Result,
89};
90use crate::typelevel::{Is, Sealed};
91use modular_bitfield::prelude::*;
92
93//==============================================================================
94// Beat
95//==============================================================================
96
97/// Useable beat sizes for DMA transfers
98#[derive(Clone, Copy, BitfieldSpecifier)]
99#[bits = 2]
100pub enum BeatSize {
101    /// Byte = [`u8`](core::u8)
102    Byte = 0x00,
103    /// Half word = [`u16`](core::u16)
104    HalfWord = 0x01,
105    /// Word = [`u32`](core::u32)
106    Word = 0x02,
107}
108
109/// Convert 8, 16 and 32 bit types
110/// into [`BeatSize`]
111///
112/// # Safety
113///
114/// This trait should not be implemented outside of the crate-provided
115/// implementations
116pub unsafe trait Beat: Sealed {
117    /// Convert to BeatSize enum
118    const BEATSIZE: BeatSize;
119}
120
121macro_rules! impl_beat {
122    ( $( ($Type:ty, $Size:ident) ),+ ) => {
123        $(
124            unsafe impl Beat for $Type {
125                const BEATSIZE: BeatSize = BeatSize::$Size;
126            }
127        )+
128    };
129}
130
131impl_beat!(
132    (u8, Byte),
133    (i8, Byte),
134    (u16, HalfWord),
135    (i16, HalfWord),
136    (u32, Word),
137    (i32, Word),
138    (f32, Word)
139);
140
141//==============================================================================
142// Buffer
143//==============================================================================
144
145/// Buffer useable by the DMAC.
146///
147/// # Safety
148///
149/// This trait should only be implemented for valid DMAC sources/sinks. That is,
150/// you need to make sure that:
151/// * `dma_ptr` points to a valid memory location useable by the DMAC
152/// * `incrementing` is correct for the source/sink. For example, an `&[u8]` of
153///   size one is not incrementing.
154/// * `buffer_len` is correct for the source/sink.
155pub unsafe trait Buffer {
156    /// DMAC beat size
157    type Beat: Beat;
158    /// Pointer to the buffer. If the buffer is incrementing, the address should
159    /// point to one past the last beat transfer in the block.
160    fn dma_ptr(&mut self) -> *mut Self::Beat;
161    /// Return whether the buffer pointer should be incrementing or not
162    fn incrementing(&self) -> bool;
163    /// Buffer length in beats
164    fn buffer_len(&self) -> usize;
165}
166
167unsafe impl<T: Beat, const N: usize> Buffer for &mut [T; N] {
168    type Beat = T;
169    #[inline]
170    fn dma_ptr(&mut self) -> *mut Self::Beat {
171        let ptrs = self.as_mut_ptr_range();
172        if self.incrementing() {
173            ptrs.end
174        } else {
175            ptrs.start
176        }
177    }
178
179    #[inline]
180    fn incrementing(&self) -> bool {
181        N > 1
182    }
183
184    #[inline]
185    fn buffer_len(&self) -> usize {
186        N
187    }
188}
189
190unsafe impl<T: Beat> Buffer for &mut [T] {
191    type Beat = T;
192    #[inline]
193    fn dma_ptr(&mut self) -> *mut Self::Beat {
194        let ptrs = self.as_mut_ptr_range();
195        if self.incrementing() {
196            ptrs.end
197        } else {
198            ptrs.start
199        }
200    }
201
202    #[inline]
203    fn incrementing(&self) -> bool {
204        self.len() > 1
205    }
206
207    #[inline]
208    fn buffer_len(&self) -> usize {
209        self.len()
210    }
211}
212
213unsafe impl<T: Beat> Buffer for &mut T {
214    type Beat = T;
215    #[inline]
216    fn dma_ptr(&mut self) -> *mut Self::Beat {
217        *self as *mut T
218    }
219
220    #[inline]
221    fn incrementing(&self) -> bool {
222        false
223    }
224
225    #[inline]
226    fn buffer_len(&self) -> usize {
227        1
228    }
229}
230
231//==============================================================================
232// BufferPair
233//==============================================================================
234
235/// Struct holding the source and destination buffers of a
236/// [`Transfer`].
237pub struct BufferPair<S, D = S>
238where
239    S: Buffer,
240    D: Buffer<Beat = S::Beat>,
241{
242    /// Source buffer
243    pub source: S,
244    /// Destination buffer
245    pub destination: D,
246}
247
248//==============================================================================
249// AnyBufferPair
250//==============================================================================
251
252pub trait AnyBufferPair: Sealed + Is<Type = SpecificBufferPair<Self>> {
253    type Src: Buffer;
254    type Dst: Buffer<Beat = BufferPairBeat<Self>>;
255}
256
257pub type SpecificBufferPair<C> = BufferPair<<C as AnyBufferPair>::Src, <C as AnyBufferPair>::Dst>;
258
259pub type BufferPairSrc<B> = <B as AnyBufferPair>::Src;
260pub type BufferPairDst<B> = <B as AnyBufferPair>::Dst;
261pub type BufferPairBeat<B> = <BufferPairSrc<B> as Buffer>::Beat;
262
263impl<S, D> Sealed for BufferPair<S, D>
264where
265    S: Buffer,
266    D: Buffer<Beat = S::Beat>,
267{
268}
269
270impl<S, D> AnyBufferPair for BufferPair<S, D>
271where
272    S: Buffer,
273    D: Buffer<Beat = S::Beat>,
274{
275    type Src = S;
276    type Dst = D;
277}
278
279impl<S, D> AsRef<Self> for BufferPair<S, D>
280where
281    S: Buffer,
282    D: Buffer<Beat = S::Beat>,
283{
284    #[inline]
285    fn as_ref(&self) -> &Self {
286        self
287    }
288}
289
290impl<S, D> AsMut<Self> for BufferPair<S, D>
291where
292    S: Buffer,
293    D: Buffer<Beat = S::Beat>,
294{
295    #[inline]
296    fn as_mut(&mut self) -> &mut Self {
297        self
298    }
299}
300
301// TODO change source and dest types to Pin? (see https://docs.rust-embedded.org/embedonomicon/dma.html#immovable-buffers)
302/// DMA transfer, owning the resources until the transfer is done and
303/// [`Transfer::wait`] is called.
304pub struct Transfer<Chan, Buf>
305where
306    Buf: AnyBufferPair,
307    Chan: AnyChannel,
308{
309    chan: Chan,
310    buffers: Buf,
311    complete: bool,
312}
313
314impl<C, S, D, R> Transfer<C, BufferPair<S, D>>
315where
316    S: Buffer + 'static,
317    D: Buffer<Beat = S::Beat> + 'static,
318    C: AnyChannel<Status = R>,
319    R: ReadyChannel,
320{
321    /// Safely construct a new `Transfer`. To guarantee memory safety, both
322    /// buffers are required to be `'static`.
323    /// Refer [here](https://docs.rust-embedded.org/embedonomicon/dma.html#memforget) or
324    /// [here](https://blog.japaric.io/safe-dma/) for more information.
325    ///
326    /// If two array references can be used as source and destination buffers
327    /// (as opposed to slices), then it is recommended to use the
328    /// [`Transfer::new_from_arrays`] method instead.
329    ///
330    /// # Errors
331    ///
332    /// Returns [`Error::LengthMismatch`] if both
333    /// buffers have a length > 1 and are not of equal length.
334    #[allow(clippy::new_ret_no_self)]
335    #[inline]
336    pub fn new(
337        chan: C,
338        source: S,
339        destination: D,
340        circular: bool,
341    ) -> Result<Transfer<C, BufferPair<S, D>>> {
342        Self::check_buffer_pair(&source, &destination)?;
343
344        // SAFETY: The safety checks are done by the function signature and the buffer
345        // length verification
346        Ok(unsafe { Self::new_unchecked(chan, source, destination, circular) })
347    }
348}
349
350impl<S, D, C> Transfer<C, BufferPair<S, D>>
351where
352    S: Buffer,
353    D: Buffer<Beat = S::Beat>,
354    C: AnyChannel,
355{
356    #[inline]
357    pub(super) fn check_buffer_pair(source: &S, destination: &D) -> Result<()> {
358        let src_len = source.buffer_len();
359        let dst_len = destination.buffer_len();
360
361        if src_len > 1 && dst_len > 1 && src_len != dst_len {
362            Err(Error::LengthMismatch)
363        } else {
364            Ok(())
365        }
366    }
367}
368
369impl<C, S, D, R> Transfer<C, BufferPair<S, D>>
370where
371    S: Buffer,
372    D: Buffer<Beat = S::Beat>,
373    C: AnyChannel<Status = R>,
374    R: ReadyChannel,
375{
376    /// Construct a new `Transfer` without checking for memory safety.
377    ///
378    /// # Safety
379    ///
380    /// To guarantee the safety of creating a `Transfer` using this method, you
381    /// must uphold some invariants:
382    ///
383    /// * A `Transfer` holding a `Channel<Id, Running>` must *never* be dropped.
384    ///   It should *always* be explicitly be `wait`ed upon or `stop`ped.
385    ///
386    /// * The size in bytes or the source and destination buffers should be
387    ///   exacly the same, unless one or both buffers are of length 1. The
388    ///   transfer length will be set to the longest of both buffers if they are
389    ///   not of equal size.
390    #[inline]
391    pub unsafe fn new_unchecked(
392        mut chan: C,
393        mut source: S,
394        mut destination: D,
395        circular: bool,
396    ) -> Transfer<C, BufferPair<S, D>> {
397        chan.as_mut()
398            .fill_descriptor(&mut source, &mut destination, circular);
399
400        let buffers = BufferPair {
401            source,
402            destination,
403        };
404
405        Transfer {
406            buffers,
407            chan,
408            complete: false,
409        }
410    }
411}
412
413impl<C, S, D> Transfer<C, BufferPair<S, D>>
414where
415    S: Buffer,
416    D: Buffer<Beat = S::Beat>,
417    C: AnyChannel<Status = Ready>,
418{
419    /// Begin DMA transfer in blocking mode. If [`TriggerSource::Disable`] is
420    /// used, a software trigger will be issued to the DMA channel to launch
421    /// the transfer. Is is therefore not necessary, in most cases, to manually
422    /// issue a software trigger to the channel.
423    #[inline]
424    pub fn begin(
425        mut self,
426        trig_src: TriggerSource,
427        trig_act: TriggerAction,
428    ) -> Transfer<Channel<ChannelId<C>, Busy>, BufferPair<S, D>> {
429        // Reset the complete flag before triggering the transfer.
430        // This way an interrupt handler could set complete to true
431        // before this function returns.
432        self.complete = false;
433
434        let chan = self.chan.into().start(trig_src, trig_act);
435
436        Transfer {
437            buffers: self.buffers,
438            chan,
439            complete: self.complete,
440        }
441    }
442
443    /// Free the [`Transfer`] and return the resources it holds.
444    ///
445    /// Similar to [`stop`](Transfer::stop), but it acts on a [`Transfer`]
446    /// holding a [`Ready`] channel, so there is no need to explicitly stop the
447    /// transfer.
448    pub fn free(self) -> (Channel<ChannelId<C>, Ready>, S, D) {
449        (
450            self.chan.into(),
451            self.buffers.source,
452            self.buffers.destination,
453        )
454    }
455}
456
457impl<B, C, R, const N: usize> Transfer<C, BufferPair<&'static mut [B; N]>>
458where
459    B: 'static + Beat,
460    C: AnyChannel<Status = R>,
461    R: ReadyChannel,
462{
463    /// Create a new `Transfer` from static array references of the same type
464    /// and length. When two array references are available (instead of slice
465    /// references), it is recommended to use this function over
466    /// [`Transfer::new`](Transfer::new), because it provides compile-time
467    /// checking that the array lengths match. It therefore does not panic, and
468    /// saves some runtime checking of the array lengths.
469    #[inline]
470    pub fn new_from_arrays(
471        chan: C,
472        source: &'static mut [B; N],
473        destination: &'static mut [B; N],
474        circular: bool,
475    ) -> Self {
476        unsafe { Self::new_unchecked(chan, source, destination, circular) }
477    }
478}
479
480impl<S, D, C> Transfer<C, BufferPair<S, D>>
481where
482    S: Buffer,
483    D: Buffer<Beat = S::Beat>,
484    C: AnyChannel<Status = Busy>,
485{
486    /// Issue a software trigger request to the corresponding channel.
487    /// Note that is not guaranteed that the trigger request will register,
488    /// if a trigger request is already pending for the channel.
489    #[inline]
490    pub fn software_trigger(&mut self) {
491        self.chan.as_mut().software_trigger();
492    }
493
494    /// Unsafely and mutably borrow the source buffer
495    ///
496    /// # Safety
497    ///
498    /// The source buffer should never be borrowed when a transfer is in
499    /// progress, as it is getting mutated or read in another context (ie,
500    /// the DMAC hardware "thread").
501    #[inline]
502    pub(crate) unsafe fn borrow_source(&mut self) -> &mut S {
503        &mut self.buffers.source
504    }
505
506    /// Unsafely and mutably borrow the destination buffer.
507    /// # Safety
508    ///
509    /// The destination buffer should never be borrowed when a transfer is in
510    /// progress, as it is getting mutated or read in another context (ie,
511    /// the DMAC hardware "thread").
512    #[inline]
513    pub(crate) unsafe fn borrow_destination(&mut self) -> &mut D {
514        &mut self.buffers.destination
515    }
516
517    /// Wait for the DMA transfer to complete and release all owned
518    /// resources
519    ///
520    /// # Blocking: This method may block
521    #[inline]
522    pub fn wait(mut self) -> (Channel<ChannelId<C>, Ready>, S, D) {
523        // Wait for transfer to complete
524        while !self.complete() {}
525        self.stop()
526    }
527
528    /// Check if the transfer has completed
529    #[inline]
530    pub fn complete(&mut self) -> bool {
531        if !self.complete {
532            let chan = self.chan.as_mut();
533            let complete = chan.xfer_complete();
534            self.complete = complete;
535        }
536        self.complete
537    }
538
539    /// Checks and clears the block transfer complete interrupt flag
540    #[inline]
541    pub fn block_transfer_interrupt(&mut self) -> bool {
542        self.chan
543            .as_mut()
544            .check_and_clear_interrupts(InterruptFlags::new().with_tcmpl(true))
545            .tcmpl()
546    }
547
548    /// Modify a completed transfer with new `source` and `destination`, then
549    /// restart.
550    ///
551    /// Returns a Result containing the source and destination from the
552    /// completed transfer. Returns `Err(_)` if the buffer lengths are
553    /// mismatched or if the previous transfer has not yet completed.
554    #[inline]
555    pub fn recycle(&mut self, mut source: S, mut destination: D) -> Result<(S, D)> {
556        Self::check_buffer_pair(&source, &destination)?;
557
558        if !self.complete() {
559            return Err(Error::InvalidState);
560        }
561
562        // Circular transfers won't ever complete, so never re-fill as one
563        unsafe {
564            self.chan
565                .as_mut()
566                .fill_descriptor(&mut source, &mut destination, false);
567        }
568
569        let new_buffers = BufferPair {
570            source,
571            destination,
572        };
573
574        let old_buffers = core::mem::replace(&mut self.buffers, new_buffers);
575        self.chan.as_mut().restart();
576        Ok((old_buffers.source, old_buffers.destination))
577    }
578
579    /// Modify a completed transfer with a new `destination`, then restart.
580    ///
581    /// Returns a Result containing the destination from the
582    /// completed transfer. Returns `Err(_)` if the buffer lengths are
583    /// mismatched or if the previous transfer has not yet completed.
584    #[inline]
585    pub fn recycle_source(&mut self, mut destination: D) -> Result<D> {
586        Self::check_buffer_pair(&self.buffers.source, &destination)?;
587
588        if !self.complete() {
589            return Err(Error::InvalidState);
590        }
591
592        // Circular transfers won't ever complete, so never re-fill as one
593        unsafe {
594            self.chan
595                .as_mut()
596                .fill_descriptor(&mut self.buffers.source, &mut destination, false);
597        }
598
599        let old_destination = core::mem::replace(&mut self.buffers.destination, destination);
600        self.chan.as_mut().restart();
601        Ok(old_destination)
602    }
603
604    /// Modify a completed transfer with a new `source`, then restart.
605    ///
606    /// Returns a Result containing the source from the
607    /// completed transfer. Returns `Err(_)` if the buffer lengths are
608    /// mismatched or if the previous transfer has not yet completed.
609    #[inline]
610    pub fn recycle_destination(&mut self, mut source: S) -> Result<S> {
611        Self::check_buffer_pair(&source, &self.buffers.destination)?;
612
613        if !self.complete() {
614            return Err(Error::InvalidState);
615        }
616
617        // Circular transfers won't ever complete, so never re-fill as one
618        unsafe {
619            self.chan
620                .as_mut()
621                .fill_descriptor(&mut source, &mut self.buffers.destination, false);
622        }
623
624        let old_source = core::mem::replace(&mut self.buffers.source, source);
625        self.chan.as_mut().restart();
626        Ok(old_source)
627    }
628
629    /// Non-blocking; Immediately stop the DMA transfer and release all owned
630    /// resources
631    #[inline]
632    pub fn stop(self) -> (Channel<ChannelId<C>, Ready>, S, D) {
633        // `free()` stops the transfer, waits for the burst to finish, and emits a
634        // compiler fence.
635        let chan = self.chan.into().free();
636        (chan, self.buffers.source, self.buffers.destination)
637    }
638}