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 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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
34#[cfg_attr(feature = "defmt", derive(defmt::Format))]
35#[non_exhaustive]
36pub struct TransferOptions {
37 pub priority: Priority,
39 pub circular: bool,
45 pub half_transfer_ir: bool,
47 pub complete_transfer_ir: bool,
49 pub peripheral_increment: bool,
55 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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
78#[cfg_attr(feature = "defmt", derive(defmt::Format))]
79pub enum Priority {
80 Low,
82 Medium,
84 High,
86 VeryHigh,
88}
89
90pub(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
103pub(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#[cfg(not(dma_v4x7))]
114fn dir_bit(dir: Dir) -> bool {
115 matches!(dir, Dir::MemoryToPeripheral)
116}
117
118#[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#[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); ch.mar().write_value(mem_addr as u32); ch.ndtr().write(|w| w.set_ndt(mem_len as u16)); 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); w.set_tcie(options.complete_transfer_ir); w.set_htie(options.half_transfer_ir); w.set_circ(options.circular); 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); });
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 #[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
244pub(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 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 #[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 #[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 #[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 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 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 #[cfg(ch32h4)]
385 {
386 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 #[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 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 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#[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 #[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 #[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 #[cfg(dma_v4x7)]
590 pub fn has_error(&self) -> bool {
591 self.channel.has_error()
592 }
593
594 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 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 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 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 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 pub fn request_stop(&mut self) {
709 self.channel.request_stop()
710 }
711
712 pub fn is_running(&mut self) -> bool {
717 self.channel.is_running()
718 }
719
720 pub fn get_remaining_transfers(&self) -> u16 {
723 self.channel.get_remaining_transfers()
724 }
725
726 pub fn blocking_wait(mut self) {
728 while self.is_running() {}
729
730 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 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 #[cfg(any(ch32v003, ch32v203))]
762 cx.waker().wake_by_ref();
763 Poll::Pending
764 } else {
765 Poll::Ready(())
766 }
767 }
768}
769
770struct 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
797pub 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 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 pub fn start(&mut self) {
843 self.channel.start()
844 }
845
846 pub fn clear(&mut self) {
848 self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
849 }
850
851 pub fn request_pause(&mut self) {
854 self.channel.request_pause()
855 }
856
857 pub fn reset(&mut self) {
860 self.channel.set_count(self.ringbuf.cap() as u16);
861 self.clear();
862 }
863
864 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 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 pub const fn capacity(&self) -> usize {
892 self.ringbuf.cap()
893 }
894
895 pub fn set_waker(&mut self, waker: &Waker) {
897 DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
898 }
899
900 pub fn request_stop(&mut self) {
904 self.channel.request_stop()
905 }
906
907 pub fn is_running(&mut self) -> bool {
912 self.channel.is_running()
913 }
914
915 pub async fn stop(&mut self) {
925 self.channel.disable_circular_mode();
926 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 fence(Ordering::SeqCst);
942 }
943}
944
945pub 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 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 pub fn start(&mut self) {
991 self.channel.start()
992 }
993
994 pub fn clear(&mut self) {
996 self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
997 }
998
999 #[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 pub fn write(&mut self, buf: &[W]) -> Result<(usize, usize), OverrunError> {
1009 self.ringbuf.write(&mut DmaCtrlImpl(self.channel.reborrow()), buf)
1010 }
1011
1012 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 pub const fn capacity(&self) -> usize {
1021 self.ringbuf.cap()
1022 }
1023
1024 pub fn set_waker(&mut self, waker: &Waker) {
1026 DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
1027 }
1028
1029 pub fn request_stop(&mut self) {
1033 self.channel.request_stop()
1034 }
1035
1036 pub fn is_running(&mut self) -> bool {
1041 self.channel.is_running()
1042 }
1043
1044 pub async fn stop(&mut self) {
1052 self.channel.disable_circular_mode();
1053 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 fence(Ordering::SeqCst);
1069 }
1070}
1071
1072#[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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1094#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1095pub struct RingPosition {
1096 pub laps: u32,
1101 pub index: usize,
1103}
1104
1105#[cfg(not(dma_v4x7))]
1106#[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 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 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 ndt = remaining(r, info.num);
1137 }
1138 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)))]
1151pub(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 pub fn new(channel: Peri<'a, impl Channel>) -> Self {
1166 Self {
1167 channel: channel.into(),
1168 len: 0,
1169 }
1170 }
1171
1172 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 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 pub fn start(&mut self) {
1252 compiler_fence(Ordering::SeqCst);
1253 self.channel.start();
1254 }
1255
1256 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 pub fn position(&self) -> RingPosition {
1270 self.reader().read()
1271 }
1272
1273 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 pub fn take_error(&self) -> bool {
1284 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 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}