Skip to main content

esp_hal/dma/engine/
crypto.rs

1use enumset::EnumSet;
2use portable_atomic::{AtomicBool, Ordering};
3
4use crate::{
5    RegisterToggle,
6    asynch::AtomicWaker,
7    dma::{
8        BurstConfig,
9        DmaChannel,
10        DmaExtMemBKSize,
11        DmaPeripheral,
12        DmaRxChannel,
13        DmaRxInterrupt,
14        DmaTxChannel,
15        DmaTxInterrupt,
16        InterruptAccess,
17        RegisterAccess,
18        RxRegisterAccess,
19        TxRegisterAccess,
20    },
21    interrupt::InterruptHandler,
22    peripherals::{DMA_CRYPTO, Interrupt},
23    system::{Peripheral, PeripheralGuard},
24};
25
26/// Immutable per-channel metadata.
27#[doc(hidden)]
28pub struct ChannelInfo {
29    /// Peripheral IDs this channel can serve. An empty slice means no runtime check is needed.
30    pub(crate) compatible_peripherals: &'static [u8],
31}
32
33/// Mutable per-channel runtime state (wakers and async-mode flags).
34pub(crate) struct ChannelState {
35    /// Async waker for the TX (out) half of this channel.
36    pub(crate) tx_waker: AtomicWaker,
37
38    /// Async waker for the RX (in) half of this channel.
39    pub(crate) rx_waker: AtomicWaker,
40
41    /// Whether the TX half is currently in async mode.
42    pub(crate) tx_async_flag: portable_atomic::AtomicBool,
43
44    /// Whether the RX half is currently in async mode.
45    pub(crate) rx_async_flag: portable_atomic::AtomicBool,
46}
47
48pub(super) type CryptoRegisterBlock = crate::pac::crypto_dma::RegisterBlock;
49
50/// The RX half of a Crypto DMA channel.
51#[derive(Debug)]
52#[cfg_attr(feature = "defmt", derive(defmt::Format))]
53pub struct CryptoDmaRxChannel<'d>(CryptoDmaChannel<'d>);
54
55impl CryptoDmaRxChannel<'_> {
56    fn regs(&self) -> &CryptoRegisterBlock {
57        self.0.register_block()
58    }
59}
60
61impl crate::private::Sealed for CryptoDmaRxChannel<'_> {}
62impl DmaRxChannel for CryptoDmaRxChannel<'_> {}
63
64/// The TX half of a Crypto DMA channel.
65#[derive(Debug)]
66#[cfg_attr(feature = "defmt", derive(defmt::Format))]
67pub struct CryptoDmaTxChannel<'d>(CryptoDmaChannel<'d>);
68
69impl CryptoDmaTxChannel<'_> {
70    fn regs(&self) -> &CryptoRegisterBlock {
71        self.0.register_block()
72    }
73}
74
75impl crate::private::Sealed for CryptoDmaTxChannel<'_> {}
76impl DmaTxChannel for CryptoDmaTxChannel<'_> {}
77
78impl RegisterAccess for CryptoDmaTxChannel<'_> {
79    #[allow(private_interfaces)]
80    fn enable(&self) -> Option<PeripheralGuard> {
81        Some(PeripheralGuard::new(Peripheral::CryptoDma))
82    }
83
84    fn reset(&self) {
85        self.regs().conf().toggle(|w, bit| {
86            w.out_rst().bit(bit);
87            w.ahbm_rst().bit(bit);
88            w.ahbm_fifo_rst().bit(bit)
89        });
90    }
91
92    fn set_burst_mode(&self, burst_mode: BurstConfig) {
93        self.regs()
94            .conf()
95            .modify(|_, w| w.out_data_burst_en().bit(burst_mode.is_burst_enabled()));
96    }
97
98    fn set_descr_burst_mode(&self, burst_mode: bool) {
99        self.regs()
100            .conf()
101            .modify(|_, w| w.outdscr_burst_en().bit(burst_mode));
102    }
103
104    fn set_peripheral(&self, peripheral: u8) {
105        use esp32s2::crypto_dma::aes_sha_select::SELECT;
106        let sel = match peripheral {
107            p if p == DmaPeripheral::AES.0 => SELECT::Aes,
108            p if p == DmaPeripheral::SHA.0 => SELECT::Sha,
109            _ => unreachable!(),
110        };
111        self.regs()
112            .aes_sha_select()
113            .modify(|_, w| w.select().variant(sel));
114    }
115
116    fn set_link_addr(&self, address: u32) {
117        self.regs()
118            .out_link()
119            .modify(|_, w| unsafe { w.outlink_addr().bits(address) });
120    }
121
122    fn start(&self) {
123        self.regs()
124            .out_link()
125            .modify(|_, w| w.outlink_start().set_bit());
126    }
127
128    fn stop(&self) {
129        self.regs()
130            .out_link()
131            .modify(|_, w| w.outlink_stop().set_bit());
132    }
133
134    fn restart(&self) {
135        self.regs()
136            .out_link()
137            .modify(|_, w| w.outlink_restart().set_bit());
138    }
139
140    fn set_check_owner(&self, check_owner: Option<bool>) {
141        if check_owner == Some(true) {
142            panic!("Crypto DMA does not support checking descriptor ownership");
143        }
144    }
145
146    #[cfg(dma_ext_mem_configurable_block_size)]
147    fn set_ext_mem_block_size(&self, size: DmaExtMemBKSize) {
148        self.regs()
149            .conf1()
150            .modify(|_, w| unsafe { w.ext_mem_bk_size().bits(size as u8) });
151    }
152
153    #[cfg(dma_can_access_psram)]
154    fn can_access_psram(&self) -> bool {
155        true
156    }
157
158    fn compatible_peripherals(&self) -> &[u8] {
159        self.0.info().compatible_peripherals
160    }
161}
162
163impl TxRegisterAccess for CryptoDmaTxChannel<'_> {
164    fn is_fifo_empty(&self) -> bool {
165        self.regs().state1().read().outfifo_cnt_debug().bits() == 0
166    }
167
168    fn set_auto_write_back(&self, enable: bool) {
169        self.regs()
170            .conf()
171            .modify(|_, w| w.out_auto_wrback().bit(enable));
172    }
173
174    fn last_dscr_address(&self) -> usize {
175        self.regs()
176            .out_eof_des_addr()
177            .read()
178            .out_eof_des_addr()
179            .bits() as usize
180    }
181
182    fn peripheral_interrupt(&self) -> Option<Interrupt> {
183        None
184    }
185
186    fn async_handler(&self) -> Option<InterruptHandler> {
187        None
188    }
189}
190
191impl InterruptAccess<DmaTxInterrupt> for CryptoDmaTxChannel<'_> {
192    fn enable_listen(&self, interrupts: EnumSet<DmaTxInterrupt>, enable: bool) {
193        self.regs().int_ena().modify(|_, w| {
194            for interrupt in interrupts {
195                match interrupt {
196                    DmaTxInterrupt::TotalEof => w.out_total_eof().bit(enable),
197                    DmaTxInterrupt::DescriptorError => w.out_dscr_err().bit(enable),
198                    DmaTxInterrupt::Eof => w.out_eof().bit(enable),
199                    DmaTxInterrupt::Done => w.out_done().bit(enable),
200                };
201            }
202            w
203        });
204    }
205
206    fn is_listening(&self) -> EnumSet<DmaTxInterrupt> {
207        let mut result = EnumSet::new();
208
209        let int_ena = self.regs().int_ena().read();
210        if int_ena.out_total_eof().bit_is_set() {
211            result |= DmaTxInterrupt::TotalEof;
212        }
213        if int_ena.out_dscr_err().bit_is_set() {
214            result |= DmaTxInterrupt::DescriptorError;
215        }
216        if int_ena.out_eof().bit_is_set() {
217            result |= DmaTxInterrupt::Eof;
218        }
219        if int_ena.out_done().bit_is_set() {
220            result |= DmaTxInterrupt::Done;
221        }
222
223        result
224    }
225
226    fn clear(&self, interrupts: impl Into<EnumSet<DmaTxInterrupt>>) {
227        self.regs().int_clr().write(|w| {
228            for interrupt in interrupts.into() {
229                match interrupt {
230                    DmaTxInterrupt::TotalEof => w.out_total_eof().clear_bit_by_one(),
231                    DmaTxInterrupt::DescriptorError => w.out_dscr_err().clear_bit_by_one(),
232                    DmaTxInterrupt::Eof => w.out_eof().clear_bit_by_one(),
233                    DmaTxInterrupt::Done => w.out_done().clear_bit_by_one(),
234                };
235            }
236            w
237        });
238    }
239
240    fn pending_interrupts(&self) -> EnumSet<DmaTxInterrupt> {
241        let mut result = EnumSet::new();
242
243        let int_raw = self.regs().int_raw().read();
244        if int_raw.out_total_eof().bit_is_set() {
245            result |= DmaTxInterrupt::TotalEof;
246        }
247        if int_raw.out_dscr_err().bit_is_set() {
248            result |= DmaTxInterrupt::DescriptorError;
249        }
250        if int_raw.out_eof().bit_is_set() {
251            result |= DmaTxInterrupt::Eof;
252        }
253        if int_raw.out_done().bit_is_set() {
254            result |= DmaTxInterrupt::Done;
255        }
256
257        result
258    }
259
260    fn waker(&self) -> &'static AtomicWaker {
261        &self.0.state().tx_waker
262    }
263
264    fn is_async(&self) -> bool {
265        self.0.state().tx_async_flag.load(Ordering::Acquire)
266    }
267
268    fn set_async(&self, is_async: bool) {
269        self.0
270            .state()
271            .tx_async_flag
272            .store(is_async, Ordering::Release);
273    }
274}
275
276impl RegisterAccess for CryptoDmaRxChannel<'_> {
277    #[allow(private_interfaces)]
278    fn enable(&self) -> Option<PeripheralGuard> {
279        Some(PeripheralGuard::new(Peripheral::CryptoDma))
280    }
281
282    fn reset(&self) {
283        self.regs().conf().toggle(|w, bit| {
284            w.in_rst().bit(bit);
285            w.ahbm_rst().bit(bit);
286            w.ahbm_fifo_rst().bit(bit)
287        });
288    }
289
290    fn set_burst_mode(&self, _burst_mode: BurstConfig) {}
291
292    fn set_descr_burst_mode(&self, burst_mode: bool) {
293        self.regs()
294            .conf()
295            .modify(|_, w| w.indscr_burst_en().bit(burst_mode));
296    }
297
298    fn set_peripheral(&self, peripheral: u8) {
299        use esp32s2::crypto_dma::aes_sha_select::SELECT;
300        let sel = match peripheral {
301            p if p == DmaPeripheral::AES.0 => SELECT::Aes,
302            p if p == DmaPeripheral::SHA.0 => SELECT::Sha,
303            _ => unreachable!(),
304        };
305        self.regs()
306            .aes_sha_select()
307            .modify(|_, w| w.select().variant(sel));
308    }
309
310    fn set_link_addr(&self, address: u32) {
311        self.regs()
312            .in_link()
313            .modify(|_, w| unsafe { w.inlink_addr().bits(address) });
314    }
315
316    fn start(&self) {
317        self.regs()
318            .in_link()
319            .modify(|_, w| w.inlink_start().set_bit());
320    }
321
322    fn stop(&self) {
323        self.regs()
324            .in_link()
325            .modify(|_, w| w.inlink_stop().set_bit());
326    }
327
328    fn restart(&self) {
329        self.regs()
330            .in_link()
331            .modify(|_, w| w.inlink_restart().set_bit());
332    }
333
334    fn set_check_owner(&self, check_owner: Option<bool>) {
335        if check_owner == Some(true) {
336            panic!("Crypto DMA does not support checking descriptor ownership");
337        }
338    }
339
340    #[cfg(dma_ext_mem_configurable_block_size)]
341    fn set_ext_mem_block_size(&self, size: DmaExtMemBKSize) {
342        self.regs()
343            .conf1()
344            .modify(|_, w| unsafe { w.ext_mem_bk_size().bits(size as u8) });
345    }
346
347    #[cfg(dma_can_access_psram)]
348    fn can_access_psram(&self) -> bool {
349        true
350    }
351
352    fn compatible_peripherals(&self) -> &[u8] {
353        self.0.info().compatible_peripherals
354    }
355}
356
357impl RxRegisterAccess for CryptoDmaRxChannel<'_> {
358    #[cfg(dma_supports_mem2mem)]
359    fn set_mem2mem_mode(&self, en: bool) {
360        self.regs().conf().modify(|_, w| w.mem_trans_en().bit(en));
361    }
362
363    fn peripheral_interrupt(&self) -> Option<Interrupt> {
364        // We don't know if the channel is used by AES or SHA, so interrupt handler
365        // setup is the responsibility of the peripheral driver.
366        None
367    }
368
369    fn async_handler(&self) -> Option<InterruptHandler> {
370        None
371    }
372}
373
374impl InterruptAccess<DmaRxInterrupt> for CryptoDmaRxChannel<'_> {
375    fn enable_listen(&self, interrupts: EnumSet<DmaRxInterrupt>, enable: bool) {
376        self.regs().int_ena().modify(|_, w| {
377            for interrupt in interrupts {
378                match interrupt {
379                    DmaRxInterrupt::SuccessfulEof => w.in_suc_eof().bit(enable),
380                    DmaRxInterrupt::ErrorEof => w.in_err_eof().bit(enable),
381                    DmaRxInterrupt::DescriptorError => w.in_dscr_err().bit(enable),
382                    DmaRxInterrupt::DescriptorEmpty => w.in_dscr_empty().bit(enable),
383                    DmaRxInterrupt::Done => w.in_done().bit(enable),
384                };
385            }
386            w
387        });
388    }
389
390    fn is_listening(&self) -> EnumSet<DmaRxInterrupt> {
391        let mut result = EnumSet::new();
392
393        let int_ena = self.regs().int_ena().read();
394        if int_ena.in_dscr_err().bit_is_set() {
395            result |= DmaRxInterrupt::DescriptorError;
396        }
397        if int_ena.in_dscr_empty().bit_is_set() {
398            result |= DmaRxInterrupt::DescriptorEmpty;
399        }
400        if int_ena.in_suc_eof().bit_is_set() {
401            result |= DmaRxInterrupt::SuccessfulEof;
402        }
403        if int_ena.in_err_eof().bit_is_set() {
404            result |= DmaRxInterrupt::ErrorEof;
405        }
406        if int_ena.in_done().bit_is_set() {
407            result |= DmaRxInterrupt::Done;
408        }
409
410        result
411    }
412
413    fn clear(&self, interrupts: impl Into<EnumSet<DmaRxInterrupt>>) {
414        self.regs().int_clr().write(|w| {
415            for interrupt in interrupts.into() {
416                match interrupt {
417                    DmaRxInterrupt::SuccessfulEof => w.in_suc_eof().clear_bit_by_one(),
418                    DmaRxInterrupt::ErrorEof => w.in_err_eof().clear_bit_by_one(),
419                    DmaRxInterrupt::DescriptorError => w.in_dscr_err().clear_bit_by_one(),
420                    DmaRxInterrupt::DescriptorEmpty => w.in_dscr_empty().clear_bit_by_one(),
421                    DmaRxInterrupt::Done => w.in_done().clear_bit_by_one(),
422                };
423            }
424            w
425        });
426    }
427
428    fn pending_interrupts(&self) -> EnumSet<DmaRxInterrupt> {
429        let mut result = EnumSet::new();
430
431        let int_raw = self.regs().int_raw().read();
432        if int_raw.in_dscr_err().bit_is_set() {
433            result |= DmaRxInterrupt::DescriptorError;
434        }
435        if int_raw.in_dscr_empty().bit_is_set() {
436            result |= DmaRxInterrupt::DescriptorEmpty;
437        }
438        if int_raw.in_suc_eof().bit_is_set() {
439            result |= DmaRxInterrupt::SuccessfulEof;
440        }
441        if int_raw.in_err_eof().bit_is_set() {
442            result |= DmaRxInterrupt::ErrorEof;
443        }
444        if int_raw.in_done().bit_is_set() {
445            result |= DmaRxInterrupt::Done;
446        }
447
448        result
449    }
450
451    fn waker(&self) -> &'static AtomicWaker {
452        &self.0.state().rx_waker
453    }
454
455    fn is_async(&self) -> bool {
456        self.0.state().rx_async_flag.load(Ordering::Relaxed)
457    }
458
459    fn set_async(&self, is_async: bool) {
460        self.0
461            .state()
462            .rx_async_flag
463            .store(is_async, Ordering::Relaxed);
464    }
465}
466
467/// A crypto-compatible type-erased DMA channel.
468pub type CryptoDmaChannel<'d> = DMA_CRYPTO<'d>;
469
470impl DMA_CRYPTO<'_> {
471    pub(super) fn info(&self) -> &'static ChannelInfo {
472        static INFO: ChannelInfo = ChannelInfo {
473            compatible_peripherals: &[DmaPeripheral::AES.0, DmaPeripheral::SHA.0],
474        };
475        &INFO
476    }
477
478    pub(super) fn state(&self) -> &'static ChannelState {
479        static STATE: ChannelState = ChannelState {
480            tx_waker: AtomicWaker::new(),
481            rx_waker: AtomicWaker::new(),
482            tx_async_flag: AtomicBool::new(false),
483            rx_async_flag: AtomicBool::new(false),
484        };
485        &STATE
486    }
487}
488
489crate::dma::impl_channel_common!(CryptoDma, DMA_CRYPTO);