forked from briansmith/ring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxous_rand.rs
98 lines (90 loc) · 3.51 KB
/
xous_rand.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
/// Fill `dest` with random bytes from the system's preferred random number
/// source.
///
/// This function returns an error on any failure, including partial reads. We
/// make no guarantees regarding the contents of `dest` on error. If `dest` is
/// empty, `getrandom` immediately returns success, making no calls to the
/// underlying operating system.
///
/// Blocking is possible, at least during early boot; see module documentation.
///
/// In general, `getrandom` will be fast enough for interactive usage, though
/// significantly slower than a user-space CSPRNG; for the latter consider
/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
use core::sync::atomic::AtomicU32;
use core::sync::atomic::Ordering;
use xous_ipc::Buffer;
use crate::error;
static TRNG_CONN: AtomicU32 = AtomicU32::new(0);
#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct TrngBuf {
pub data: [u32; 1024],
pub len: u16,
}
fn ensure_trng_conn() {
if TRNG_CONN.load(Ordering::SeqCst) == 0 {
let xns = xous_names::XousNames::new().unwrap();
TRNG_CONN.store(
xns
.request_connection_blocking("_TRNG manager_")
.expect("Can't connect to TRNG server"),
Ordering::SeqCst
);
}
}
pub fn fill_impl(dest: &mut [u8]) -> Result<(), error::Unspecified> {
if dest.is_empty() {
return Ok(());
}
ensure_trng_conn();
fill_bytes(dest);
Ok(())
}
fn fill_buf(data: &mut [u32]) {
let mut tb = TrngBuf {
data: [0; 1024],
len: 0,
};
assert!(data.len() <= tb.data.len());
tb.len = data.len() as u16;
let mut buf = Buffer::into_buf(tb).unwrap();
let _ = buf.lend_mut(TRNG_CONN.load(Ordering::SeqCst), 1 /* FillTrng */);
let rtb = buf.as_flat::<TrngBuf, _>().unwrap();
assert!(rtb.len as usize == data.len());
data.copy_from_slice(&rtb.data);
}
/// this is less efficient that the implementation in TRNG, but has fewer dependencies
/// In particular, it will always use a memory message to fetch a TRNG value, even if it's just a u32 or u64
fn fill_bytes(dest: &mut [u8]) {
// big chunks handled here, using in-place transformations
for chunk in dest.chunks_exact_mut(4096) {
let chunk_u32 = unsafe {
core::slice::from_raw_parts_mut(chunk.as_mut_ptr() as *mut u32, chunk.len() / 4)
};
fill_buf(chunk_u32);
}
// smaller chunks, we absorb the fill_buf routine above here so we amortize the cost of
// initializing the empty 4k-page...
let remainder = dest.chunks_exact_mut(4096).into_remainder();
if remainder.len() != 0 {
let mut tb = TrngBuf {
data: [0; 1024],
len: 0,
};
tb.len = if remainder.len() % 4 == 0 {
(remainder.len() / 4) as u16
} else {
1 + (remainder.len() / 4) as u16
};
let mut buf = Buffer::into_buf(tb).unwrap();
let _ = buf.lend_mut(TRNG_CONN.load(Ordering::SeqCst), 1 /* FillTrng */);
let rtb = buf.as_flat::<TrngBuf, _>().unwrap();
// transform the whole buffer into a ret_u8 slice (including trailing zeroes)
let ret_u8 = unsafe {
core::slice::from_raw_parts(rtb.data.as_ptr() as *mut u8, rtb.data.len()*4)
};
// we've allocated an extra remainder word to handle the last word overflow, if anything
// we'll end up throwing away a couple of unused bytes, but better than copying zeroes!
remainder.copy_from_slice(&ret_u8[..remainder.len()]);
}
}