esp-hal 1.2.0

Bare-metal HAL for Espressif devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
use core::{
    mem::ManuallyDrop,
    ops::{Deref, DerefMut},
};

use enumset::EnumSet;

#[cfg(dma_mem2mem_requires_peripheral)]
use crate::dma::DmaEligiblePeripheral;
use crate::{
    Async,
    Blocking,
    DriverMode,
    dma::{
        BurstConfig,
        Channel,
        ChannelRx,
        ChannelTx,
        DmaChannel,
        DmaDescriptor,
        DmaError,
        DmaPeripheral,
        DmaRxBuf,
        DmaRxBuffer,
        DmaRxInterrupt,
        DmaTxBuf,
        DmaTxBuffer,
        DmaTxInterrupt,
        aligned::DmaAlignedMut,
    },
};

/// A DMA channel singleton that supports memory-to-memory transfers on this chip.
///
/// Only channels listed in device metadata (`mem2mem = true`) implement this trait.
/// Use [`Mem2Mem::new`] to construct a transfer engine from such a channel.
#[diagnostic::on_unimplemented(
    message = "this DMA channel does not support memory-to-memory transfers",
    note = "Use a channel with `mem2mem = true` in device metadata. See `Mem2Mem::new`."
)]
pub trait Mem2MemCapableChannel<'d>: DmaChannel {
    #[doc(hidden)]
    type Erased: DmaChannel + From<Self>;

    /// Peripheral selector programmed for memory-to-memory on this channel.
    #[cfg(not(dma_mem2mem_requires_peripheral))]
    fn mem2mem_id(&self) -> DmaPeripheral;

    #[doc(hidden)]
    #[allow(private_interfaces)]
    fn into_channel(self) -> ErasedChannel<'d, Blocking>;
}

// Type-erased version of Channel/ChannelRx/ChannelTx
for_each_mem2mem_channel! {
    (engines $( ($engine:literal, $variant:ident, $any_ch:ident) ),* ) => {
        struct ErasedChannel<'d, Dm: DriverMode> {
            rx: ErasedChannelRx<'d, Dm>,
            tx: ErasedChannelTx<'d, Dm>,
        }

        enum ErasedChannelRx<'d, Dm: DriverMode> {
            $(
                $variant(ChannelRx<Dm, <crate::dma::$any_ch<'d> as DmaChannel>::Rx>),
            )*
        }

        impl<Dm: DriverMode> ErasedChannelRx<'_, Dm> {
            delegate::delegate! {
                to match self {
                    $( Self::$variant(channel) => channel, )*
                } {
                    fn has_error(&self) -> bool;
                    fn pending_in_interrupts(&self) -> EnumSet<DmaRxInterrupt>;
                    #[cfg(dma_mem2mem_requires_peripheral)]
                    fn runtime_ensure_compatible(&self, peripheral: DmaPeripheral);
                }

                to match self {
                    $( Self::$variant(channel) => channel, )*
                } {
                    fn set_mem2mem_mode(&mut self, value: bool);
                    fn start_transfer(&mut self) -> Result<(), DmaError>;
                    fn stop_transfer(&mut self);
                    unsafe fn prepare_transfer<BUF: DmaRxBuffer>(
                        &mut self,
                        peri: DmaPeripheral,
                        buffer: &mut BUF,
                    ) -> Result<(), DmaError>;
                }
            }
        }

        impl<'d> ErasedChannelRx<'d, Blocking> {
            fn into_async(self) -> ErasedChannelRx<'d, Async> {
                match self {
                    $( Self::$variant(channel) => ErasedChannelRx::$variant(channel.into_async()), )*
                }
            }
        }

        impl<'d> ErasedChannelRx<'d, Async> {
            fn into_blocking(self) -> ErasedChannelRx<'d, Blocking> {
                match self {
                    $( Self::$variant(channel) => ErasedChannelRx::$variant(channel.into_blocking()), )*
                }
            }
        }

        enum ErasedChannelTx<'d, Dm: DriverMode> {
            $(
                $variant(ChannelTx<Dm, <crate::dma::$any_ch<'d> as DmaChannel>::Tx>),
            )*
        }

        impl<Dm: DriverMode> ErasedChannelTx<'_, Dm> {
            delegate::delegate! {
                to match self {
                    $( Self::$variant(channel) => channel, )*
                } {
                    fn has_error(&self) -> bool;
                    fn pending_out_interrupts(&self) -> EnumSet<DmaTxInterrupt>;
                }

                to match self {
                    $( Self::$variant(channel) => channel, )*
                } {
                    fn start_transfer(&mut self) -> Result<(), DmaError>;
                    fn stop_transfer(&mut self);
                    unsafe fn prepare_transfer<BUF: DmaTxBuffer>(
                        &mut self,
                        peri: DmaPeripheral,
                        buffer: &mut BUF,
                    ) -> Result<(), DmaError>;
                }
            }
        }

        impl<'d> ErasedChannelTx<'d, Blocking> {
            fn into_async(self) -> ErasedChannelTx<'d, Async> {
                match self {
                    $( Self::$variant(channel) => ErasedChannelTx::$variant(channel.into_async()), )*
                }
            }
        }

        impl<'d> ErasedChannelTx<'d, Async> {
            fn into_blocking(self) -> ErasedChannelTx<'d, Blocking> {
                match self {
                    $( Self::$variant(channel) => ErasedChannelTx::$variant(channel.into_blocking()), )*
                }
            }
        }
    };
}

for_each_mem2mem_channel! {
    ($engine:literal, $variant:ident, $any_ch:ident, $($hw:literal, $id:literal),+) => {
        impl<'d> Mem2MemCapableChannel<'d> for crate::dma::$any_ch<'d> {
            type Erased = Self;

            #[cfg(not(dma_mem2mem_requires_peripheral))]
            fn mem2mem_id(&self) -> DmaPeripheral {
                match self.channel_index() {
                    $( $hw => DmaPeripheral($id), )+
                    ch => panic!(
                        "Channel {} does not support memory-to-memory transfers",
                        ch
                    ),
                }
            }

            fn into_channel(self) -> ErasedChannel<'d, Blocking> {
                let channel = Channel::new(self);
                ErasedChannel {
                    rx: ErasedChannelRx::$variant(channel.rx),
                    tx: ErasedChannelTx::$variant(channel.tx),
                }
            }
        }
    };
    ($engine:literal, $variant:ident, $any_ch:ident, $ch:ident, $id:literal) => {
        impl<'d> Mem2MemCapableChannel<'d> for crate::peripherals::$ch<'d> {
            type Erased = crate::dma::$any_ch<'d>;

            #[cfg(not(dma_mem2mem_requires_peripheral))]
            fn mem2mem_id(&self) -> DmaPeripheral {
                DmaPeripheral($id)
            }

            fn into_channel(self) -> ErasedChannel<'d, Blocking> {
                let channel = Channel::new(crate::dma::$any_ch::from(self));
                ErasedChannel {
                    rx: ErasedChannelRx::$variant(channel.rx),
                    tx: ErasedChannelTx::$variant(channel.tx),
                }
            }
        }
    };
}

/// DMA Memory to Memory pseudo-Peripheral
///
/// This is a pseudo-peripheral that allows for memory to memory transfers.
/// It is not a real peripheral, but a way to use the DMA engine for memory
/// to memory transfers.
pub struct Mem2Mem<'d, Dm>
where
    Dm: DriverMode,
{
    /// RX Half
    pub rx: Mem2MemRx<'d, Dm>,
    /// TX Half
    pub tx: Mem2MemTx<'d, Dm>,
}

impl<'d> Mem2Mem<'d, Blocking> {
    /// Creates a new [`Mem2Mem`] instance.
    pub fn new<CH>(
        channel: CH,
        #[cfg(dma_mem2mem_requires_peripheral)] peripheral: impl DmaEligiblePeripheral<CH::Erased>,
    ) -> Self
    where
        CH: Mem2MemCapableChannel<'d>,
    {
        let dma_peri = cfg_select! {
            dma_mem2mem_requires_peripheral => peripheral.dma_peripheral(),
            _ => channel.mem2mem_id(),
        };
        Self::new_inner(channel, dma_peri)
    }

    /// Creates a new [`Mem2Mem`] instance.
    ///
    /// # Safety
    ///
    /// The caller must ensure that DMA is not used for the same peripheral,
    /// that this is the only user of the peripheral, and that the peripheral is
    /// compatible with the channel.
    #[cfg(dma_mem2mem_requires_peripheral)]
    pub unsafe fn new_unsafe<CH>(channel: CH, peripheral: DmaPeripheral) -> Self
    where
        CH: Mem2MemCapableChannel<'d>,
    {
        Self::new_inner(channel, peripheral)
    }

    /// Converts Mem2Mem to an async Mem2Mem.
    pub fn into_async(self) -> Mem2Mem<'d, Async> {
        Mem2Mem {
            rx: self.rx.into_async(),
            tx: self.tx.into_async(),
        }
    }
}

impl<'d> Mem2Mem<'d, Blocking> {
    fn new_inner(channel: impl Mem2MemCapableChannel<'d>, peripheral: DmaPeripheral) -> Self {
        let mut channel = channel.into_channel();

        #[cfg(dma_mem2mem_requires_peripheral)]
        channel.rx.runtime_ensure_compatible(peripheral);

        #[cfg(dma_supports_mem2mem)]
        channel.rx.set_mem2mem_mode(true);

        Mem2Mem {
            rx: Mem2MemRx {
                channel: channel.rx,
                peripheral,
            },
            tx: Mem2MemTx {
                channel: channel.tx,
                peripheral,
            },
        }
    }

    /// Shortcut to create a [SimpleMem2Mem]
    pub fn with_descriptors(
        self,
        rx_descriptors: &'d mut [DmaDescriptor],
        tx_descriptors: &'d mut [DmaDescriptor],
        config: BurstConfig,
    ) -> Result<SimpleMem2Mem<'d, Blocking>, DmaError> {
        SimpleMem2Mem::new(self, rx_descriptors, tx_descriptors, config)
    }
}

/// The RX half of [Mem2Mem].
pub struct Mem2MemRx<'d, Dm>
where
    Dm: DriverMode,
{
    channel: ErasedChannelRx<'d, Dm>,
    peripheral: DmaPeripheral,
}

impl<'d> Mem2MemRx<'d, Blocking> {
    /// Converts Mem2MemRx to an async Mem2MemRx.
    pub fn into_async(self) -> Mem2MemRx<'d, Async> {
        Mem2MemRx {
            channel: self.channel.into_async(),
            peripheral: self.peripheral,
        }
    }
}

impl<'d, Dm> Mem2MemRx<'d, Dm>
where
    Dm: DriverMode,
{
    /// Starts the RX half of a memory to memory transfer.
    pub fn receive<BUF>(
        mut self,
        mut buf: BUF,
    ) -> Result<Mem2MemRxTransfer<'d, BUF, Dm>, (DmaError, Self, BUF)>
    where
        BUF: DmaRxBuffer,
    {
        let result = unsafe {
            self.channel
                .prepare_transfer(self.peripheral, &mut buf)
                .and_then(|_| self.channel.start_transfer())
        };

        if let Err(e) = result {
            return Err((e, self, buf));
        }

        Ok(Mem2MemRxTransfer {
            m2m: ManuallyDrop::new(self),
            buf_view: ManuallyDrop::new(buf.into_view()),
        })
    }
}

/// Represents an ongoing (or potentially finished) DMA Memory-to-Memory RX
/// transfer.
pub struct Mem2MemRxTransfer<'d, BUF, Dm>
where
    BUF: DmaRxBuffer,
    Dm: DriverMode,
{
    m2m: ManuallyDrop<Mem2MemRx<'d, Dm>>,
    buf_view: ManuallyDrop<BUF::View>,
}

impl<'d, BUF, Dm> Mem2MemRxTransfer<'d, BUF, Dm>
where
    BUF: DmaRxBuffer,
    Dm: DriverMode,
{
    /// Returns whether [`Self::wait`] will not block.
    pub fn is_done(&self) -> bool {
        let done_interrupts = DmaRxInterrupt::DescriptorError | DmaRxInterrupt::DescriptorEmpty;
        !self
            .m2m
            .channel
            .pending_in_interrupts()
            .is_disjoint(done_interrupts)
    }

    /// Waits for the transfer to stop and returns the peripheral and buffer.
    pub fn wait(self) -> (Result<(), DmaError>, Mem2MemRx<'d, Dm>, BUF::Final) {
        while !self.is_done() {}

        let (m2m, view) = self.release();

        let result = if m2m.channel.has_error() {
            Err(DmaError::DescriptorError)
        } else {
            Ok(())
        };

        (result, m2m, BUF::from_view(view))
    }

    /// Stops this transfer on the spot and returns the peripheral and buffer.
    pub fn stop(self) -> (Mem2MemRx<'d, Dm>, BUF::Final) {
        let (mut m2m, view) = self.release();

        m2m.channel.stop_transfer();

        (m2m, BUF::from_view(view))
    }

    fn release(mut self) -> (Mem2MemRx<'d, Dm>, BUF::View) {
        // SAFETY: Since forget is called on self, we know that self.m2m and
        // self.buf_view won't be touched again.
        let result = unsafe {
            let m2m = ManuallyDrop::take(&mut self.m2m);
            let view = ManuallyDrop::take(&mut self.buf_view);
            (m2m, view)
        };
        core::mem::forget(self);
        result
    }
}

impl<'d, BUF, Dm> Deref for Mem2MemRxTransfer<'d, BUF, Dm>
where
    BUF: DmaRxBuffer,
    Dm: DriverMode,
{
    type Target = BUF::View;

    fn deref(&self) -> &Self::Target {
        &self.buf_view
    }
}

impl<'d, BUF, Dm> DerefMut for Mem2MemRxTransfer<'d, BUF, Dm>
where
    BUF: DmaRxBuffer,
    Dm: DriverMode,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.buf_view
    }
}

impl<'d, BUF, Dm> Drop for Mem2MemRxTransfer<'d, BUF, Dm>
where
    BUF: DmaRxBuffer,
    Dm: DriverMode,
{
    fn drop(&mut self) {
        self.m2m.channel.stop_transfer();

        // SAFETY: This is Drop, we know that self.m2m and self.buf_view
        // won't be touched again.
        let view = unsafe {
            ManuallyDrop::drop(&mut self.m2m);
            ManuallyDrop::take(&mut self.buf_view)
        };
        let _ = BUF::from_view(view);
    }
}

/// The TX half of [Mem2Mem].
pub struct Mem2MemTx<'d, Dm>
where
    Dm: DriverMode,
{
    channel: ErasedChannelTx<'d, Dm>,
    peripheral: DmaPeripheral,
}

impl<'d> Mem2MemTx<'d, Blocking> {
    /// Converts Mem2MemTx to an async Mem2MemTx.
    pub fn into_async(self) -> Mem2MemTx<'d, Async> {
        Mem2MemTx {
            channel: self.channel.into_async(),
            peripheral: self.peripheral,
        }
    }
}

impl<'d, Dm> Mem2MemTx<'d, Dm>
where
    Dm: DriverMode,
{
    /// Starts the TX half of a memory to memory transfer.
    pub fn send<BUF>(
        mut self,
        mut buf: BUF,
    ) -> Result<Mem2MemTxTransfer<'d, BUF, Dm>, (DmaError, Self, BUF)>
    where
        BUF: DmaTxBuffer,
    {
        let result = unsafe {
            self.channel
                .prepare_transfer(self.peripheral, &mut buf)
                .and_then(|_| self.channel.start_transfer())
        };

        if let Err(e) = result {
            return Err((e, self, buf));
        }

        Ok(Mem2MemTxTransfer {
            m2m: ManuallyDrop::new(self),
            buf_view: ManuallyDrop::new(buf.into_view()),
        })
    }
}

/// Represents an ongoing (or potentially finished) DMA Memory-to-Memory TX
/// transfer.
pub struct Mem2MemTxTransfer<'d, BUF, Dm>
where
    BUF: DmaTxBuffer,
    Dm: DriverMode,
{
    m2m: ManuallyDrop<Mem2MemTx<'d, Dm>>,
    buf_view: ManuallyDrop<BUF::View>,
}

impl<'d, BUF, Dm> Mem2MemTxTransfer<'d, BUF, Dm>
where
    BUF: DmaTxBuffer,
    Dm: DriverMode,
{
    /// Returns whether [`Self::wait`] will not block.
    pub fn is_done(&self) -> bool {
        let done_interrupts = DmaTxInterrupt::DescriptorError | DmaTxInterrupt::TotalEof;
        !self
            .m2m
            .channel
            .pending_out_interrupts()
            .is_disjoint(done_interrupts)
    }

    /// Waits for the transfer to stop and returns the peripheral and buffer.
    pub fn wait(self) -> (Result<(), DmaError>, Mem2MemTx<'d, Dm>, BUF::Final) {
        while !self.is_done() {}

        let (m2m, view) = self.release();

        let result = if m2m.channel.has_error() {
            Err(DmaError::DescriptorError)
        } else {
            Ok(())
        };

        (result, m2m, BUF::from_view(view))
    }

    /// Stops this transfer on the spot and returns the peripheral and buffer.
    pub fn stop(self) -> (Mem2MemTx<'d, Dm>, BUF::Final) {
        let (mut m2m, view) = self.release();

        m2m.channel.stop_transfer();

        (m2m, BUF::from_view(view))
    }

    fn release(mut self) -> (Mem2MemTx<'d, Dm>, BUF::View) {
        // SAFETY: Since forget is called on self, we know that self.m2m and
        // self.buf_view won't be touched again.
        let result = unsafe {
            let m2m = ManuallyDrop::take(&mut self.m2m);
            let view = ManuallyDrop::take(&mut self.buf_view);
            (m2m, view)
        };
        core::mem::forget(self);
        result
    }
}

impl<'d, BUF, Dm> Deref for Mem2MemTxTransfer<'d, BUF, Dm>
where
    BUF: DmaTxBuffer,
    Dm: DriverMode,
{
    type Target = BUF::View;

    fn deref(&self) -> &Self::Target {
        &self.buf_view
    }
}

impl<'d, BUF, Dm> DerefMut for Mem2MemTxTransfer<'d, BUF, Dm>
where
    BUF: DmaTxBuffer,
    Dm: DriverMode,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.buf_view
    }
}

impl<'d, BUF, Dm> Drop for Mem2MemTxTransfer<'d, BUF, Dm>
where
    BUF: DmaTxBuffer,
    Dm: DriverMode,
{
    fn drop(&mut self) {
        self.m2m.channel.stop_transfer();

        // SAFETY: This is Drop, we know that self.m2m and self.buf_view
        // won't be touched again.
        let view = unsafe {
            ManuallyDrop::drop(&mut self.m2m);
            ManuallyDrop::take(&mut self.buf_view)
        };
        let _ = BUF::from_view(view);
    }
}

/// A simple and easy to use wrapper around [SimpleMem2Mem].
/// More complex memory to memory transfers should use [Mem2Mem] directly.
pub struct SimpleMem2Mem<'d, Dm>
where
    Dm: DriverMode,
{
    state: State<'d, Dm>,
    config: BurstConfig,
}

enum State<'d, Dm: DriverMode> {
    Idle(
        Mem2Mem<'d, Dm>,
        DmaAlignedMut<'d, [DmaDescriptor]>,
        DmaAlignedMut<'d, [DmaDescriptor]>,
    ),
    Active(
        Mem2MemRxTransfer<'d, DmaRxBuf, Dm>,
        Mem2MemTxTransfer<'d, DmaTxBuf, Dm>,
    ),
    InUse,
}

impl<'d, Dm> SimpleMem2Mem<'d, Dm>
where
    Dm: DriverMode,
{
    /// Creates a new [SimpleMem2Mem].
    pub fn new(
        mem2mem: Mem2Mem<'d, Dm>,
        rx_descriptors: &'d mut [DmaDescriptor],
        tx_descriptors: &'d mut [DmaDescriptor],
        config: BurstConfig,
    ) -> Result<Self, DmaError> {
        if rx_descriptors.is_empty() || tx_descriptors.is_empty() {
            return Err(DmaError::OutOfDescriptors);
        }

        // Safety: descriptors are aligned to what the DMA requires, and we don't call invalidate on
        // these slices.
        let rx_descriptors = unsafe { DmaAlignedMut::new_unchecked(rx_descriptors) };
        let tx_descriptors = unsafe { DmaAlignedMut::new_unchecked(tx_descriptors) };

        Ok(Self {
            state: State::Idle(mem2mem, rx_descriptors, tx_descriptors),
            config,
        })
    }
}

impl<'d, Dm> SimpleMem2Mem<'d, Dm>
where
    Dm: DriverMode,
{
    /// Starts a memory to memory transfer.
    pub fn start_transfer(
        &mut self,
        rx_buffer: &mut [u8],
        tx_buffer: &[u8],
    ) -> Result<SimpleMem2MemTransfer<'_, 'd, Dm>, DmaError> {
        let State::Idle(mem2mem, mut rx_descriptors, mut tx_descriptors) =
            core::mem::replace(&mut self.state, State::InUse)
        else {
            panic!("SimpleMem2MemTransfer was forgotten with core::mem::forget or similar");
        };

        // Raise these buffers to 'static. This is not safe, bad things will happen if
        // the user calls core::mem::forget on SimpleMem2MemTransfer. This is
        // just the unfortunate consequence of doing DMA without enforcing
        // 'static.
        let rx_buffer = DmaAlignedMut::new(unsafe {
            core::slice::from_raw_parts_mut(rx_buffer.as_mut_ptr(), rx_buffer.len())
        })?;
        let tx_buffer = unsafe {
            DmaAlignedMut::new_unchecked(core::slice::from_raw_parts_mut(
                tx_buffer.as_ptr() as _,
                tx_buffer.len(),
            ))
        };
        let rx_descriptors = unsafe {
            DmaAlignedMut::new_unchecked(core::slice::from_raw_parts_mut(
                rx_descriptors.as_mut_ptr(),
                rx_descriptors.len(),
            ))
        };
        let tx_descriptors = unsafe {
            DmaAlignedMut::new_unchecked(core::slice::from_raw_parts_mut(
                tx_descriptors.as_mut_ptr(),
                tx_descriptors.len(),
            ))
        };

        // Note: The ESP32-S2 insists that RX is started before TX. Contrary to the TRM
        // and every other chip.

        let dma_rx_buf = unwrap!(
            DmaRxBuf::new_with_config(rx_descriptors, rx_buffer, self.config),
            "There's no way to get the descriptors back yet"
        );

        let rx = match mem2mem.rx.receive(dma_rx_buf) {
            Ok(rx) => rx,
            Err((err, rx, buf)) => {
                let (rx_descriptors, _rx_buffer) = buf.split();
                self.state = State::Idle(
                    Mem2Mem { rx, tx: mem2mem.tx },
                    rx_descriptors,
                    tx_descriptors,
                );
                return Err(err);
            }
        };

        let dma_tx_buf = unwrap!(
            DmaTxBuf::new_with_config(tx_descriptors, tx_buffer, self.config),
            "There's no way to get the descriptors back yet"
        );

        let tx = match mem2mem.tx.send(dma_tx_buf) {
            Ok(tx) => tx,
            Err((err, tx, buf)) => {
                let (tx_descriptors, _tx_buffer) = buf.split();
                let (rx, buf) = rx.stop();
                let (rx_descriptors, _rx_buffer) = buf.split();
                self.state = State::Idle(Mem2Mem { rx, tx }, rx_descriptors, tx_descriptors);
                return Err(err);
            }
        };

        self.state = State::Active(rx, tx);

        Ok(SimpleMem2MemTransfer(self))
    }
}

impl<Dm> Drop for SimpleMem2Mem<'_, Dm>
where
    Dm: DriverMode,
{
    fn drop(&mut self) {
        if !matches!(&mut self.state, State::Idle(_, _, _)) {
            panic!("SimpleMem2MemTransfer was forgotten with core::mem::forget or similar");
        }
    }
}

/// Represents an ongoing (or potentially finished) DMA Memory-to-Memory
/// transfer.
pub struct SimpleMem2MemTransfer<'a, 'd, Dm>(&'a mut SimpleMem2Mem<'d, Dm>)
where
    Dm: DriverMode;

impl<Dm> SimpleMem2MemTransfer<'_, '_, Dm>
where
    Dm: DriverMode,
{
    /// Returns whether [`Self::wait`] will not block.
    pub fn is_done(&self) -> bool {
        let State::Active(rx, tx) = &self.0.state else {
            unreachable!()
        };

        // Wait for transmission to finish, and wait for the RX channel to receive the
        // one and only EOF that DmaTxBuf will send.
        tx.is_done()
            && rx
                .m2m
                .channel
                .pending_in_interrupts()
                .contains(DmaRxInterrupt::SuccessfulEof)
    }

    /// Waits for the transfer to finish.
    pub fn wait(self) -> Result<(), DmaError> {
        while !self.is_done() {}
        Ok(())
    }
}

impl<Dm> Drop for SimpleMem2MemTransfer<'_, '_, Dm>
where
    Dm: DriverMode,
{
    fn drop(&mut self) {
        let State::Active(rx, tx) = core::mem::replace(&mut self.0.state, State::InUse) else {
            unreachable!()
        };

        let (tx, dma_tx_buf) = tx.stop();
        let (rx, dma_rx_buf) = rx.stop();

        let (tx_descriptors, _tx_buffer) = dma_tx_buf.split();
        let (rx_descriptors, _rx_buffer) = dma_rx_buf.split();

        self.0.state = State::Idle(Mem2Mem { rx, tx }, rx_descriptors, tx_descriptors);
    }
}