|
| 1 | +//! RNDR register backend for aarch64 targets |
| 2 | +// Arm Architecture Reference Manual for A-profile architecture |
| 3 | +// ARM DDI 0487K.a, ID032224, D23.2.147 RNDR, Random Number |
| 4 | + |
| 5 | +use crate::{util::slice_as_uninit, Error}; |
| 6 | +use core::arch::asm; |
| 7 | +use core::mem::{size_of, MaybeUninit}; |
| 8 | + |
| 9 | +const RETRY_LIMIT: usize = 5; |
| 10 | + |
| 11 | +// Read a random number from the aarch64 rndr register |
| 12 | +// |
| 13 | +// Callers must ensure that FEAT_RNG is available on the system |
| 14 | +// The function assumes that the RNDR register is available |
| 15 | +// If it fails to read a random number, it will retry up to 5 times |
| 16 | +// After 5 failed reads the function will return None |
| 17 | +#[target_feature(enable = "rand")] |
| 18 | +unsafe fn rndr() -> Option<u64> { |
| 19 | + for _ in 0..RETRY_LIMIT { |
| 20 | + let mut x: u64; |
| 21 | + let mut nzcv: u64; |
| 22 | + |
| 23 | + // AArch64 RNDR register is accessible by s3_3_c2_c4_0 |
| 24 | + asm!( |
| 25 | + "mrs {x}, RNDR", |
| 26 | + "mrs {nzcv}, NZCV", |
| 27 | + x = out(reg) x, |
| 28 | + nzcv = out(reg) nzcv, |
| 29 | + ); |
| 30 | + |
| 31 | + // If the hardware returns a genuine random number, PSTATE.NZCV is set to 0b0000 |
| 32 | + if nzcv == 0 { |
| 33 | + return Some(x); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + None |
| 38 | +} |
| 39 | + |
| 40 | +pub unsafe fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
| 41 | + rndr_exact(dest).ok_or(Error::FAILED_RNDR) |
| 42 | +} |
| 43 | + |
| 44 | +#[target_feature(enable = "rand")] |
| 45 | +unsafe fn rndr_exact(dest: &mut [MaybeUninit<u8>]) -> Option<()> { |
| 46 | + let mut chunks = dest.chunks_exact_mut(size_of::<u64>()); |
| 47 | + for chunk in chunks.by_ref() { |
| 48 | + let src = rndr()?.to_ne_bytes(); |
| 49 | + chunk.copy_from_slice(slice_as_uninit(&src)); |
| 50 | + } |
| 51 | + |
| 52 | + let tail = chunks.into_remainder(); |
| 53 | + let n = tail.len(); |
| 54 | + if n > 0 { |
| 55 | + let src = rndr()?.to_ne_bytes(); |
| 56 | + tail.copy_from_slice(slice_as_uninit(&src[..n])); |
| 57 | + } |
| 58 | + Some(()) |
| 59 | +} |
0 commit comments