Implement async RNG, including rand_core sync traits.

This commit is contained in:
Bob McWhirter 2021-05-06 14:33:29 -04:00
parent 1eb70a7e5d
commit e8537ca9c2
10 changed files with 3449 additions and 3332 deletions

View File

@ -1,8 +1,5 @@
[target.'cfg(all(target_arch = "arm", target_os = "none"))'] [target.'cfg(all(target_arch = "arm", target_os = "none"))']
#runner = "probe-run --chip STM32F401CCUx" runner = "probe-run --chip STM32F401CCUx"
#runner = "probe-run --chip STM32L4S5VITx"
#runner = "probe-run --chip ${PROBE_RUN_CHIP}"
runner = "probe-run"
rustflags = [ rustflags = [
# LLD (shipped with the Rust toolchain) is used as the default linker # LLD (shipped with the Rust toolchain) is used as the default linker
@ -28,5 +25,4 @@ rustflags = [
] ]
[build] [build]
#target = "thumbv7em-none-eabihf" target = "thumbv7em-none-eabihf"
target = "thumbv7em-none-eabi"

View File

@ -18,11 +18,9 @@ defmt-error = []
[dependencies] [dependencies]
embassy = { version = "0.1.0", path = "../embassy", features = ["defmt", "defmt-trace"] } embassy = { version = "0.1.0", path = "../embassy", features = ["defmt", "defmt-trace"] }
embassy-traits = { version = "0.1.0", path = "../embassy-traits", features = ["defmt"] } embassy-traits = { version = "0.1.0", path = "../embassy-traits", features = ["defmt"] }
#embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32", features = ["defmt", "defmt-trace", "stm32f429zi"] } embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32", features = ["defmt", "defmt-trace", "stm32f429zi"] }
embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32", features = ["defmt", "defmt-trace", "stm32l4s5vi"] }
embassy-extras = {version = "0.1.0", path = "../embassy-extras" } embassy-extras = {version = "0.1.0", path = "../embassy-extras" }
#stm32f4 = { version = "0.13", features = ["stm32f429"] } stm32f4 = { version = "0.13", features = ["stm32f429"] }
stm32l4 = { version = "0.13", features = ["stm32l4x5" ] }
defmt = "0.2.0" defmt = "0.2.0"
defmt-rtt = "0.2.0" defmt-rtt = "0.2.0"

View File

@ -12,8 +12,7 @@ use embedded_hal::digital::v2::OutputPin;
use example_common::*; use example_common::*;
use cortex_m_rt::entry; use cortex_m_rt::entry;
//use stm32f4::stm32f429 as pac; use stm32f4::stm32f429 as pac;
use stm32l4::stm32l4x5 as pac;
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
@ -26,21 +25,21 @@ fn main() -> ! {
w.dbg_standby().set_bit(); w.dbg_standby().set_bit();
w.dbg_stop().set_bit() w.dbg_stop().set_bit()
}); });
pp.RCC.ahb1enr.modify(|_, w| w.dma1en().set_bit()); pp.RCC.ahb1enr.modify(|_, w| w.dma1en().enabled());
pp.RCC.ahb2enr.modify(|_, w| { pp.RCC.ahb1enr.modify(|_, w| {
w.gpioaen().set_bit(); w.gpioaen().enabled();
w.gpioben().set_bit(); w.gpioben().enabled();
w.gpiocen().set_bit(); w.gpiocen().enabled();
w.gpioden().set_bit(); w.gpioden().enabled();
w.gpioeen().set_bit(); w.gpioeen().enabled();
w.gpiofen().set_bit(); w.gpiofen().enabled();
w w
}); });
let p = embassy_stm32::init(Default::default()); let p = embassy_stm32::init(Default::default());
let mut led = Output::new(p.PA5, Level::High); let mut led = Output::new(p.PB7, Level::High);
loop { loop {
info!("high"); info!("high");

View File

@ -16,8 +16,7 @@ use embassy_traits::gpio::{WaitForFallingEdge, WaitForRisingEdge};
use example_common::*; use example_common::*;
use cortex_m_rt::entry; use cortex_m_rt::entry;
//use stm32f4::stm32f429 as pac; use stm32f4::stm32f429 as pac;
use stm32l4::stm32l4x5 as pac;
#[embassy::task] #[embassy::task]
async fn main_task() { async fn main_task() {
@ -57,20 +56,19 @@ fn main() -> ! {
w.dbg_standby().set_bit(); w.dbg_standby().set_bit();
w.dbg_stop().set_bit() w.dbg_stop().set_bit()
}); });
pp.RCC.ahb1enr.modify(|_, w| w.dma1en().enabled());
pp.RCC.ahb1enr.modify(|_, w| w.dma1en().set_bit()); pp.RCC.ahb1enr.modify(|_, w| {
w.gpioaen().enabled();
pp.RCC.ahb2enr.modify(|_, w| { w.gpioben().enabled();
w.gpioaen().set_bit(); w.gpiocen().enabled();
w.gpioben().set_bit(); w.gpioden().enabled();
w.gpiocen().set_bit(); w.gpioeen().enabled();
w.gpioden().set_bit(); w.gpiofen().enabled();
w.gpioeen().set_bit();
w.gpiofen().set_bit();
w w
}); });
pp.RCC.apb2enr.modify(|_, w| { pp.RCC.apb2enr.modify(|_, w| {
w.syscfgen().set_bit(); w.syscfgen().enabled();
w w
}); });

View File

@ -15,6 +15,7 @@ cortex-m-rt = { version = "0.6.13", features = ["device"] }
cortex-m = "0.7.1" cortex-m = "0.7.1"
embedded-hal = { version = "0.2.4" } embedded-hal = { version = "0.2.4" }
futures = { version = "0.3.5", default-features = false, features = ["async-await"] } futures = { version = "0.3.5", default-features = false, features = ["async-await"] }
rand_core = { version = "0.6.2", optional=true}
[build-dependencies] [build-dependencies]
regex = "1.4.6" regex = "1.4.6"
@ -321,7 +322,7 @@ _exti = []
_exti_v1 = [] _exti_v1 = []
_gpio = [] _gpio = []
_gpio_v2 = [] _gpio_v2 = []
_rng = [] _rng = [ "rand_core",]
_rng_v1 = [] _rng_v1 = []
_stm32f4 = [] _stm32f4 = []
_stm32l4 = [] _stm32l4 = []

View File

@ -201,6 +201,9 @@ for chip in chips.values():
# ========= Update Cargo features # ========= Update Cargo features
feature_optional_deps = {}
feature_optional_deps['_rng'] = ['rand_core']
features = {} features = {}
extra_features = set() extra_features = set()
for name, chip in chips.items(): for name, chip in chips.items():
@ -208,6 +211,9 @@ for name, chip in chips.items():
for feature in chip['features']: for feature in chip['features']:
extra_features.add(feature) extra_features.add(feature)
for feature in sorted(list(extra_features)): for feature in sorted(list(extra_features)):
if feature in feature_optional_deps:
features[feature] = feature_optional_deps[feature]
else:
features[feature] = [] features[feature] = []
SEPARATOR_START = '# BEGIN GENERATED FEATURES\n' SEPARATOR_START = '# BEGIN GENERATED FEATURES\n'

View File

@ -15,6 +15,7 @@ pub mod exti;
pub mod gpio; pub mod gpio;
#[cfg(feature = "_rng")] #[cfg(feature = "_rng")]
pub mod rng; pub mod rng;
#[cfg(feature = "_usart")]
pub mod usart; pub mod usart;
// This must go LAST so that it sees the `impl_foo!` macros // This must go LAST so that it sees the `impl_foo!` macros

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,25 @@
#![macro_use] #![macro_use]
use crate::pac::rng::{regs, Rng};
//use crate::pac::rng::{regs, Rng};
use crate::pac;
use crate::peripherals; use crate::peripherals;
use embassy::util::Unborrow; use crate::interrupt;
use embassy::util::{Unborrow, AtomicWaker};
use embassy_extras::unborrow; use embassy_extras::unborrow;
use rand_core::{RngCore, CryptoRng};
use defmt::*;
static RNG_WAKER: AtomicWaker = AtomicWaker::new();
#[interrupt]
unsafe fn RNG() {
let bits = crate::pac::RNG.sr().read();
if bits.drdy() || bits.seis() || bits.ceis() {
crate::pac::RNG.cr().write(|reg| reg.set_ie(false));
RNG_WAKER.wake();
}
}
pub struct Random<T: Instance> { pub struct Random<T: Instance> {
inner: T, inner: T,
@ -15,17 +32,118 @@ impl<T: Instance> Random<T> {
} }
} }
impl<T: Instance> RngCore for Random<T> {
fn next_u32(&mut self) -> u32 {
loop {
let bits = unsafe { T::regs().sr().read() };
if bits.drdy() {
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> {
self.fill_bytes( dest );
Ok(())
}
}
impl<T: Instance> CryptoRng for Random<T> { }
use core::future::Future; use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use embassy::traits::rng::Rng as RngTrait; use embassy::traits;
use core::task::{Poll, Context};
use core::pin::Pin;
impl<T: Instance> RngTrait for Random<T> { struct RngInterruptFuture<T: Instance> {
type Error = (); _marker: PhantomData<T>,
#[rustfmt::skip] }
impl<T: Instance> Future for RngInterruptFuture<T> {
type Output = Result<(), Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
RNG_WAKER.register(cx.waker());
let bits = unsafe { T::regs().sr().read() };
if bits.drdy() {
return Poll::Ready(Ok(()));
} else if bits.seis() {
unsafe {
T::regs().sr().modify(|reg| {
reg.set_seis(false);
});
}
} else if bits.ceis() {
unsafe {
T::regs().sr().modify(|reg| {
reg.set_ceis(false);
});
}
}
Poll::Pending
}
}
impl<T: Instance> RngInterruptFuture<T> {
async fn new() -> Result<(), Error> {
unsafe {
T::regs().cr().modify(|reg| {
reg.set_ie(true);
//reg.set_rngen(true);
});
}
Self {
_marker: PhantomData
}.await
}
}
pub enum Error {
SeedError,
ClockError,
}
impl<T: Instance> traits::rng::Rng for Random<T> {
type Error = Error;
type RngFuture<'a> where Self: 'a = impl Future<Output=Result<(), Self::Error>>; type RngFuture<'a> where Self: 'a = impl Future<Output=Result<(), Self::Error>>;
fn fill<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a> { fn fill_bytes<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a> {
async move { Ok(()) } unsafe {
T::regs().cr().modify(|reg| {
reg.set_rngen(true);
});
}
async move {
for chunk in dest.chunks_mut(4) {
RngInterruptFuture::<T>::new().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(())
}
} }
} }
@ -33,20 +151,20 @@ pub(crate) mod sealed {
use super::*; use super::*;
pub trait Instance { pub trait Instance {
fn regs(&self) -> Rng; fn regs() -> pac::rng::Rng;
} }
} }
pub trait Instance: sealed::Instance {} pub trait Instance: sealed::Instance {}
macro_rules! impl_rng { macro_rules! impl_rng {
($inst:ident) => { ($addr:ident) => {
impl crate::rng::sealed::Instance for peripherals::$inst { impl crate::rng::sealed::Instance for peripherals::RNG {
fn regs(&self) -> crate::pac::rng::Rng { fn regs() -> crate::pac::chip::rng::Rng {
crate::pac::$inst crate::pac::RNG
} }
} }
impl crate::rng::Instance for peripherals::$inst {} impl crate::rng::Instance for peripherals::RNG {}
}; };
} }

View File

@ -13,5 +13,5 @@ pub trait Rng {
/// May result in delays if entropy is exhausted prior to completely /// May result in delays if entropy is exhausted prior to completely
/// filling the buffer. Upon completion, the buffer will be completely /// filling the buffer. Upon completion, the buffer will be completely
/// filled or an error will have been reported. /// filled or an error will have been reported.
fn fill<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a>; fn fill_bytes<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a>;
} }