1#![macro_use]
3
4use core::future::poll_fn;
5use core::marker::PhantomData;
6use core::num::NonZeroU32;
7use core::task::Poll;
8
9use embassy_sync::waitqueue::AtomicWaker;
10use rand_core::{CryptoRng, RngCore};
11
12use crate::internal::drop::OnDrop;
13use crate::interrupt::typelevel::Interrupt;
14use crate::{interrupt, pac, peripherals, Peri};
15
16static RNG_WAKER: AtomicWaker = AtomicWaker::new();
17
18#[derive(Debug, Copy, Clone, PartialEq, Eq)]
20#[cfg_attr(feature = "defmt", derive(defmt::Format))]
21pub enum Error {
22 SeedError,
24 ClockError,
26}
27
28impl From<Error> for rand_core::Error {
29 fn from(error: Error) -> Self {
30 let code = match error {
31 Error::SeedError => 0,
32 Error::ClockError => 1,
33 };
34 NonZeroU32::new(rand_core::Error::CUSTOM_START + code).unwrap().into()
35 }
36}
37
38fn ready_or_error(status: &pac::rng::regs::Sr) -> bool {
39 status.drdy() || status.secs() || status.seis() || status.cecs() || status.ceis()
40}
41
42pub struct InterruptHandler<T: Instance> {
44 _phantom: PhantomData<T>,
45}
46
47impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
48 unsafe fn on_interrupt() {
49 if ready_or_error(&T::regs().sr().read()) {
50 T::regs().cr().modify(|reg| reg.set_ie(false));
51 RNG_WAKER.wake();
52 }
53 }
54}
55
56pub struct Rng<'d, T: Instance> {
58 _inner: Peri<'d, T>,
59 discard_first: bool,
60}
61
62impl<'d, T: Instance> Rng<'d, T> {
63 pub fn new(
65 inner: Peri<'d, T>,
66 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
67 ) -> Self {
68 #[cfg(ch32v4)]
69 assert!(
70 crate::rcc::rng_source_frequency().is_some(),
71 "RNG source clock is not ready"
72 );
73 T::enable_and_reset();
74 let mut random = Self {
75 _inner: inner,
76 discard_first: true,
77 };
78 random.reset();
79 T::Interrupt::unpend();
80 unsafe { T::Interrupt::enable() };
81 random
82 }
83
84 pub fn reset(&mut self) {
88 T::regs().cr().write(|reg| reg.set_rngen(false));
89 T::regs().sr().write_value(pac::rng::regs::Sr(0));
90 self.discard_first = true;
91 T::regs().cr().modify(|reg| reg.set_rngen(true));
92 }
93
94 pub fn recover_seed_error(&mut self) {
96 self.reset();
97 }
98
99 fn check_status(&mut self, status: &pac::rng::regs::Sr) -> Result<(), Error> {
100 if status.seis() || status.secs() {
101 self.reset();
102 return Err(Error::SeedError);
103 }
104 if status.ceis() || status.cecs() {
105 T::regs().sr().modify(|reg| reg.set_ceis(false));
108 return Err(Error::ClockError);
109 }
110 Ok(())
111 }
112
113 pub fn try_next_u32(&mut self) -> Result<Option<u32>, Error> {
115 let status = T::regs().sr().read();
116 self.check_status(&status)?;
117 if !status.drdy() {
118 return Ok(None);
119 }
120 let value = T::regs().dr().read();
121 self.check_status(&T::regs().sr().read())?;
122 if self.discard_first {
123 self.discard_first = false;
124 return Ok(None);
125 }
126 Ok(Some(value))
127 }
128
129 pub fn blocking_next_u32(&mut self) -> Result<u32, Error> {
131 loop {
132 if let Some(value) = self.try_next_u32()? {
133 return Ok(value);
134 }
135 }
136 }
137
138 pub async fn async_next_u32(&mut self) -> Result<u32, Error> {
140 let _cleanup = OnDrop::new(|| T::regs().cr().modify(|reg| reg.set_ie(false)));
141 poll_fn(|context| {
142 RNG_WAKER.register(context.waker());
143 match self.try_next_u32() {
144 Ok(Some(value)) => return Poll::Ready(Ok(value)),
145 Err(error) => return Poll::Ready(Err(error)),
146 Ok(None) => {}
147 }
148 T::regs().cr().modify(|reg| reg.set_ie(true));
149 match self.try_next_u32() {
150 Ok(Some(value)) => Poll::Ready(Ok(value)),
151 Err(error) => Poll::Ready(Err(error)),
152 Ok(None) => Poll::Pending,
153 }
154 })
155 .await
156 }
157
158 pub async fn async_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
162 for chunk in dest.chunks_mut(4) {
163 let word = self.async_next_u32().await?;
164 chunk.copy_from_slice(&word.to_le_bytes()[..chunk.len()]);
165 }
166 Ok(())
167 }
168}
169
170impl<'d, T: Instance> Drop for Rng<'d, T> {
171 fn drop(&mut self) {
172 T::regs().cr().write(|reg| {
173 reg.set_ie(false);
174 reg.set_rngen(false);
175 });
176 T::Interrupt::disable();
177 T::disable();
178 }
179}
180
181impl<'d, T: Instance> RngCore for Rng<'d, T> {
182 fn next_u32(&mut self) -> u32 {
183 loop {
184 match self.blocking_next_u32() {
185 Ok(value) => return value,
186 Err(Error::SeedError) => {}
190 Err(Error::ClockError) => panic!("RNG clock error"),
191 }
192 }
193 }
194
195 fn next_u64(&mut self) -> u64 {
196 u64::from(self.next_u32()) | (u64::from(self.next_u32()) << 32)
197 }
198
199 fn fill_bytes(&mut self, dest: &mut [u8]) {
200 for chunk in dest.chunks_mut(4) {
201 let word = self.next_u32();
202 chunk.copy_from_slice(&word.to_le_bytes()[..chunk.len()]);
203 }
204 }
205
206 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
207 for chunk in dest.chunks_mut(4) {
208 let word = self.blocking_next_u32()?;
209 chunk.copy_from_slice(&word.to_le_bytes()[..chunk.len()]);
210 }
211 Ok(())
212 }
213}
214
215impl<'d, T: Instance> CryptoRng for Rng<'d, T> {}
216
217trait SealedInstance {
218 fn regs() -> pac::rng::Rng;
219}
220
221#[allow(private_bounds)]
223pub trait Instance:
224 SealedInstance + embassy_hal_internal::PeripheralType + crate::peripheral::RccPeripheral + 'static + Send
225{
226 type Interrupt: interrupt::typelevel::Interrupt;
228}
229
230foreach_peripheral!(
231 (rng, $inst:ident) => {
232 impl Instance for peripherals::$inst {
233 type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
234 }
235
236 impl SealedInstance for peripherals::$inst {
237 fn regs() -> crate::pac::rng::Rng { crate::pac::$inst }
238 }
239 };
240);