Skip to main content

ch32_hal/dma/
dma_bdma.rs

1use core::future::{poll_fn, Future};
2use core::pin::Pin;
3#[cfg(not(dma_v4x7))]
4use core::sync::atomic::compiler_fence;
5#[cfg(dma_v4x7)]
6use core::sync::atomic::AtomicBool;
7use core::sync::atomic::{fence, AtomicUsize, Ordering};
8use core::task::{Context, Poll, Waker};
9
10use embassy_sync::waitqueue::AtomicWaker;
11
12use super::ringbuffer::{DmaCtrl, OverrunError, ReadableDmaRingBuffer, WritableDmaRingBuffer};
13use super::word::{Word, WordSize};
14use super::{AnyChannel, Channel, Dir, Request, STATE};
15use crate::interrupt::typelevel::Interrupt;
16use crate::pac::InterruptNumber;
17use crate::{interrupt, pac, Peri};
18
19pub(crate) struct ChannelInfo {
20    pub(crate) dma: DmaInfo,
21    pub(crate) num: usize,
22    /// PFIC interrupt this channel's completion is delivered on. `None` for a
23    /// channel whose controller has no per-channel interrupt in the metadata.
24    pub(crate) irq: Option<pac::Interrupt>,
25}
26
27#[derive(Clone, Copy)]
28pub(crate) enum DmaInfo {
29    Dma(pac::dma::Dma),
30    #[cfg(dma_v4x7)]
31    Dma2(pac::dma::Dma2),
32}
33
34/// DMA transfer options.
35#[derive(Debug, Copy, Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "defmt", derive(defmt::Format))]
37#[non_exhaustive]
38pub struct TransferOptions {
39    /// Request priority level
40    pub priority: Priority,
41    /// Enable circular DMA
42    ///
43    /// Note:
44    /// If you enable circular mode manually, you may want to build and `.await` the `Transfer` in a separate task.
45    /// Since DMA in circular mode need manually stop, `.await` in current task would block the task forever.
46    pub circular: bool,
47    /// Enable half transfer interrupt
48    pub half_transfer_ir: bool,
49    /// Enable transfer complete interrupt
50    pub complete_transfer_ir: bool,
51    /// Increment the peripheral address after each transfer.
52    ///
53    /// Off by default: a peripheral's data register sits at a fixed address.
54    /// Turn it on together with `memory_to_memory` for a memory-to-memory copy,
55    /// where both ends are real addresses.
56    pub peripheral_increment: bool,
57    /// Memory-to-memory mode.
58    ///
59    /// The controller then reads from the peripheral address and writes to the
60    /// memory address on its own, without waiting for a peripheral request.
61    /// Off by default, which is what every peripheral driver needs.
62    pub memory_to_memory: bool,
63}
64
65impl Default for TransferOptions {
66    fn default() -> Self {
67        Self {
68            priority: Priority::VeryHigh,
69            circular: false,
70            half_transfer_ir: false,
71            complete_transfer_ir: true,
72            peripheral_increment: false,
73            memory_to_memory: false,
74        }
75    }
76}
77
78/// DMA request priority
79#[derive(Debug, Copy, Clone, PartialEq, Eq)]
80#[cfg_attr(feature = "defmt", derive(defmt::Format))]
81pub enum Priority {
82    /// Low Priority
83    Low,
84    /// Medium Priority
85    Medium,
86    /// High Priority
87    High,
88    /// Very High Priority
89    VeryHigh,
90}
91
92/// Register encoding of a [`Priority`].
93///
94/// V1-style PACs expose this as `pac::dma::vals::Pl`; the H4 block has the
95/// same two bits but no value enum, so both sides go through this.
96pub(super) fn priority_bits(priority: Priority) -> u8 {
97    match priority {
98        Priority::Low => 0,
99        Priority::Medium => 1,
100        Priority::High => 2,
101        Priority::VeryHigh => 3,
102    }
103}
104
105/// Register encoding of a [`WordSize`]: 0 = byte, 1 = half-word, 2 = word.
106pub(super) fn size_bits(size: WordSize) -> u8 {
107    match size {
108        WordSize::OneByte => 0,
109        WordSize::TwoBytes => 1,
110        WordSize::FourBytes => 2,
111    }
112}
113
114/// `DIR` bit: set when the peripheral is written, clear when it is read.
115#[cfg(not(dma_v4x7))]
116fn dir_bit(dir: Dir) -> bool {
117    matches!(dir, Dir::MemoryToPeripheral)
118}
119
120/// DMAMUX slot for a channel. DMA1 CH1..CH8 occupy slots 0..8 and DMA2
121/// CH1..CH8 occupy slots 8..16, so the slot is the controller base address
122/// offset from DMA1 divided by the 0x400 stride, times 8, plus the channel.
123#[cfg(ch32h4)]
124fn mux_slot(info: &ChannelInfo) -> usize {
125    let DmaInfo::Dma(r) = info.dma;
126    (r.as_ptr() as usize - pac::DMA1.as_ptr() as usize) / 0x400 * 8 + info.num
127}
128
129/// Program one channel's address, count and configuration registers.
130///
131/// The two PACs describe the same layout, but the V1 block names the
132/// registers `CR`/`NDTR`/`PAR`/`MAR` and types the fields as enums, while H4
133/// names them `CFGR`/`CNTR`/`PADDR`/`MADDR` and types them as raw values.
134#[cfg(not(any(ch32h4, dma_v4x7)))]
135fn write_channel(
136    ch: pac::dma::Ch,
137    peri_addr: *const u32,
138    mem_addr: *mut u32,
139    mem_len: usize,
140    incr_mem: bool,
141    data_size: WordSize,
142    dir: Dir,
143    options: &TransferOptions,
144) {
145    use pac::dma::vals::{Dir as DirVal, Pl, Size};
146
147    ch.par().write_value(peri_addr as u32); // PADDR
148    ch.mar().write_value(mem_addr as u32); // MADDR
149    ch.ndtr().write(|w| w.set_ndt(mem_len as u16)); // CNTR
150    ch.cr().write(|w| {
151        w.set_psize(match size_bits(data_size) {
152            0 => Size::BITS8,
153            1 => Size::BITS16,
154            _ => Size::BITS32,
155        });
156        w.set_msize(match size_bits(data_size) {
157            0 => Size::BITS8,
158            1 => Size::BITS16,
159            _ => Size::BITS32,
160        });
161        w.set_pinc(options.peripheral_increment);
162        w.set_mem2mem(options.memory_to_memory);
163        w.set_minc(incr_mem);
164        w.set_dir(if dir_bit(dir) {
165            DirVal::FROMMEMORY
166        } else {
167            DirVal::FROMPERIPHERAL
168        });
169        w.set_teie(true); // error
170        w.set_tcie(options.complete_transfer_ir); // tx complete
171        w.set_htie(options.half_transfer_ir); // half
172        w.set_circ(options.circular); // circular
173        w.set_pl(match priority_bits(options.priority) {
174            0 => Pl::LOW,
175            1 => Pl::MEDIUM,
176            2 => Pl::HIGH,
177            _ => Pl::VERYHIGH,
178        });
179        w.set_en(false); // don't start yet
180    });
181}
182
183#[cfg(ch32h4)]
184fn write_channel(
185    ch: pac::dma::Ch,
186    peri_addr: *const u32,
187    mem_addr: *mut u32,
188    mem_len: usize,
189    incr_mem: bool,
190    data_size: WordSize,
191    dir: Dir,
192    options: &TransferOptions,
193) {
194    ch.paddr().write_value(peri_addr as u32);
195    ch.maddr().write_value(mem_addr as u32);
196    ch.cntr().write(|w| w.set_ndt(mem_len as u16));
197    ch.cfgr().write(|w| {
198        w.set_psize(size_bits(data_size));
199        w.set_msize(size_bits(data_size));
200        w.set_pinc(options.peripheral_increment);
201        w.set_mem2mem(options.memory_to_memory);
202        w.set_minc(incr_mem);
203        w.set_dir(dir_bit(dir));
204        w.set_teie(true);
205        w.set_tcie(options.complete_transfer_ir);
206        w.set_htie(options.half_transfer_ir);
207        w.set_circ(options.circular);
208        w.set_pl(priority_bits(options.priority));
209        w.set_en(false);
210    });
211}
212
213pub(crate) struct ChannelState {
214    pub(super) waker: AtomicWaker,
215    pub(super) complete_count: AtomicUsize,
216    #[cfg(dma_v4x7)]
217    pub(super) stop_at_complete: AtomicBool,
218    #[cfg(dma_v4x7)]
219    pub(super) report_error: AtomicBool,
220    #[cfg(dma_v4x7)]
221    pub(super) transfer_error: AtomicBool,
222}
223
224impl ChannelState {
225    pub(crate) const NEW: Self = Self {
226        waker: AtomicWaker::new(),
227        complete_count: AtomicUsize::new(0),
228        #[cfg(dma_v4x7)]
229        stop_at_complete: AtomicBool::new(false),
230        #[cfg(dma_v4x7)]
231        report_error: AtomicBool::new(false),
232        #[cfg(dma_v4x7)]
233        transfer_error: AtomicBool::new(false),
234    };
235}
236
237/// safety: must be called only once
238///
239/// `enable_irqs` is false on a core that does not own the DMA interrupts. On
240/// CH32H4 an interrupt above 31 is shared and delivered to exactly one core:
241/// enabling it assigns it to the core that did the enable (RM §4.7.5.45,
242/// `PFIC_IALLOCR`). Enabling all of them here would take them from the boot
243/// core. The channel IRQ is unmasked later, when this core starts a transfer
244/// on a channel it owns.
245pub(crate) unsafe fn init(cs: critical_section::CriticalSection, dma_priority: interrupt::Priority, enable_irqs: bool) {
246    #[cfg(dma_v4x7)]
247    {
248        crate::_generated::init_dma();
249        for (id, info) in crate::_generated::DMA_CHANNELS.iter().enumerate() {
250            AnyChannel { id: id as u8 }.request_stop();
251            if let Some(irq) = info.irq {
252                qingke::pfic::unpend_interrupt(irq.number() as u8);
253            }
254        }
255    }
256    foreach_interrupt! {
257        ($peri:ident, dma, $block:ident, $signal_name:ident, $irq:ident) => {
258            crate::interrupt::typelevel::$irq::set_priority_with_cs(cs, dma_priority);
259            if enable_irqs {
260                crate::interrupt::typelevel::$irq::enable();
261            }
262        };
263    }
264    #[cfg(not(dma_v4x7))]
265    crate::_generated::init_dma();
266}
267
268#[cfg(not(dma_v4x7))]
269impl AnyChannel {
270    /// Safety: Must be called with a matching set of parameters for a valid dma channel
271    pub(crate) unsafe fn on_irq(&self) {
272        let info = self.info();
273        let state = &STATE[self.id as usize];
274        match self.info().dma {
275            DmaInfo::Dma(r) => {
276                // V1 calls the flag registers ISR/IFCR and the channel
277                // configuration CR; H4 calls them INTFR/INTFCR and CFGR. The
278                // bit positions are identical.
279                #[cfg(not(ch32h4))]
280                let (teif, htif, htie, tcif, tcie) = {
281                    let isr = r.isr().read();
282                    let cr = r.ch(info.num).cr().read();
283                    (
284                        isr.teif(info.num),
285                        isr.htif(info.num),
286                        cr.htie(),
287                        isr.tcif(info.num),
288                        cr.tcie(),
289                    )
290                };
291                #[cfg(ch32h4)]
292                let (teif, htif, htie, tcif, tcie) = {
293                    let isr = r.intfr().read();
294                    let cr = r.ch(info.num).cfgr().read();
295                    (
296                        isr.teif(info.num),
297                        isr.htif(info.num),
298                        cr.htie(),
299                        isr.tcif(info.num),
300                        cr.tcie(),
301                    )
302                };
303
304                if teif {
305                    panic!("DMA: error on DMA@{:08x} channel {}", r.as_ptr() as u32, info.num);
306                }
307
308                if htif && htie {
309                    // Acknowledge half transfer complete interrupt
310                    #[cfg(not(ch32h4))]
311                    r.ifcr().write(|w| w.set_htif(info.num, true));
312                    #[cfg(ch32h4)]
313                    r.intfcr().write(|w| w.set_chtif(info.num, true));
314                } else if tcif && tcie {
315                    // Acknowledge transfer complete interrupt
316                    #[cfg(not(ch32h4))]
317                    r.ifcr().write(|w| w.set_tcif(info.num, true));
318                    #[cfg(ch32h4)]
319                    r.intfcr().write(|w| w.set_ctcif(info.num, true));
320                    critical_section::with(|_| {
321                        // #safty this is okay because critical section ensures
322                        // no interruption
323                        let cnt = state.complete_count.load(Ordering::Acquire);
324                        state.complete_count.store(cnt + 1, Ordering::Release);
325                    });
326                } else {
327                    return;
328                }
329
330                state.waker.wake();
331            }
332        }
333    }
334
335    unsafe fn configure(
336        &self,
337        request: Request,
338        dir: Dir,
339        peri_addr: *const u32,
340        mem_addr: *mut u32,
341        mem_len: usize,
342        incr_mem: bool,
343        data_size: WordSize,
344        options: TransferOptions,
345    ) {
346        let info = self.info();
347
348        // Unmask this channel's interrupt on the core that starts the transfer.
349        // `init` only does this for the core that owns the DMA interrupts; on
350        // CH32H4 enabling an interrupt above 31 assigns it to the enabling core
351        // (RM §4.7.5.45), so the other core must enable exactly the channels it
352        // uses and no others.
353        if let Some(irq) = info.irq {
354            unsafe { qingke::pfic::enable_interrupt(irq.number() as u8) };
355        }
356
357        assert!(mem_len > 0 && mem_len <= 0xFFFF);
358
359        // On CH32H4 the request number selects the peripheral inside the
360        // DMAMUX. The mux has one 7-bit slot per channel: DMA1 CH1..CH8 are
361        // slots 0..8, DMA2 CH1..CH8 are slots 8..16, packed four per CFGR.
362        // Fixed-wiring chips pass `()` and never reach this.
363        #[cfg(ch32h4)]
364        {
365            // RM table 10-2 numbers the request inputs from 1, the `CHANNELn_MUX`
366            // field from 0 (RM §10.2.3). Writing the table number directly picks
367            // the next peripheral: SDIO (111) became SAI_A_TX (112), whose request
368            // never fires, so an SDIO DMA read stalled with the data waiting in
369            // the FIFO. WCH's `DMA_MuxChannelConfig` subtracts one as well.
370            let slot = mux_slot(info);
371            debug_assert!(request != 0, "DMAMUX request numbers are 1-based");
372            pac::DMAMUX.cfgr(slot / 4).modify(|w| {
373                w.set_channel_mux(slot % 4, request - 1);
374            });
375        }
376        #[cfg(not(ch32h4))]
377        let _ = request;
378
379        match self.info().dma {
380            DmaInfo::Dma(r) => {
381                let state: &ChannelState = &STATE[self.id as usize];
382                let ch = r.ch(info.num);
383
384                state.complete_count.store(0, Ordering::Release);
385                self.clear_irqs();
386
387                write_channel(ch, peri_addr, mem_addr, mem_len, incr_mem, data_size, dir, &options);
388            }
389        }
390    }
391
392    fn start(&self) {
393        let info = self.info();
394        match self.info().dma {
395            DmaInfo::Dma(r) => {
396                let ch = r.ch(info.num);
397                #[cfg(not(ch32h4))]
398                ch.cr().modify(|w| w.set_en(true));
399                #[cfg(ch32h4)]
400                ch.cfgr().modify(|w| w.set_en(true));
401            }
402        }
403    }
404
405    fn clear_irqs(&self) {
406        let info = self.info();
407        match self.info().dma {
408            DmaInfo::Dma(r) => {
409                #[cfg(not(ch32h4))]
410                r.ifcr().write(|w| {
411                    w.set_htif(info.num, true);
412                    w.set_tcif(info.num, true);
413                    w.set_teif(info.num, true);
414                });
415                #[cfg(ch32h4)]
416                r.intfcr().write(|w| {
417                    w.set_chtif(info.num, true);
418                    w.set_ctcif(info.num, true);
419                    w.set_cteif(info.num, true);
420                });
421            }
422        }
423    }
424
425    fn request_stop(&self) {
426        let info = self.info();
427        match self.info().dma {
428            DmaInfo::Dma(r) => {
429                // Disable the channel. Keep the IEs enabled so the irqs still fire.
430                #[cfg(not(ch32h4))]
431                r.ch(info.num).cr().write(|w| {
432                    w.set_teie(true);
433                    w.set_tcie(true);
434                });
435                #[cfg(ch32h4)]
436                r.ch(info.num).cfgr().write(|w| {
437                    w.set_teie(true);
438                    w.set_tcie(true);
439                });
440            }
441        }
442    }
443
444    /// Clear only EN: the configuration stays, so `start` resumes the channel.
445    fn request_pause(&self) {
446        let info = self.info();
447        match self.info().dma {
448            #[cfg(not(ch32h4))]
449            DmaInfo::Dma(r) => r.ch(info.num).cr().modify(|w| w.set_en(false)),
450            #[cfg(ch32h4)]
451            DmaInfo::Dma(r) => r.ch(info.num).cfgr().modify(|w| w.set_en(false)),
452        }
453    }
454
455    /// Reload the transfer count (the channel must be disabled).
456    fn set_count(&self, count: u16) {
457        let info = self.info();
458        match self.info().dma {
459            #[cfg(not(ch32h4))]
460            DmaInfo::Dma(r) => r.ch(info.num).ndtr().write(|w| w.set_ndt(count)),
461            #[cfg(ch32h4)]
462            DmaInfo::Dma(r) => r.ch(info.num).cntr().write(|w| w.set_ndt(count)),
463        }
464    }
465
466    fn is_running(&self) -> bool {
467        let info = self.info();
468        match self.info().dma {
469            DmaInfo::Dma(r) => {
470                let state: &ChannelState = &STATE[self.id as usize];
471                let ch = r.ch(info.num);
472                #[cfg(not(ch32h4))]
473                let (en, circular) = {
474                    let cr = ch.cr().read();
475                    (cr.en(), cr.circ())
476                };
477                #[cfg(ch32h4)]
478                let (en, circular) = {
479                    let cr = ch.cfgr().read();
480                    (cr.en(), cr.circ())
481                };
482                let tcif = state.complete_count.load(Ordering::Acquire) != 0;
483                en && (circular || !tcif)
484            }
485        }
486    }
487
488    fn get_remaining_transfers(&self) -> u16 {
489        let info = self.info();
490        match self.info().dma {
491            #[cfg(not(ch32h4))]
492            DmaInfo::Dma(r) => r.ch(info.num).ndtr().read().ndt(),
493            #[cfg(ch32h4)]
494            DmaInfo::Dma(r) => r.ch(info.num).cntr().read().ndt(),
495        }
496    }
497
498    fn disable_circular_mode(&self) {
499        let info = self.info();
500        match self.info().dma {
501            DmaInfo::Dma(regs) => {
502                #[cfg(not(ch32h4))]
503                regs.ch(info.num).cr().modify(|w| w.set_circ(false));
504                #[cfg(ch32h4)]
505                regs.ch(info.num).cfgr().modify(|w| w.set_circ(false));
506            }
507        }
508    }
509
510    fn poll_stop(&self) -> Poll<()> {
511        compiler_fence(Ordering::SeqCst);
512
513        if !self.is_running() {
514            Poll::Ready(())
515        } else {
516            Poll::Pending
517        }
518    }
519}
520
521/// DMA transfer.
522#[must_use = "futures do nothing unless you `.await` or poll them"]
523pub struct Transfer<'a> {
524    channel: Peri<'a, AnyChannel>,
525}
526
527impl<'a> Transfer<'a> {
528    /// Start a V4x7 read whose DMA errors are reported through `has_error`.
529    #[cfg(dma_v4x7)]
530    pub unsafe fn new_read_checked<W: Word>(
531        channel: Peri<'a, impl Channel>,
532        request: Request,
533        peri_addr: *mut W,
534        buf: &'a mut [W],
535        options: TransferOptions,
536    ) -> Self {
537        critical_section::with(|_| {
538            let transfer = Self::new_read(channel, request, peri_addr, buf, options);
539            STATE[transfer.channel.id as usize]
540                .report_error
541                .store(true, Ordering::Release);
542            transfer
543        })
544    }
545
546    /// Start a V4x7 write whose DMA errors are reported through `has_error`.
547    #[cfg(dma_v4x7)]
548    pub unsafe fn new_write_checked<W: Word>(
549        channel: Peri<'a, impl Channel>,
550        request: Request,
551        buf: &'a [W],
552        peri_addr: *mut W,
553        options: TransferOptions,
554    ) -> Self {
555        critical_section::with(|_| {
556            let transfer = Self::new_write(channel, request, buf, peri_addr, options);
557            STATE[transfer.channel.id as usize]
558                .report_error
559                .store(true, Ordering::Release);
560            transfer
561        })
562    }
563
564    /// Inspect a checked transfer after polling or waiting for completion.
565    /// A DMA error stops the channel and wakes its waiter; the future still returns `()`.
566    #[cfg(dma_v4x7)]
567    pub fn has_error(&self) -> bool {
568        self.channel.has_error()
569    }
570
571    /// Create a new read DMA transfer (peripheral to memory).
572    pub unsafe fn new_read<W: Word>(
573        channel: Peri<'a, impl Channel>,
574        request: Request,
575        peri_addr: *mut W,
576        buf: &'a mut [W],
577        options: TransferOptions,
578    ) -> Self {
579        Self::new_read_raw(channel, request, peri_addr, buf, options)
580    }
581
582    /// Create a new read DMA transfer (peripheral to memory), using raw pointers.
583    pub unsafe fn new_read_raw<W: Word>(
584        channel: Peri<'a, impl Channel>,
585        request: Request,
586        peri_addr: *mut W,
587        buf: *mut [W],
588        options: TransferOptions,
589    ) -> Self {
590        let (ptr, len) = super::slice_ptr_parts_mut(buf);
591        assert!(len > 0 && len <= 0xFFFF);
592
593        Self::new_inner(
594            channel.into(),
595            request,
596            Dir::PeripheralToMemory,
597            peri_addr as *const u32,
598            ptr as *mut u32,
599            len,
600            true,
601            W::size(),
602            options,
603        )
604    }
605
606    /// Create a new write DMA transfer (memory to peripheral).
607    pub unsafe fn new_write<W: Word>(
608        channel: Peri<'a, impl Channel>,
609        request: Request,
610        buf: &'a [W],
611        peri_addr: *mut W,
612        options: TransferOptions,
613    ) -> Self {
614        Self::new_write_raw(channel, request, buf, peri_addr, options)
615    }
616
617    /// Create a new write DMA transfer (memory to peripheral), using raw pointers.
618    pub unsafe fn new_write_raw<W: Word>(
619        channel: Peri<'a, impl Channel>,
620        request: Request,
621        buf: *const [W],
622        peri_addr: *mut W,
623        options: TransferOptions,
624    ) -> Self {
625        let (ptr, len) = super::slice_ptr_parts(buf);
626        assert!(len > 0 && len <= 0xFFFF);
627
628        Self::new_inner(
629            channel.into(),
630            request,
631            Dir::MemoryToPeripheral,
632            peri_addr as *const u32,
633            ptr as *mut u32,
634            len,
635            true,
636            W::size(),
637            options,
638        )
639    }
640
641    /// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly.
642    pub unsafe fn new_write_repeated<W: Word>(
643        channel: Peri<'a, impl Channel>,
644        request: Request,
645        repeated: &'a W,
646        count: usize,
647        peri_addr: *mut W,
648        options: TransferOptions,
649    ) -> Self {
650        Self::new_inner(
651            channel.into(),
652            request,
653            Dir::MemoryToPeripheral,
654            peri_addr as *const u32,
655            repeated as *const W as *mut u32,
656            count,
657            false,
658            W::size(),
659            options,
660        )
661    }
662
663    unsafe fn new_inner(
664        channel: Peri<'a, AnyChannel>,
665        _request: Request,
666        dir: Dir,
667        peri_addr: *const u32,
668        mem_addr: *mut u32,
669        mem_len: usize,
670        incr_mem: bool,
671        data_size: WordSize,
672        options: TransferOptions,
673    ) -> Self {
674        channel.configure(
675            _request, dir, peri_addr, mem_addr, mem_len, incr_mem, data_size, options,
676        );
677        channel.start();
678
679        Self { channel }
680    }
681
682    /// Request the transfer to stop.
683    ///
684    /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
685    pub fn request_stop(&mut self) {
686        self.channel.request_stop()
687    }
688
689    /// Return whether this transfer is still running.
690    ///
691    /// If this returns `false`, it can be because either the transfer finished, or
692    /// it was requested to stop early with [`request_stop`](Self::request_stop).
693    pub fn is_running(&mut self) -> bool {
694        self.channel.is_running()
695    }
696
697    /// Gets the total remaining transfers for the channel
698    /// Note: this will be zero for transfers that completed without cancellation.
699    pub fn get_remaining_transfers(&self) -> u16 {
700        self.channel.get_remaining_transfers()
701    }
702
703    /// Blocking wait until the transfer finishes.
704    pub fn blocking_wait(mut self) {
705        while self.is_running() {}
706
707        // "Subsequent reads and writes cannot be moved ahead of preceding reads."
708        fence(Ordering::SeqCst);
709
710        core::mem::forget(self);
711    }
712}
713
714impl<'a> Drop for Transfer<'a> {
715    fn drop(&mut self) {
716        self.request_stop();
717        while self.is_running() {}
718
719        // "Subsequent reads and writes cannot be moved ahead of preceding reads."
720        fence(Ordering::SeqCst);
721    }
722}
723
724impl<'a> Unpin for Transfer<'a> {}
725impl<'a> Future for Transfer<'a> {
726    type Output = ();
727    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
728        let state: &ChannelState = &STATE[self.channel.id as usize];
729
730        state.waker.register(cx.waker());
731
732        if self.is_running() {
733            // On the CH32V003 and CH32V203 the DMA makes no progress while the
734            // core sleeps in WFI/WFE, so an executor that sleeps between polls
735            // would only move the transfer on at its next unrelated wake-up.
736            // Wake the task again so that the executor keeps polling until the
737            // transfer is done.
738            #[cfg(any(ch32v003, ch32v203))]
739            cx.waker().wake_by_ref();
740            Poll::Pending
741        } else {
742            Poll::Ready(())
743        }
744    }
745}
746
747// ==============================
748
749struct DmaCtrlImpl<'a>(Peri<'a, AnyChannel>);
750
751impl<'a> DmaCtrl for DmaCtrlImpl<'a> {
752    fn get_remaining_transfers(&self) -> usize {
753        self.0.get_remaining_transfers() as _
754    }
755
756    fn get_complete_count(&self) -> usize {
757        STATE[self.0.id as usize].complete_count.load(Ordering::Acquire)
758    }
759
760    fn reset_complete_count(&mut self) -> usize {
761        let state = &STATE[self.0.id as usize];
762        critical_section::with(|_| {
763            let old_val = state.complete_count.load(Ordering::Acquire);
764            state.complete_count.store(0, Ordering::Release);
765            old_val
766        })
767    }
768
769    fn set_waker(&mut self, waker: &Waker) {
770        STATE[self.0.id as usize].waker.register(waker);
771    }
772}
773
774/// Ringbuffer for receiving data using DMA circular mode.
775pub struct ReadableRingBuffer<'a, W: Word> {
776    channel: Peri<'a, AnyChannel>,
777    ringbuf: ReadableDmaRingBuffer<'a, W>,
778}
779
780impl<'a, W: Word> ReadableRingBuffer<'a, W> {
781    /// Create a new ring buffer.
782    pub unsafe fn new(
783        channel: Peri<'a, impl Channel>,
784        _request: Request,
785        peri_addr: *mut W,
786        buffer: &'a mut [W],
787        mut options: TransferOptions,
788    ) -> Self {
789        let channel: Peri<'a, AnyChannel> = channel.into();
790
791        let buffer_ptr = buffer.as_mut_ptr();
792        let len = buffer.len();
793        let dir = Dir::PeripheralToMemory;
794        let data_size = W::size();
795
796        options.complete_transfer_ir = true;
797        options.circular = true;
798
799        channel.configure(
800            _request,
801            dir,
802            peri_addr as *mut u32,
803            buffer_ptr as *mut u32,
804            len,
805            true,
806            data_size,
807            options,
808        );
809
810        Self {
811            channel,
812            ringbuf: ReadableDmaRingBuffer::new(buffer),
813        }
814    }
815
816    /// Start the ring buffer operation.
817    ///
818    /// You must call this after creating it for it to work.
819    pub fn start(&mut self) {
820        self.channel.start()
821    }
822
823    /// Clear all data in the ring buffer.
824    pub fn clear(&mut self) {
825        self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
826    }
827
828    /// Stop the channel but keep its configuration: [`start`](Self::start) resumes it
829    /// ([`request_stop`](Self::request_stop) clears the configuration).
830    pub fn request_pause(&mut self) {
831        self.channel.request_pause()
832    }
833
834    /// Empty a paused ring buffer: the next [`start`](Self::start) fills it from the
835    /// beginning.
836    pub fn reset(&mut self) {
837        self.channel.set_count(self.ringbuf.cap() as u16);
838        self.clear();
839    }
840
841    /// Read elements from the ring buffer
842    /// Return a tuple of the length read and the length remaining in the buffer
843    /// If not all of the elements were read, then there will be some elements in the buffer remaining
844    /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read
845    /// OverrunError is returned if the portion to be read was overwritten by the DMA controller.
846    pub fn read(&mut self, buf: &mut [W]) -> Result<(usize, usize), OverrunError> {
847        self.ringbuf.read(&mut DmaCtrlImpl(self.channel.reborrow()), buf)
848    }
849
850    /// Read an exact number of elements from the ringbuffer.
851    ///
852    /// Returns the remaining number of elements available for immediate reading.
853    /// OverrunError is returned if the portion to be read was overwritten by the DMA controller.
854    ///
855    /// Async/Wake Behavior:
856    /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point,
857    /// and when it wraps around. This means that when called with a buffer of length 'M', when this
858    /// ring buffer was created with a buffer of size 'N':
859    /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source.
860    /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning.
861    pub async fn read_exact(&mut self, buffer: &mut [W]) -> Result<usize, OverrunError> {
862        self.ringbuf
863            .read_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer)
864            .await
865    }
866
867    /// The capacity of the ringbuffer
868    pub const fn capacity(&self) -> usize {
869        self.ringbuf.cap()
870    }
871
872    /// Set a waker to be woken when at least one byte is received.
873    pub fn set_waker(&mut self, waker: &Waker) {
874        DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
875    }
876
877    /// Request DMA to stop.
878    ///
879    /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
880    pub fn request_stop(&mut self) {
881        self.channel.request_stop()
882    }
883
884    /// Return whether DMA is still running.
885    ///
886    /// If this returns `false`, it can be because either the transfer finished, or
887    /// it was requested to stop early with [`request_stop`](Self::request_stop).
888    pub fn is_running(&mut self) -> bool {
889        self.channel.is_running()
890    }
891
892    /// Stop the DMA transfer and await until the buffer is full.
893    ///
894    /// This disables the DMA transfer's circular mode so that the transfer
895    /// stops when the buffer is full.
896    ///
897    /// This is designed to be used with streaming input data such as the
898    /// I2S/SAI or ADC.
899    ///
900    /// When using the UART, you probably want `request_stop()`.
901    pub async fn stop(&mut self) {
902        self.channel.disable_circular_mode();
903        //wait until cr.susp reads as true
904        poll_fn(|cx| {
905            self.set_waker(cx.waker());
906            self.channel.poll_stop()
907        })
908        .await
909    }
910}
911
912impl<'a, W: Word> Drop for ReadableRingBuffer<'a, W> {
913    fn drop(&mut self) {
914        self.request_stop();
915        while self.is_running() {}
916
917        // "Subsequent reads and writes cannot be moved ahead of preceding reads."
918        fence(Ordering::SeqCst);
919    }
920}
921
922/// Ringbuffer for writing data using DMA circular mode.
923pub struct WritableRingBuffer<'a, W: Word> {
924    channel: Peri<'a, AnyChannel>,
925    ringbuf: WritableDmaRingBuffer<'a, W>,
926}
927
928impl<'a, W: Word> WritableRingBuffer<'a, W> {
929    /// Create a new ring buffer.
930    pub unsafe fn new(
931        channel: Peri<'a, impl Channel>,
932        _request: Request,
933        peri_addr: *mut W,
934        buffer: &'a mut [W],
935        mut options: TransferOptions,
936    ) -> Self {
937        let channel: Peri<'a, AnyChannel> = channel.into();
938
939        let len = buffer.len();
940        let dir = Dir::MemoryToPeripheral;
941        let data_size = W::size();
942        let buffer_ptr = buffer.as_mut_ptr();
943
944        options.complete_transfer_ir = true;
945        options.circular = true;
946
947        channel.configure(
948            _request,
949            dir,
950            peri_addr as *mut u32,
951            buffer_ptr as *mut u32,
952            len,
953            true,
954            data_size,
955            options,
956        );
957
958        Self {
959            channel,
960            ringbuf: WritableDmaRingBuffer::new(buffer),
961        }
962    }
963
964    /// Start the ring buffer operation.
965    ///
966    /// You must call this after creating it for it to work.
967    pub fn start(&mut self) {
968        self.channel.start()
969    }
970
971    /// Clear all data in the ring buffer.
972    pub fn clear(&mut self) {
973        self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
974    }
975
976    /// Write elements directly to the raw buffer.
977    /// This can be used to fill the buffer before starting the DMA transfer.
978    #[allow(dead_code)]
979    pub fn write_immediate(&mut self, buf: &[W]) -> Result<(usize, usize), OverrunError> {
980        self.ringbuf.write_immediate(buf)
981    }
982
983    /// Write elements from the ring buffer
984    /// Return a tuple of the length written and the length remaining in the buffer
985    pub fn write(&mut self, buf: &[W]) -> Result<(usize, usize), OverrunError> {
986        self.ringbuf.write(&mut DmaCtrlImpl(self.channel.reborrow()), buf)
987    }
988
989    /// Write an exact number of elements to the ringbuffer.
990    pub async fn write_exact(&mut self, buffer: &[W]) -> Result<usize, OverrunError> {
991        self.ringbuf
992            .write_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer)
993            .await
994    }
995
996    /// The capacity of the ringbuffer
997    pub const fn capacity(&self) -> usize {
998        self.ringbuf.cap()
999    }
1000
1001    /// Set a waker to be woken when at least one byte is received.
1002    pub fn set_waker(&mut self, waker: &Waker) {
1003        DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
1004    }
1005
1006    /// Request DMA to stop.
1007    ///
1008    /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
1009    pub fn request_stop(&mut self) {
1010        self.channel.request_stop()
1011    }
1012
1013    /// Return whether DMA is still running.
1014    ///
1015    /// If this returns `false`, it can be because either the transfer finished, or
1016    /// it was requested to stop early with [`request_stop`](Self::request_stop).
1017    pub fn is_running(&mut self) -> bool {
1018        self.channel.is_running()
1019    }
1020
1021    /// Stop the DMA transfer and await until the buffer is empty.
1022    ///
1023    /// This disables the DMA transfer's circular mode so that the transfer
1024    /// stops when all available data has been written.
1025    ///
1026    /// This is designed to be used with streaming output data such as the
1027    /// I2S/SAI or DAC.
1028    pub async fn stop(&mut self) {
1029        self.channel.disable_circular_mode();
1030        //wait until cr.susp reads as true
1031        poll_fn(|cx| {
1032            self.set_waker(cx.waker());
1033            self.channel.poll_stop()
1034        })
1035        .await
1036    }
1037}
1038
1039impl<'a, W: Word> Drop for WritableRingBuffer<'a, W> {
1040    fn drop(&mut self) {
1041        self.request_stop();
1042        while self.is_running() {}
1043
1044        // "Subsequent reads and writes cannot be moved ahead of preceding reads."
1045        fence(Ordering::SeqCst);
1046    }
1047}