-
Notifications
You must be signed in to change notification settings - Fork 615
/
rng.rs
273 lines (228 loc) · 7.74 KB
/
rng.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! Random Number Generator (RNG) driver.
#![macro_use]
use core::cell::{RefCell, RefMut};
use core::future::poll_fn;
use core::marker::PhantomData;
use core::ptr;
use core::task::Poll;
use critical_section::{CriticalSection, Mutex};
use embassy_hal_internal::drop::OnDrop;
use embassy_hal_internal::{into_ref, PeripheralRef};
use embassy_sync::waitqueue::WakerRegistration;
use crate::interrupt::typelevel::Interrupt;
use crate::{interrupt, Peripheral};
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
let r = T::regs();
// Clear the event.
r.events_valrdy.reset();
// Mutate the slice within a critical section,
// so that the future isn't dropped in between us loading the pointer and actually dereferencing it.
critical_section::with(|cs| {
let mut state = T::state().borrow_mut(cs);
// We need to make sure we haven't already filled the whole slice,
// in case the interrupt fired again before the executor got back to the future.
if !state.ptr.is_null() && state.ptr != state.end {
// If the future was dropped, the pointer would have been set to null,
// so we're still good to mutate the slice.
// The safety contract of `Rng::new` means that the future can't have been dropped
// without calling its destructor.
unsafe {
*state.ptr = r.value.read().value().bits();
state.ptr = state.ptr.add(1);
}
if state.ptr == state.end {
state.waker.wake();
}
}
});
}
}
/// A wrapper around an nRF RNG peripheral.
///
/// It has a non-blocking API, and a blocking api through `rand`.
pub struct Rng<'d, T: Instance> {
_peri: PeripheralRef<'d, T>,
}
impl<'d, T: Instance> Rng<'d, T> {
/// Creates a new RNG driver from the `RNG` peripheral and interrupt.
///
/// SAFETY: The future returned from `fill_bytes` must not have its lifetime end without running its destructor,
/// e.g. using `mem::forget`.
///
/// The synchronous API is safe.
pub fn new(
rng: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
) -> Self {
into_ref!(rng);
let this = Self { _peri: rng };
this.stop();
this.disable_irq();
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
this
}
fn stop(&self) {
T::regs().tasks_stop.write(|w| unsafe { w.bits(1) })
}
fn start(&self) {
T::regs().tasks_start.write(|w| unsafe { w.bits(1) })
}
fn enable_irq(&self) {
T::regs().intenset.write(|w| w.valrdy().set());
}
fn disable_irq(&self) {
T::regs().intenclr.write(|w| w.valrdy().clear());
}
/// Enable or disable the RNG's bias correction.
///
/// Bias correction removes any bias towards a '1' or a '0' in the bits generated.
/// However, this makes the generation of numbers slower.
///
/// Defaults to disabled.
pub fn set_bias_correction(&self, enable: bool) {
T::regs().config.write(|w| w.dercen().bit(enable))
}
/// Fill the buffer with random bytes.
pub async fn fill_bytes(&mut self, dest: &mut [u8]) {
if dest.is_empty() {
return; // Nothing to fill
}
let range = dest.as_mut_ptr_range();
// Even if we've preempted the interrupt, it can't preempt us again,
// so we don't need to worry about the order we write these in.
critical_section::with(|cs| {
let mut state = T::state().borrow_mut(cs);
state.ptr = range.start;
state.end = range.end;
});
self.enable_irq();
self.start();
let on_drop = OnDrop::new(|| {
self.stop();
self.disable_irq();
critical_section::with(|cs| {
let mut state = T::state().borrow_mut(cs);
state.ptr = ptr::null_mut();
state.end = ptr::null_mut();
});
});
poll_fn(|cx| {
critical_section::with(|cs| {
let mut s = T::state().borrow_mut(cs);
s.waker.register(cx.waker());
if s.ptr == s.end {
// We're done.
Poll::Ready(())
} else {
Poll::Pending
}
})
})
.await;
// Trigger the teardown
drop(on_drop);
}
/// Fill the buffer with random bytes, blocking version.
pub fn blocking_fill_bytes(&mut self, dest: &mut [u8]) {
self.start();
for byte in dest.iter_mut() {
let regs = T::regs();
while regs.events_valrdy.read().bits() == 0 {}
regs.events_valrdy.reset();
*byte = regs.value.read().value().bits();
}
self.stop();
}
}
impl<'d, T: Instance> Drop for Rng<'d, T> {
fn drop(&mut self) {
self.stop();
critical_section::with(|cs| {
let mut state = T::state().borrow_mut(cs);
state.ptr = ptr::null_mut();
state.end = ptr::null_mut();
});
}
}
impl<'d, T: Instance> rand_core::RngCore for Rng<'d, T> {
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.blocking_fill_bytes(dest);
}
fn next_u32(&mut self) -> u32 {
let mut bytes = [0; 4];
self.blocking_fill_bytes(&mut bytes);
// We don't care about the endianness, so just use the native one.
u32::from_ne_bytes(bytes)
}
fn next_u64(&mut self) -> u64 {
let mut bytes = [0; 8];
self.blocking_fill_bytes(&mut bytes);
u64::from_ne_bytes(bytes)
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
self.blocking_fill_bytes(dest);
Ok(())
}
}
impl<'d, T: Instance> rand_core::CryptoRng for Rng<'d, T> {}
/// Peripheral static state
pub(crate) struct State {
inner: Mutex<RefCell<InnerState>>,
}
struct InnerState {
ptr: *mut u8,
end: *mut u8,
waker: WakerRegistration,
}
unsafe impl Send for InnerState {}
impl State {
pub(crate) const fn new() -> Self {
Self {
inner: Mutex::new(RefCell::new(InnerState::new())),
}
}
fn borrow_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, InnerState> {
self.inner.borrow(cs).borrow_mut()
}
}
impl InnerState {
const fn new() -> Self {
Self {
ptr: ptr::null_mut(),
end: ptr::null_mut(),
waker: WakerRegistration::new(),
}
}
}
pub(crate) trait SealedInstance {
fn regs() -> &'static crate::pac::rng::RegisterBlock;
fn state() -> &'static State;
}
/// RNG peripheral instance.
#[allow(private_bounds)]
pub trait Instance: Peripheral<P = Self> + SealedInstance + 'static + Send {
/// Interrupt for this peripheral.
type Interrupt: interrupt::typelevel::Interrupt;
}
macro_rules! impl_rng {
($type:ident, $pac_type:ident, $irq:ident) => {
impl crate::rng::SealedInstance for peripherals::$type {
fn regs() -> &'static crate::pac::rng::RegisterBlock {
unsafe { &*pac::$pac_type::ptr() }
}
fn state() -> &'static crate::rng::State {
static STATE: crate::rng::State = crate::rng::State::new();
&STATE
}
}
impl crate::rng::Instance for peripherals::$type {
type Interrupt = crate::interrupt::typelevel::$irq;
}
};
}