embassy/embassy-stm32/src/rng.rs

211 lines
5.3 KiB
Rust
Raw Normal View History

#![macro_use]
2021-05-10 01:19:07 +02:00
use core::future::Future;
use core::task::Poll;
use embassy::traits;
use embassy::util::{AtomicWaker, Unborrow};
use embassy_hal_common::unborrow;
2021-05-10 01:19:07 +02:00
use futures::future::poll_fn;
use rand_core::{CryptoRng, RngCore};
2021-05-10 01:19:07 +02:00
use crate::pac;
use crate::peripherals;
pub(crate) static RNG_WAKER: AtomicWaker = AtomicWaker::new();
2021-04-26 20:11:46 +02:00
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
SeedError,
ClockError,
}
2021-04-26 20:11:46 +02:00
pub struct Random<T: Instance> {
2021-05-11 06:34:10 +02:00
_inner: T,
2021-04-26 20:11:46 +02:00
}
impl<T: Instance> Random<T> {
2021-05-10 01:19:07 +02:00
pub fn new(inner: impl Unborrow<Target = T>) -> Self {
2021-06-09 13:54:53 +02:00
T::enable();
T::reset();
2021-04-26 20:11:46 +02:00
unborrow!(inner);
2021-05-11 06:34:10 +02:00
let mut random = Self { _inner: inner };
random.reset();
random
}
pub fn reset(&mut self) {
unsafe {
T::regs().cr().modify(|reg| {
reg.set_rngen(true);
reg.set_ie(true);
});
T::regs().sr().modify(|reg| {
reg.set_seis(false);
reg.set_ceis(false);
});
}
// Reference manual says to discard the first.
let _ = self.next_u32();
2021-04-26 20:11:46 +02:00
}
}
impl<T: Instance> RngCore for Random<T> {
fn next_u32(&mut self) -> u32 {
loop {
let bits = unsafe { T::regs().sr().read() };
if bits.drdy() {
2021-05-10 01:19:07 +02:00
return unsafe { T::regs().dr().read() };
}
}
}
fn next_u64(&mut self) -> u64 {
let mut rand = self.next_u32() as u64;
rand |= (self.next_u32() as u64) << 32;
rand
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
for chunk in dest.chunks_mut(4) {
let rand = self.next_u32();
for (slot, num) in chunk.iter_mut().zip(rand.to_be_bytes().iter()) {
*slot = *num
}
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
2021-05-10 01:19:07 +02:00
self.fill_bytes(dest);
Ok(())
}
}
2021-05-10 01:19:07 +02:00
impl<T: Instance> CryptoRng for Random<T> {}
impl<T: Instance> traits::rng::Rng for Random<T> {
type Error = Error;
2021-05-10 01:19:07 +02:00
#[rustfmt::skip]
type RngFuture<'a> where Self: 'a = impl Future<Output=Result<(), Self::Error>> + 'a;
fn fill_bytes<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a> {
unsafe {
T::regs().cr().modify(|reg| {
reg.set_rngen(true);
});
}
async move {
for chunk in dest.chunks_mut(4) {
poll_fn(|cx| {
RNG_WAKER.register(cx.waker());
unsafe {
T::regs().cr().modify(|reg| {
reg.set_ie(true);
});
}
let bits = unsafe { T::regs().sr().read() };
if bits.drdy() {
Poll::Ready(Ok(()))
} else if bits.seis() {
self.reset();
Poll::Ready(Err(Error::SeedError))
} else if bits.ceis() {
self.reset();
Poll::Ready(Err(Error::ClockError))
} else {
Poll::Pending
}
2021-05-10 01:19:07 +02:00
})
.await?;
let random_bytes = unsafe { T::regs().dr().read() }.to_be_bytes();
for (dest, src) in chunk.iter_mut().zip(random_bytes.iter()) {
*dest = *src
}
}
Ok(())
}
2021-04-26 20:11:46 +02:00
}
2021-08-27 22:10:01 +02:00
#[rustfmt::skip]
type NextFuture<'a> where Self: 'a = impl Future<Output=Result<u32, Self::Error>> + 'a;
fn next<'a>(&'a mut self, range: u32) -> Self::NextFuture<'a> {
async move {
let t = (-(range as i32) % (range as i32)) as u32;
loop {
let mut buf = [0; 4];
traits::rng::Rng::fill_bytes(self, &mut buf).await?;
let x = u32::from_le_bytes(buf);
let m = x as u64 * range as u64;
let l = m as u32;
if l < t {
continue;
}
return Ok((m >> 32) as u32);
}
}
}
2021-04-26 20:11:46 +02:00
}
pub(crate) mod sealed {
use super::*;
pub trait Instance {
fn regs() -> pac::rng::Rng;
2021-04-26 20:11:46 +02:00
}
}
2021-06-09 13:54:53 +02:00
pub trait Instance: sealed::Instance + crate::rcc::RccPeripheral {}
2021-04-26 20:11:46 +02:00
crate::pac::peripherals!(
(rng, $inst:ident) => {
impl Instance for peripherals::$inst {}
impl sealed::Instance for peripherals::$inst {
fn regs() -> crate::pac::rng::Rng {
crate::pac::RNG
}
}
};
);
macro_rules! irq {
($irq:ident) => {
mod rng_irq {
use crate::interrupt;
#[interrupt]
unsafe fn $irq() {
let bits = $crate::pac::RNG.sr().read();
if bits.drdy() || bits.seis() || bits.ceis() {
$crate::pac::RNG.cr().write(|reg| reg.set_ie(false));
$crate::rng::RNG_WAKER.wake();
}
}
}
};
}
crate::pac::interrupts!(
(RNG) => {
irq!(RNG);
};
(RNG_LPUART1) => {
irq!(RNG_LPUART1);
};
(AES_RNG_LPUART1) => {
irq!(AES_RNG_LPUART1);
};
(AES_RNG) => {
irq!(AES_RNG);
};
(HASH_RNG) => {
irq!(HASH_RNG);
};
);