Skip to main content

esp_hal/
ecc.rs

1//! # Elliptic Curve Cryptography (ECC) Accelerator
2//!
3//! ## Overview
4//!
5//! Elliptic Curve Cryptography (ECC) is an approach to public-key cryptography
6//! based on the algebraic structure of elliptic curves. ECC allows smaller
7//! keys compared to RSA cryptography while providing equivalent security.
8//!
9//! ECC Accelerator can complete various calculation based on different
10//! elliptic curves, thus accelerating ECC algorithm and ECC-derived
11//! algorithms (such as ECDSA).
12
13use core::{marker::PhantomData, ptr::NonNull};
14
15use procmacros::BuilderLite;
16
17#[cfg(ecc_supports_enhanced_security)]
18use crate::efuse::ChipRevision;
19use crate::{
20    Blocking,
21    DriverMode,
22    interrupt::InterruptHandler,
23    pac::{self, ecc::mult_conf::KEY_LENGTH},
24    peripherals::{ECC, Interrupt},
25    private::Sealed,
26    system::{self, CryptoClockGuard, GenericPeripheralGuard},
27    work_queue::{Handle, Poll, Status, VTable, WorkQueue, WorkQueueDriver, WorkQueueFrontend},
28};
29
30/// This macro defines 4 other macros:
31/// - `doc_summary` that takes the first line of the documentation and returns it as a string
32/// - `result_type` that generates the return types for each operation
33/// - `operation` that generates the operation function
34/// - `backend_operation` that generates the backend operation function
35///
36/// These generated macros can then be fed to `for_each_ecc_working_mode!` to generate operations
37/// the device supports.
38macro_rules! define_operations {
39    ($($op:tt {
40        // The first line is used for summary, and it is prepended with `# ` on the driver method.
41        docs: [$first_line:literal $(, $lines:literal)*],
42        // The driver method name
43        function: $function:ident,
44        // Whether the operation is modular, i.e. whether it needs a modulus argument.
45        $(modular_arithmetic_method: $is_modular:literal,)?
46        // Whether the operation does point verification first.
47        $(verifies_point: $verifies_point:literal,)?
48        // Input parameters. This determines the name and order of the function arguments,
49        // as well as which memory block they will be written to. Depending on the value of
50        // cfg(ecc_separate_jacobian_point_memory), qx, qy and qz may be mapped to px, py and k.
51        inputs: [$($input:ident),*],
52        // What data does the output contain?
53        // - Scalar (and which memory block contains the scalar)
54        // - AffinePoint
55        // - JacobianPoint
56        returns: [
57            $(
58                // What data is computed may be device specific.
59                $(#[$returns_meta:meta])*
60                $returns:ident $({ const $c:ident: $t:tt = $v:expr })?
61            ),*
62        ]
63    }),*) => {
64        macro_rules! doc_summary {
65            $(
66                ($op) => { $first_line };
67            )*
68        }
69        macro_rules! result_type {
70            $(
71                ($op) => {
72                    #[doc = concat!("A marker type representing ", doc_summary!($op))]
73                    #[non_exhaustive]
74                    pub struct $op;
75
76                    impl crate::private::Sealed for $op {}
77
78                    impl EccOperation for $op {
79                        const WORK_MODE: WorkMode = WorkMode::$op;
80                        const VERIFIES_POINT: bool = $crate::if_set!($($verifies_point)?, false);
81                    }
82
83                    paste::paste! {
84                        $(
85                            $(#[$returns_meta])*
86                            impl [<OperationReturns $returns>] for $op {
87                                $(
88                                    const $c: $t = $v;
89                                )?
90                            }
91                        )*
92
93                        $(
94                            const _: bool = $verifies_point; // I just need this ignored.
95                            impl OperationVerifiesPoint for $op {}
96                        )?
97                    }
98                };
99            )*
100        }
101        macro_rules! driver_method {
102            $(
103                ($op) => {
104                    #[doc = concat!("# ", $first_line)]
105                    $(#[doc = $lines])*
106                    #[doc = r"
107
108# Errors
109
110[`OperationError::ParameterLengthMismatch`] if an input does not match the curve's size."]
111                    #[cfg_attr(ecc_has_curve_sm2, doc = "\n[`OperationError::UnsupportedCurve`] if SM2 is disabled by eFuse.")]
112                    #[inline]
113                    pub fn $function<'op>(
114                        &'op mut self,
115                        curve: EllipticCurve,
116                        $(#[cfg($is_modular)] modulus: EccModBase,)?
117                        $($input: &[u8],)*
118                    ) -> Result<EccResultHandle<'op, $op>, OperationError> {
119                        curve.check_parameters([$($input),*])?;
120
121                        paste::paste! {
122                            $(
123                                self.info().write_mem(self.info().[<$input _mem>](), $input);
124                            )*
125                        };
126
127                        #[cfg(ecc_has_modular_arithmetic)]
128                        let mod_base = $crate::if_set! {
129                            $(
130                                {
131                                    $crate::ignore!($is_modular);
132                                    modulus
133                                }
134                            )?,
135                            // else
136                            EccModBase::OrderOfCurve
137                        };
138
139                        Ok(self.run_operation::<$op>(
140                            curve,
141                            #[cfg(ecc_has_modular_arithmetic)] mod_base,
142                        ))
143                    }
144                };
145            )*
146        }
147
148        macro_rules! backend_operation {
149            $(
150                ($op) => {
151                    #[doc = concat!("Configures a new ", $first_line, " operation with the given inputs, to be executed on [`EccBackend`].")]
152                    ///
153                    /// Outputs need to be assigned separately before executing the operation.
154                    ///
155                    /// # Errors
156                    ///
157                    /// [`OperationError::ParameterLengthMismatch`] if an input does not match the curve's size.
158                    #[cfg_attr(ecc_has_curve_sm2, doc = "\n[`OperationError::UnsupportedCurve`] if SM2 is disabled by eFuse.")]
159                    pub fn $function<'op>(
160                        self,
161                        $(#[cfg($is_modular)] modulus: EccModBase,)?
162                        $($input: &'op [u8],)*
163                    ) -> Result<EccBackendOperation<'op, $op>, OperationError> {
164                        self.check_parameters([&$($input,)*])?;
165
166                        #[cfg(ecc_has_modular_arithmetic)]
167                        let mod_base = $crate::if_set! {
168                            $(
169                                {
170                                    $crate::ignore!($is_modular);
171                                    modulus
172                                }
173                            )?,
174                            // else
175                            EccModBase::OrderOfCurve
176                        };
177
178                        let work_item = EccWorkItem {
179                            curve: self,
180                            operation: WorkMode::$op,
181                            cancelled: false,
182                            #[cfg(ecc_has_modular_arithmetic)]
183                            mod_base,
184                            inputs: {
185                                let mut inputs = MemoryPointers::default();
186                                $(
187                                    paste::paste! {
188                                        inputs.[<set_ $input>](NonNull::from($input));
189                                    };
190                                )*
191                                inputs
192                            },
193                            point_verification_result: false,
194                            outputs: MemoryPointers::default(),
195                        };
196
197                        Ok(EccBackendOperation::new(work_item))
198                    }
199                };
200            )*
201        }
202    }
203}
204
205define_operations! {
206    AffinePointMultiplication {
207        docs: [
208            "Base Point Multiplication",
209            "",
210            "This operation performs `(Qx, Qy) = k * (Px, Py)`."
211        ],
212        function: affine_point_multiplication,
213        inputs: [k, px, py],
214        returns: [AffinePoint]
215    },
216
217    AffinePointVerification {
218        docs: [
219            "Base Point Verification",
220            "",
221            "This operation verifies whether Point (Px, Py) is on the selected elliptic curve."
222        ],
223        function: affine_point_verification,
224        verifies_point: true,
225        inputs: [px, py],
226        returns: []
227    },
228
229    AffinePointVerificationAndMultiplication {
230        docs: [
231            "Base Point Verification and Multiplication",
232            "",
233            "This operation verifies whether Point (Px, Py) is on the selected elliptic curve and performs `(Qx, Qy) = k * (Px, Py)`."
234        ],
235        function: affine_point_verification_multiplication,
236        verifies_point: true,
237        inputs: [k, px, py],
238        returns: [
239            AffinePoint,
240            #[cfg(ecc_separate_jacobian_point_memory)]
241            JacobianPoint
242        ]
243    },
244
245    AffinePointAddition {
246        docs: [
247            "Point Addition",
248            "",
249            "This operation performs `(Rx, Ry) = (Jx, Jy, Jz) = (Px, Py, 1) + (Qx, Qy, Qz)`."
250        ],
251        function: affine_point_addition,
252        inputs: [px, py, qx, qy, qz],
253        returns: [
254            AffinePoint,
255            #[cfg(ecc_separate_jacobian_point_memory)]
256            JacobianPoint
257        ]
258    },
259
260    JacobianPointMultiplication {
261        docs: [
262            "Jacobian Point Multiplication",
263            "",
264            "This operation performs `(Qx, Qy, Qz) = k * (Px, Py, 1)`."
265        ],
266        function: jacobian_point_multiplication,
267        inputs: [k, px, py],
268        returns: [
269            JacobianPoint
270        ]
271    },
272
273    JacobianPointVerification {
274        docs: [
275            "Jacobian Point Verification",
276            "",
277            "This operation verifies whether Point (Qx, Qy, Qz) is on the selected elliptic curve."
278        ],
279        function: jacobian_point_verification,
280        verifies_point: true,
281        inputs: [qx, qy, qz],
282        returns: [
283            JacobianPoint
284        ]
285    },
286
287    AffinePointVerificationAndJacobianPointMultiplication {
288        docs: [
289            "Base Point Verification + Jacobian Point Multiplication",
290            "",
291            "This operation first verifies whether Point (Px, Py) is on the selected elliptic curve. If yes, it performs `(Qx, Qy, Qz) = k * (Px, Py, 1)`."
292        ],
293        function: affine_point_verification_jacobian_multiplication,
294        verifies_point: true,
295        inputs: [k, px, py],
296        returns: [
297            JacobianPoint
298        ]
299    },
300
301    FiniteFieldDivision {
302        docs: [
303            "Finite Field Division",
304            "",
305            "This operation performs `R = Py * k^{−1} mod p`."
306        ],
307        function: finite_field_division,
308        inputs: [k, py],
309        returns: [
310            Scalar { const LOCATION: ScalarResultLocation = ScalarResultLocation::Py }
311        ]
312    },
313
314    ModularAddition {
315        docs: [
316            "Modular Addition",
317            "",
318            "This operation performs `R = Px + Py mod p`."
319        ],
320        function: modular_addition,
321        modular_arithmetic_method: true,
322        inputs: [px, py],
323        returns: [
324            Scalar { const LOCATION: ScalarResultLocation = ScalarResultLocation::Px }
325        ]
326    },
327
328    ModularSubtraction {
329        docs: [
330            "Modular Subtraction",
331            "",
332            "This operation performs `R = Px - Py mod p`."
333        ],
334        function: modular_subtraction,
335        modular_arithmetic_method: true,
336        inputs: [px, py],
337        returns: [
338            Scalar { const LOCATION: ScalarResultLocation = ScalarResultLocation::Px }
339        ]
340    },
341
342    ModularMultiplication {
343        docs: [
344            "Modular Multiplication",
345            "",
346            "This operation performs `R = Px * Py mod p`."
347        ],
348        function: modular_multiplication,
349        modular_arithmetic_method: true,
350        inputs: [px, py],
351        returns: [
352            Scalar { const LOCATION: ScalarResultLocation = ScalarResultLocation::Py }
353        ]
354    },
355
356    ModularDivision {
357        docs: [
358            "Modular Division",
359            "",
360            "This operation performs `R = Px * Py^{−1} mod p`."
361        ],
362        function: modular_division,
363        modular_arithmetic_method: true,
364        inputs: [px, py],
365        returns: [
366            Scalar { const LOCATION: ScalarResultLocation = ScalarResultLocation::Py }
367        ]
368    }
369}
370
371const MEM_BLOCK_SIZE: usize = property!("ecc.mem_block_size");
372
373/// The ECC Accelerator driver.
374///
375/// Unlike commonly used standards, this driver operates on **little-endian** data.
376pub struct Ecc<'d, Dm: DriverMode> {
377    _ecc: ECC<'d>,
378    phantom: PhantomData<Dm>,
379    _memory_guard: EccMemoryPowerGuard,
380    _guard: GenericPeripheralGuard<{ system::Peripheral::Ecc as u8 }>,
381    _clock_guard: CryptoClockGuard,
382}
383
384struct EccMemoryPowerGuard;
385
386impl EccMemoryPowerGuard {
387    fn new() -> Self {
388        cfg_select! {
389            esp32h4 => {
390                crate::peripherals::PCR::regs()
391                    .ecc_mem_lp_ctrl()
392                    .modify(|_, w| {
393                        w.ecc_mem_lp_en().clear_bit();
394                        w.ecc_mem_force_ctrl().set_bit()
395                    });
396            }
397            soc_has_pcr => {
398                crate::peripherals::PCR::regs()
399                    .ecc_pd_ctrl()
400                    .modify(|_, w| {
401                        w.ecc_mem_force_pd().clear_bit();
402                        w.ecc_mem_force_pu().set_bit();
403                        w.ecc_mem_pd().clear_bit()
404                    });
405            }
406            _ => {}
407        }
408        Self
409    }
410}
411
412impl Drop for EccMemoryPowerGuard {
413    fn drop(&mut self) {
414        cfg_select! {
415            esp32h4 => {
416                crate::peripherals::PCR::regs()
417                    .ecc_mem_lp_ctrl()
418                    .modify(|_, w| unsafe {
419                        w.ecc_mem_lp_mode().bits(0);
420                        w.ecc_mem_lp_en().set_bit()
421                    });
422            }
423            soc_has_pcr => {
424                crate::peripherals::PCR::regs()
425                    .ecc_pd_ctrl()
426                    .modify(|_, w| {
427                        w.ecc_mem_force_pd().clear_bit();
428                        w.ecc_mem_force_pu().clear_bit();
429                        w.ecc_mem_pd().set_bit()
430                    });
431            }
432            _ => {}
433        }
434    }
435}
436
437/// ECC peripheral configuration.
438///
439/// The default turns enhanced security on, where the chip supports it.
440#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, BuilderLite)]
441#[cfg_attr(feature = "defmt", derive(defmt::Format))]
442pub struct Config {
443    /// Force-enables the register clock.
444    force_enable_reg_clock: bool,
445
446    /// Force-enables the memory clock.
447    #[cfg(ecc_has_memory_clock_gate)]
448    force_enable_mem_clock: bool,
449
450    /// Enables constant time operation and minimized power consumption variation for
451    /// point-multiplication operations.
452    ///
453    /// Turning it off makes a point multiplication faster by an amount that depends on the
454    /// scalar's bit pattern. The time then exposes the scalar to timing-based side-channel
455    /// attacks. Turn it off only for a public scalar.
456    ///
457    /// `None` enables the mode where the chip revision supports it. Where it does not, `None`
458    /// logs a warning and `Some(true)` is refused with
459    /// [`ConfigError::EnhancedSecurityUnsupported`]. A caller that needs constant time passes
460    /// `true`.
461    ///
462    /// Default value: `None`.
463    #[cfg_attr(
464        esp32h2,
465        doc = r"
466
467Only available on chip revision 1.2 and above."
468    )]
469    #[cfg(ecc_supports_enhanced_security)]
470    enhanced_security: Option<bool>,
471}
472
473/// ECC configuration error.
474#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
475#[cfg_attr(feature = "defmt", derive(defmt::Format))]
476#[non_exhaustive]
477pub enum ConfigError {
478    /// The configuration asks for enhanced security, and this chip revision does not support it.
479    ///
480    /// Only the ESP32-H2 below revision 1.2 lacks it. The default configuration is accepted there,
481    /// turns the mode off and logs a warning.
482    #[cfg(ecc_supports_enhanced_security)]
483    EnhancedSecurityUnsupported,
484}
485
486/// Returns whether this chip revision has the enhanced security mode.
487#[cfg(ecc_supports_enhanced_security)]
488fn enhanced_security_supported() -> bool {
489    !cfg!(esp32h2) || crate::soc::chip_revision_above(ChipRevision::from_combined(102))
490}
491
492/// Returns whether `config` turns enhanced security on, with `None` resolved for this chip
493/// revision.
494#[cfg(ecc_supports_enhanced_security)]
495fn enhanced_security(config: &Config) -> Result<bool, ConfigError> {
496    match config.enhanced_security {
497        None if !enhanced_security_supported() => {
498            warn!(
499                "No ECC enhanced security on this chip revision: point multiplication exposes a private scalar to a timing side channel"
500            );
501            Ok(false)
502        }
503        None => Ok(true),
504        Some(true) if !enhanced_security_supported() => {
505            Err(ConfigError::EnhancedSecurityUnsupported)
506        }
507        Some(on) => Ok(on),
508    }
509}
510
511fn check_config(_config: &Config) -> Result<(), ConfigError> {
512    #[cfg(ecc_supports_enhanced_security)]
513    enhanced_security(_config)?;
514
515    Ok(())
516}
517
518/// ECC operation error.
519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
520pub enum OperationError {
521    /// The length of the arguments do not match the length required by the curve.
522    ParameterLengthMismatch,
523
524    /// Point verification failed.
525    PointNotOnCurve,
526
527    /// The selected curve is not supported.
528    UnsupportedCurve,
529}
530
531/// Modulus base.
532#[cfg(ecc_has_modular_arithmetic)]
533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
534pub enum EccModBase {
535    /// The order of the curve.
536    OrderOfCurve = 0,
537
538    /// Prime modulus.
539    PrimeModulus = 1,
540}
541
542for_each_ecc_curve! {
543    (all $(( $id:literal, $name:ident, $bits:literal )),*) => {
544        /// Represents supported elliptic curves for cryptographic operations.
545        ///
546        /// The methods that represent operations require the `EccBackend` to be started before use.
547        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
548        #[cfg_attr(feature = "defmt", derive(defmt::Format))]
549        pub enum EllipticCurve {
550            $(
551                #[doc = concat!("The ", stringify!($name), " elliptic curve, a ", $bits, "-bit curve.")]
552                $name,
553            )*
554        }
555        impl EllipticCurve {
556            /// Returns whether the curve is available for hardware operations.
557            #[cfg_attr(ecc_has_curve_sm2, doc = "\nSM2 is disabled when the `DIS_SM_CRYPT` eFuse is set.")]
558            #[instability::unstable]
559            pub fn is_supported(self) -> bool {
560                match self {
561                    #[cfg(ecc_has_curve_sm2)]
562                    Self::Sm2 => !crate::efuse::read_bit(crate::efuse::DIS_SM_CRYPT),
563                    _ => true,
564                }
565            }
566
567            /// Returns the size of the elliptic curve in bytes.
568            pub const fn size(self) -> usize {
569                match self {
570                    $(
571                        EllipticCurve::$name => $bits / 8,
572                    )*
573                }
574            }
575        }
576    };
577}
578
579for_each_ecc_working_mode! {
580    (all $(($wm_id:literal, $op:tt)),*) => {
581        impl EllipticCurve {
582            fn check_parameters<const N: usize>(&self, params: [&[u8]; N]) -> Result<(), OperationError> {
583                if !self.is_supported() {
584                    return Err(OperationError::UnsupportedCurve);
585                }
586
587                self.size_check(params)
588            }
589
590            fn size_check<const N: usize>(&self, params: [&[u8]; N]) -> Result<(), OperationError> {
591                let bytes = self.size();
592
593                if params.iter().any(|p| p.len() != bytes) {
594                    return Err(OperationError::ParameterLengthMismatch);
595                }
596
597                Ok(())
598            }
599
600            $(
601                // Macro defined by `define_operations`
602                backend_operation!($op);
603            )*
604        }
605    };
606}
607
608impl<'d> Ecc<'d, Blocking> {
609    /// Creates a new instance in [Blocking] mode, with the given configuration.
610    pub fn new(ecc: ECC<'d>, config: Config) -> Result<Self, ConfigError> {
611        let clock_guard = CryptoClockGuard::new();
612        let this = Self {
613            _ecc: ecc,
614            phantom: PhantomData,
615            _memory_guard: EccMemoryPowerGuard::new(),
616            _guard: GenericPeripheralGuard::new(),
617            _clock_guard: clock_guard,
618        };
619
620        this.info().apply_config(&config)?;
621
622        Ok(this)
623    }
624}
625
626impl crate::private::Sealed for Ecc<'_, Blocking> {}
627
628#[instability::unstable]
629impl crate::interrupt::InterruptConfigurable for Ecc<'_, Blocking> {
630    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
631        self.set_interrupt_handler(handler);
632    }
633}
634
635struct Info {
636    regs: &'static pac::ecc::RegisterBlock,
637}
638
639impl Info {
640    fn reset(&self) {
641        self.regs.mult_conf().reset()
642    }
643
644    fn apply_config(&self, config: &Config) -> Result<(), ConfigError> {
645        #[cfg(ecc_supports_enhanced_security)]
646        let enhanced_security = enhanced_security(config)?;
647
648        self.regs.mult_conf().modify(|_, w| {
649            w.clk_en().bit(config.force_enable_reg_clock);
650
651            #[cfg(ecc_has_memory_clock_gate)]
652            w.mem_clock_gate_force_on()
653                .bit(config.force_enable_mem_clock);
654
655            #[cfg(ecc_supports_enhanced_security)]
656            if enhanced_security_supported() {
657                w.security_mode().bit(enhanced_security);
658            }
659
660            w
661        });
662
663        Ok(())
664    }
665
666    fn check_point_verification_result(&self) -> Result<(), OperationError> {
667        if self
668            .regs
669            .mult_conf()
670            .read()
671            .verification_result()
672            .bit_is_set()
673        {
674            Ok(())
675        } else {
676            Err(OperationError::PointNotOnCurve)
677        }
678    }
679
680    #[inline]
681    fn write_mem(&self, mut word_ptr: *mut u32, data: &[u8]) {
682        // Note that at least the C2 requires writing this memory in words.
683
684        debug_assert!(data.len() <= MEM_BLOCK_SIZE);
685
686        #[cfg(ecc_zero_extend_writes)]
687        let end = word_ptr.wrapping_byte_add(MEM_BLOCK_SIZE);
688
689        let (chunks, remainder) = data.as_chunks::<4>();
690        debug_assert!(remainder.is_empty());
691
692        for word_bytes in chunks {
693            unsafe { word_ptr.write_volatile(u32::from_le_bytes(*word_bytes)) };
694            word_ptr = word_ptr.wrapping_add(1);
695        }
696
697        #[cfg(ecc_zero_extend_writes)]
698        while word_ptr < end {
699            unsafe { word_ptr.write_volatile(0) };
700            word_ptr = word_ptr.wrapping_add(1);
701        }
702    }
703
704    #[inline]
705    fn read_mem(&self, mut word_ptr: *const u32, out: &mut [u8]) {
706        let (chunks, _) = out.as_chunks_mut::<4>();
707        for word_bytes in chunks {
708            let word = unsafe { word_ptr.read_volatile() };
709            word_ptr = word_ptr.wrapping_add(1);
710            *word_bytes = word.to_le_bytes();
711        }
712    }
713
714    fn k_mem(&self) -> *mut u32 {
715        self.regs.k_mem(0).as_ptr()
716    }
717
718    fn px_mem(&self) -> *mut u32 {
719        self.regs.px_mem(0).as_ptr()
720    }
721
722    fn py_mem(&self) -> *mut u32 {
723        self.regs.py_mem(0).as_ptr()
724    }
725
726    fn qx_mem(&self) -> *mut u32 {
727        cfg_select! {
728            ecc_separate_jacobian_point_memory => self.regs.qx_mem(0).as_ptr(),
729            _ => self.regs.px_mem(0).as_ptr(),
730        }
731    }
732
733    fn qy_mem(&self) -> *mut u32 {
734        cfg_select! {
735            ecc_separate_jacobian_point_memory => self.regs.qy_mem(0).as_ptr(),
736            _ => self.regs.py_mem(0).as_ptr(),
737        }
738    }
739
740    fn qz_mem(&self) -> *mut u32 {
741        cfg_select! {
742            ecc_separate_jacobian_point_memory => self.regs.qz_mem(0).as_ptr(),
743            _ => self.regs.k_mem(0).as_ptr(),
744        }
745    }
746
747    fn read_point_result(&self, x: &mut [u8], y: &mut [u8]) {
748        self.read_mem(self.px_mem(), x);
749        self.read_mem(self.py_mem(), y);
750    }
751
752    fn read_jacobian_result(&self, qx: &mut [u8], qy: &mut [u8], qz: &mut [u8]) {
753        self.read_mem(self.qx_mem(), qx);
754        self.read_mem(self.qy_mem(), qy);
755        self.read_mem(self.qz_mem(), qz);
756    }
757
758    /// Clears all peripheral memory blocks.
759    #[cfg(clear_crypto_secrets)]
760    fn clear_secrets(&self) {
761        self.zero_mem(self.k_mem());
762        self.zero_mem(self.px_mem());
763        self.zero_mem(self.py_mem());
764
765        #[cfg(ecc_separate_jacobian_point_memory)]
766        {
767            self.zero_mem(self.qx_mem());
768            self.zero_mem(self.qy_mem());
769            self.zero_mem(self.qz_mem());
770        }
771    }
772
773    #[cfg(clear_crypto_secrets)]
774    fn zero_mem(&self, mut word_ptr: *mut u32) {
775        for _ in 0..(MEM_BLOCK_SIZE / 4) {
776            unsafe { word_ptr.write_volatile(0) };
777            word_ptr = word_ptr.wrapping_add(1);
778        }
779    }
780
781    fn is_busy(&self) -> bool {
782        self.regs.mult_conf().read().start().bit_is_set()
783    }
784
785    fn start_operation(
786        &self,
787        mode: WorkMode,
788        curve: EllipticCurve,
789        #[cfg(ecc_has_modular_arithmetic)] mod_base: EccModBase,
790    ) {
791        let curve_variant;
792        for_each_ecc_curve! {
793            (all $(($_id:tt, $name:ident, $_bits:tt)),*) => {
794                curve_variant = match curve {
795                    $(EllipticCurve::$name => KEY_LENGTH::$name,)*
796                }
797            };
798        };
799        self.regs.mult_conf().modify(|_, w| unsafe {
800            w.work_mode().bits(mode as u8);
801            w.key_length().variant(curve_variant);
802
803            #[cfg(ecc_has_modular_arithmetic)]
804            w.mod_base().bit(mod_base as u8 == 1);
805
806            w.start().set_bit()
807        });
808    }
809}
810
811// Broken into separate macro invocations per item, to make the "Expand macro" LSP output more
812// readable
813
814for_each_ecc_working_mode! {
815    (all $(( $id:literal, $mode:tt )),*) => {
816        #[derive(Clone, Copy)]
817        #[doc(hidden)]
818        /// Represents the operational modes for elliptic curve or modular arithmetic
819        /// computations.
820        pub enum WorkMode {
821            $(
822                $mode = $id,
823            )*
824        }
825    };
826}
827
828// Result type for each operation
829for_each_ecc_working_mode! {
830    (all $(( $id:literal, $mode:tt )),*) => {
831        $(
832            result_type!($mode);
833        )*
834    };
835}
836
837// The main driver implementation
838for_each_ecc_working_mode! {
839    (all $(( $id:literal, $mode:tt )),*) => {
840        impl<'d, Dm: DriverMode> Ecc<'d, Dm> {
841            fn info(&self) -> Info {
842                Info { regs: ECC::regs() }
843            }
844
845            fn run_operation<'op, O: EccOperation>(
846                &'op mut self,
847                curve: EllipticCurve,
848                #[cfg(ecc_has_modular_arithmetic)] mod_base: EccModBase,
849            ) -> EccResultHandle<'op, O> {
850                self.info().start_operation(
851                    O::WORK_MODE,
852                    curve,
853                    #[cfg(ecc_has_modular_arithmetic)] mod_base,
854                );
855
856                // wait for interrupt
857                while self.info().is_busy() {}
858
859                EccResultHandle::new(curve, self)
860            }
861
862            /// Applies the given configuration to the ECC peripheral.
863            pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
864                self.info().apply_config(config)
865            }
866
867            /// Resets the ECC peripheral.
868            pub fn reset(&mut self) {
869                self.info().reset()
870            }
871
872            /// Registers an interrupt handler for the ECC peripheral.
873            ///
874            /// Replaces any previously registered interrupt handlers.
875            #[instability::unstable]
876            pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
877                for core in crate::system::Cpu::other() {
878                    crate::interrupt::disable(core, Interrupt::ECC);
879                }
880                crate::interrupt::bind_handler(Interrupt::ECC, handler);
881            }
882
883            $(
884                driver_method!($mode);
885            )*
886        }
887    };
888}
889
890/// Marks an ECC operation.
891pub trait EccOperation: Sealed {
892    /// Whether the operation verifies that the input point is on the curve.
893    const VERIFIES_POINT: bool;
894
895    /// Work mode
896    #[doc(hidden)]
897    const WORK_MODE: WorkMode;
898}
899
900/// Scalar result location.
901#[doc(hidden)]
902pub enum ScalarResultLocation {
903    /// The scalar value is stored in the `Px` memory location.
904    Px,
905    /// The scalar value is stored in the `Py` memory location.
906    Py,
907    /// The scalar value is stored in the `k` memory location.
908    K,
909}
910
911/// Marks operations that return a scalar value.
912pub trait OperationReturnsScalar: EccOperation {
913    /// Where the scalar value is stored.
914    #[doc(hidden)]
915    const LOCATION: ScalarResultLocation;
916}
917
918/// Marks operations that return a point in affine format.
919pub trait OperationReturnsAffinePoint: EccOperation {}
920
921/// Marks operations that return a point in Jacobian format.
922pub trait OperationReturnsJacobianPoint: EccOperation {}
923
924/// Marks operations that verify that the input point is on the curve.
925pub trait OperationVerifiesPoint: EccOperation {}
926
927/// The result of an ECC operation.
928///
929/// Used to read the result of an ECC operation. The available methods depend on
930/// the operation. An operation can compute multiple values, such as an affine point
931/// and a Jacobian point at the same time.
932#[must_use]
933pub struct EccResultHandle<'op, O>
934where
935    O: EccOperation,
936{
937    curve: EllipticCurve,
938    info: Info,
939    _marker: PhantomData<(&'op mut (), O)>,
940}
941
942impl<'op, O> EccResultHandle<'op, O>
943where
944    O: EccOperation,
945{
946    fn new<'d, Dm: DriverMode>(curve: EllipticCurve, driver: &'op mut Ecc<'d, Dm>) -> Self {
947        Self {
948            curve,
949            info: driver.info(),
950            _marker: PhantomData,
951        }
952    }
953
954    fn run_checks<const N: usize>(&self, params: [&[u8]; N]) -> Result<(), OperationError> {
955        self.curve.size_check(params)?;
956        if O::VERIFIES_POINT {
957            self.info.check_point_verification_result()?;
958        }
959        Ok(())
960    }
961
962    /// Returns whether the operation was successful.
963    ///
964    /// For operations that only perform point verification, this method returns whether the point
965    /// is on the curve. For operations that do not perform point verification, this method always
966    /// returns true.
967    pub fn success(&self) -> bool {
968        if O::VERIFIES_POINT {
969            self.info.check_point_verification_result().is_ok()
970        } else {
971            true
972        }
973    }
974
975    /// Retrieves the scalar result of the operation.
976    ///
977    /// # Errors
978    ///
979    /// [`OperationError`] when point verification failed, or when `out` is not the correct size.
980    pub fn read_scalar_result(&self, out: &mut [u8]) -> Result<(), OperationError>
981    where
982        O: OperationReturnsScalar,
983    {
984        self.run_checks([out])?;
985
986        match O::LOCATION {
987            ScalarResultLocation::Px => self.info.read_mem(self.info.px_mem(), out),
988            ScalarResultLocation::Py => self.info.read_mem(self.info.py_mem(), out),
989            ScalarResultLocation::K => self.info.read_mem(self.info.k_mem(), out),
990        }
991
992        Ok(())
993    }
994
995    /// Retrieves the affine point result of the operation.
996    ///
997    /// # Errors
998    ///
999    /// [`OperationError`] when point verification failed, or when `x` or `y` are not the correct
1000    /// size.
1001    pub fn read_affine_point_result(&self, x: &mut [u8], y: &mut [u8]) -> Result<(), OperationError>
1002    where
1003        O: OperationReturnsAffinePoint,
1004    {
1005        self.run_checks([x, y])?;
1006        self.info.read_point_result(x, y);
1007        Ok(())
1008    }
1009
1010    /// Retrieves the Jacobian point result of the operation.
1011    ///
1012    /// # Errors
1013    ///
1014    /// [`OperationError`] when point verification failed, or when `x`, `y`, or `z` are not the
1015    /// correct size.
1016    pub fn read_jacobian_point_result(
1017        &self,
1018        x: &mut [u8],
1019        y: &mut [u8],
1020        z: &mut [u8],
1021    ) -> Result<(), OperationError>
1022    where
1023        O: OperationReturnsJacobianPoint,
1024    {
1025        self.run_checks([x, y, z])?;
1026        self.info.read_jacobian_result(x, y, z);
1027        Ok(())
1028    }
1029}
1030
1031struct EccWorkItem {
1032    curve: EllipticCurve,
1033    operation: WorkMode,
1034    cancelled: bool,
1035    #[cfg(ecc_has_modular_arithmetic)]
1036    mod_base: EccModBase,
1037    inputs: MemoryPointers,
1038    point_verification_result: bool,
1039    outputs: MemoryPointers,
1040}
1041
1042#[derive(Default)]
1043struct MemoryPointers {
1044    // All of these pointers point to slices with curve-appropriate lengths.
1045    k: Option<NonNull<u8>>,
1046    px: Option<NonNull<u8>>,
1047    py: Option<NonNull<u8>>,
1048    #[cfg(ecc_separate_jacobian_point_memory)]
1049    qx: Option<NonNull<u8>>,
1050    #[cfg(ecc_separate_jacobian_point_memory)]
1051    qy: Option<NonNull<u8>>,
1052    #[cfg(ecc_separate_jacobian_point_memory)]
1053    qz: Option<NonNull<u8>>,
1054}
1055
1056impl MemoryPointers {
1057    fn set_scalar(&mut self, location: ScalarResultLocation, ptr: NonNull<[u8]>) {
1058        match location {
1059            ScalarResultLocation::Px => self.set_px(ptr),
1060            ScalarResultLocation::Py => self.set_py(ptr),
1061            ScalarResultLocation::K => self.set_k(ptr),
1062        }
1063    }
1064
1065    fn set_k(&mut self, ptr: NonNull<[u8]>) {
1066        self.k = Some(ptr.cast());
1067    }
1068
1069    fn set_px(&mut self, ptr: NonNull<[u8]>) {
1070        self.px = Some(ptr.cast());
1071    }
1072
1073    fn set_py(&mut self, ptr: NonNull<[u8]>) {
1074        self.py = Some(ptr.cast());
1075    }
1076
1077    fn set_qx(&mut self, ptr: NonNull<[u8]>) {
1078        cfg_select! {
1079            ecc_separate_jacobian_point_memory => {
1080                self.qx = Some(ptr.cast());
1081            }
1082            _ => {
1083                self.px = Some(ptr.cast());
1084            }
1085        }
1086    }
1087
1088    fn set_qy(&mut self, ptr: NonNull<[u8]>) {
1089        cfg_select! {
1090            ecc_separate_jacobian_point_memory => {
1091                self.qy = Some(ptr.cast());
1092            }
1093            _ => {
1094                self.py = Some(ptr.cast());
1095            }
1096        }
1097    }
1098
1099    fn set_qz(&mut self, ptr: NonNull<[u8]>) {
1100        cfg_select! {
1101            ecc_separate_jacobian_point_memory => {
1102                self.qz = Some(ptr.cast());
1103            }
1104            _ => {
1105                self.k = Some(ptr.cast());
1106            }
1107        }
1108    }
1109}
1110
1111// Safety: MemoryPointers is safe to share between threads, in the context of a WorkQueue. The
1112// WorkQueue ensures that only a single location can access the data. All the internals, except
1113// for the pointers, are Sync. The pointers are safe to share because they point at data that the
1114// ECC driver ensures can be accessed safely and soundly.
1115unsafe impl Sync for MemoryPointers {}
1116// Safety: we will not hold on to the pointers when the work item leaves the queue.
1117unsafe impl Send for MemoryPointers {}
1118
1119static ECC_WORK_QUEUE: WorkQueue<EccWorkItem> = WorkQueue::new();
1120
1121const ECC_VTABLE: VTable<EccWorkItem> = VTable {
1122    post: |driver, item| {
1123        let driver = unsafe { EccBackend::from_raw(driver) };
1124
1125        // Ensure driver is initialized
1126        if let DriverState::Uninitialized(ecc) = &driver.driver {
1127            // `EccBackend::new` checked the configuration.
1128            let mut ecc = unwrap!(Ecc::new(unsafe { ecc.clone_unchecked() }, driver.config));
1129            ecc.set_interrupt_handler(ecc_work_queue_handler);
1130            driver.driver = DriverState::Initialized(ecc);
1131        };
1132
1133        Some(driver.process(item))
1134    },
1135    poll: |driver, item| {
1136        let driver = unsafe { EccBackend::from_raw(driver) };
1137        driver.poll(item)
1138    },
1139    cancel: |driver, item| {
1140        let driver = unsafe { EccBackend::from_raw(driver) };
1141        driver.cancel(item);
1142    },
1143    stop: |driver| {
1144        let driver = unsafe { EccBackend::from_raw(driver) };
1145        driver.deinitialize()
1146    },
1147};
1148
1149enum DriverState<'d> {
1150    Uninitialized(ECC<'d>),
1151    Initialized(Ecc<'d, Blocking>),
1152}
1153
1154/// ECC processing backend.
1155///
1156/// Enables shared access to the device's ECC hardware using a work queue.
1157pub struct EccBackend<'d> {
1158    driver: DriverState<'d>,
1159    config: Config,
1160}
1161
1162impl<'d> EccBackend<'d> {
1163    /// Creates a new ECC backend, with the given configuration.
1164    ///
1165    /// The backend must be started with [`Self::start`] before it can execute ECC operations.
1166    pub fn new(ecc: ECC<'d>, config: Config) -> Result<Self, ConfigError> {
1167        check_config(&config)?;
1168
1169        Ok(Self {
1170            driver: DriverState::Uninitialized(ecc),
1171            config,
1172        })
1173    }
1174
1175    /// Registers the ECC driver to process ECC operations.
1176    ///
1177    /// The driver stops operating when the returned object is dropped.
1178    pub fn start(&mut self) -> EccWorkQueueDriver<'_, 'd> {
1179        EccWorkQueueDriver {
1180            inner: WorkQueueDriver::new(self, ECC_VTABLE, &ECC_WORK_QUEUE),
1181        }
1182    }
1183
1184    // WorkQueue callbacks. They may run in any context.
1185
1186    unsafe fn from_raw<'any>(ptr: NonNull<()>) -> &'any mut Self {
1187        unsafe { ptr.cast::<EccBackend<'_>>().as_mut() }
1188    }
1189
1190    fn process(&mut self, item: &mut EccWorkItem) -> Poll {
1191        let DriverState::Initialized(driver) = &mut self.driver else {
1192            unreachable!()
1193        };
1194
1195        let bytes = item.curve.size();
1196
1197        macro_rules! set_input {
1198            ($input:ident, $input_mem:ident) => {
1199                if let Some($input) = item.inputs.$input {
1200                    driver.info().write_mem(driver.info().$input_mem(), unsafe {
1201                        core::slice::from_raw_parts($input.as_ptr(), bytes)
1202                    });
1203                }
1204            };
1205        }
1206
1207        set_input!(k, k_mem);
1208        set_input!(px, px_mem);
1209        set_input!(py, py_mem);
1210
1211        #[cfg(ecc_separate_jacobian_point_memory)]
1212        {
1213            set_input!(qx, qx_mem);
1214            set_input!(qy, qy_mem);
1215            set_input!(qz, qz_mem);
1216        }
1217
1218        driver.info().start_operation(
1219            item.operation,
1220            item.curve,
1221            #[cfg(ecc_has_modular_arithmetic)]
1222            item.mod_base,
1223        );
1224        Poll::Pending(false)
1225    }
1226
1227    fn poll(&mut self, item: &mut EccWorkItem) -> Poll {
1228        let DriverState::Initialized(driver) = &mut self.driver else {
1229            unreachable!()
1230        };
1231
1232        if driver.info().is_busy() {
1233            return Poll::Pending(false);
1234        }
1235        if item.cancelled {
1236            return Poll::Ready(Status::Cancelled);
1237        }
1238
1239        let bytes = item.curve.size();
1240
1241        macro_rules! read_output {
1242            ($output:ident, $output_mem:ident) => {
1243                if let Some($output) = item.outputs.$output {
1244                    driver.info().read_mem(driver.info().$output_mem(), unsafe {
1245                        core::slice::from_raw_parts_mut($output.as_ptr(), bytes)
1246                    });
1247                }
1248            };
1249        }
1250
1251        read_output!(k, k_mem);
1252        read_output!(px, px_mem);
1253        read_output!(py, py_mem);
1254
1255        #[cfg(ecc_separate_jacobian_point_memory)]
1256        {
1257            read_output!(qx, qx_mem);
1258            read_output!(qy, qy_mem);
1259            read_output!(qz, qz_mem);
1260        }
1261
1262        item.point_verification_result = driver.info().check_point_verification_result().is_ok();
1263
1264        #[cfg(clear_crypto_secrets)]
1265        driver.info().clear_secrets();
1266
1267        Poll::Ready(Status::Completed)
1268    }
1269
1270    fn cancel(&mut self, item: &mut EccWorkItem) {
1271        let DriverState::Initialized(driver) = &mut self.driver else {
1272            unreachable!()
1273        };
1274        driver.reset();
1275
1276        // The operands may have already been written to the peripheral.
1277        #[cfg(clear_crypto_secrets)]
1278        driver.info().clear_secrets();
1279
1280        item.cancelled = true;
1281    }
1282
1283    fn deinitialize(&mut self) {
1284        if let DriverState::Initialized(ref ecc) = self.driver {
1285            self.driver = DriverState::Uninitialized(unsafe { ecc._ecc.clone_unchecked() });
1286        }
1287    }
1288}
1289
1290/// An active work queue driver.
1291///
1292/// This object must be kept around, otherwise ECC operations will never complete.
1293pub struct EccWorkQueueDriver<'t, 'd> {
1294    inner: WorkQueueDriver<'t, EccBackend<'d>, EccWorkItem>,
1295}
1296
1297impl<'t, 'd> EccWorkQueueDriver<'t, 'd> {
1298    /// Finishes processing the current work queue item, then stops the driver.
1299    pub fn stop(self) -> impl Future<Output = ()> {
1300        self.inner.stop()
1301    }
1302}
1303
1304#[crate::ram]
1305#[crate::handler]
1306fn ecc_work_queue_handler() {
1307    if !ECC_WORK_QUEUE.process() {
1308        // The queue may indicate that it needs to be polled again. In this case, we do not clear
1309        // the interrupt bit, which causes the interrupt to be re-handled.
1310        cfg_select! {
1311            any(esp32c5, esp32c61) => {
1312                let reg = ECC::regs().int_clr();
1313            }
1314            _ => {
1315                let reg = ECC::regs().mult_int_clr();
1316            }
1317        }
1318        reg.write(|w| w.calc_done().clear_bit_by_one());
1319    }
1320}
1321
1322/// An ECC operation that can be enqueued on the work queue.
1323pub struct EccBackendOperation<'op, O: EccOperation> {
1324    frontend: WorkQueueFrontend<EccWorkItem>,
1325    _marker: PhantomData<(&'op mut (), O)>,
1326}
1327
1328impl<'op, O: EccOperation> EccBackendOperation<'op, O> {
1329    fn new(work_item: EccWorkItem) -> Self {
1330        Self {
1331            frontend: WorkQueueFrontend::new(work_item),
1332            _marker: PhantomData,
1333        }
1334    }
1335
1336    /// Designate a buffer for the scalar result of the operation.
1337    ///
1338    /// Once the operation is processed, the result can be retrieved from the designated buffer.
1339    ///
1340    /// # Errors
1341    ///
1342    /// [`OperationError::ParameterLengthMismatch`] when `out` is not the correct size.
1343    pub fn with_scalar_result(mut self, out: &'op mut [u8]) -> Result<Self, OperationError>
1344    where
1345        O: OperationReturnsScalar,
1346    {
1347        self.frontend.data().curve.size_check([out])?;
1348
1349        self.frontend
1350            .data_mut()
1351            .outputs
1352            .set_scalar(O::LOCATION, NonNull::from(out));
1353
1354        Ok(self)
1355    }
1356
1357    /// Designate buffers for the affine point result of the operation.
1358    ///
1359    /// Once the operation is processed, the result can be retrieved from the designated buffers.
1360    ///
1361    /// # Errors
1362    ///
1363    /// [`OperationError::ParameterLengthMismatch`] when `x` or `y` are not the correct size.
1364    pub fn with_affine_point_result(
1365        mut self,
1366        px: &'op mut [u8],
1367        py: &'op mut [u8],
1368    ) -> Result<Self, OperationError>
1369    where
1370        O: OperationReturnsAffinePoint,
1371    {
1372        self.frontend.data().curve.size_check([px, py])?;
1373
1374        self.frontend.data_mut().outputs.set_px(NonNull::from(px));
1375        self.frontend.data_mut().outputs.set_py(NonNull::from(py));
1376
1377        Ok(self)
1378    }
1379
1380    /// Designate buffers for the Jacobian point result of the operation.
1381    ///
1382    /// Once the operation is processed, the result can be retrieved from the designated buffers.
1383    ///
1384    /// # Errors
1385    ///
1386    /// [`OperationError::ParameterLengthMismatch`] when `x`, `y`, or `z` are not the correct size.
1387    pub fn with_jacobian_point_result(
1388        mut self,
1389        qx: &'op mut [u8],
1390        qy: &'op mut [u8],
1391        qz: &'op mut [u8],
1392    ) -> Result<Self, OperationError>
1393    where
1394        O: OperationReturnsJacobianPoint,
1395    {
1396        self.frontend.data().curve.size_check([qx, qy, qz])?;
1397
1398        self.frontend.data_mut().outputs.set_qx(NonNull::from(qx));
1399        self.frontend.data_mut().outputs.set_qy(NonNull::from(qy));
1400        self.frontend.data_mut().outputs.set_qz(NonNull::from(qz));
1401
1402        Ok(self)
1403    }
1404
1405    /// Returns whether the input point is on the curve.
1406    ///
1407    /// The operation must be processed before this method returns a meaningful value.
1408    pub fn point_on_curve(&self) -> bool
1409    where
1410        O: OperationVerifiesPoint,
1411    {
1412        self.frontend.data().point_verification_result
1413    }
1414
1415    /// Starts processing the operation.
1416    ///
1417    /// The returned [`EccHandle`] must be polled to completion before the operation is considered
1418    /// complete.
1419    pub fn process(&mut self) -> EccHandle<'_> {
1420        EccHandle(self.frontend.post(&ECC_WORK_QUEUE))
1421    }
1422}
1423
1424/// A handle for an in-progress operation.
1425#[must_use]
1426pub struct EccHandle<'t>(Handle<'t, EccWorkItem>);
1427
1428impl EccHandle<'_> {
1429    /// Polls the status of the work item.
1430    ///
1431    /// Returns whether the item has been processed.
1432    #[inline]
1433    pub fn poll(&mut self) -> bool {
1434        self.0.poll()
1435    }
1436
1437    /// Polls the work item to completion, by busy-looping.
1438    ///
1439    /// Returns immediately if `poll` returns `true`.
1440    #[inline]
1441    pub fn wait_blocking(self) -> Status {
1442        self.0.wait_blocking()
1443    }
1444
1445    /// Waits until the work item is completed.
1446    #[inline]
1447    pub fn wait(&mut self) -> impl Future<Output = Status> {
1448        self.0.wait()
1449    }
1450
1451    /// Cancels the work item and asynchronously waits until it is removed from the work queue.
1452    #[inline]
1453    pub fn cancel(&mut self) -> impl Future<Output = ()> {
1454        self.0.cancel()
1455    }
1456}