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