Debian Codegraph @

debian/rust-vendor/getrandom/src/backends/rndr.rs

raw
1 //! RNDR register backend for aarch64 targets
2 //!
3 //! Arm Architecture Reference Manual for A-profile architecture:
4 //! ARM DDI 0487K.a, ID032224, D23.2.147 RNDR, Random Number
5 use crate::{
6 Error,
7 util::{slice_as_uninit, truncate},
8 };
9 use core::arch::asm;
10 use core::mem::{MaybeUninit, size_of};
11
12 #[cfg(not(target_arch = "aarch64"))]
13 compile_error!("the `rndr` backend can be enabled only for AArch64 targets!");
14
15 const RETRY_LIMIT: usize = 5;
16
17 /// Read a random number from the aarch64 RNDR register
18 ///
19 /// Callers must ensure that FEAT_RNG is available on the system
20 /// The function assumes that the RNDR register is available
21 /// If it fails to read a random number, it will retry up to 5 times
22 /// After 5 failed reads the function will return `None`
23 #[target_feature(enable = "rand")]
24 unsafe fn rndr() -> Option<u64> {
25 for _ in 0..RETRY_LIMIT {
26 let mut x: u64;
27 let mut nzcv: u64;
28
29 // AArch64 RNDR register is accessible by s3_3_c2_c4_0
30 unsafe {
31 asm!(
32 "mrs {x}, RNDR",
33 "mrs {nzcv}, NZCV",
34 x = out(reg) x,
35 nzcv = out(reg) nzcv,
36 );
37 }
38
39 // If the hardware returns a genuine random number, PSTATE.NZCV is set to 0b0000
40 if nzcv == 0 {
41 return Some(x);
42 }
43 }
44
45 None
46 }
47
48 #[target_feature(enable = "rand")]
49 unsafe fn rndr_fill(dest: &mut [MaybeUninit<u8>]) -> Option<()> {
50 let mut chunks = dest.chunks_exact_mut(size_of::<u64>());
51 for chunk in chunks.by_ref() {
52 let src = unsafe { rndr() }?.to_ne_bytes();
53 chunk.copy_from_slice(slice_as_uninit(&src));
54 }
55
56 let tail = chunks.into_remainder();
57 let n = tail.len();
58 if n > 0 {
59 let src = unsafe { rndr() }?.to_ne_bytes();
60 tail.copy_from_slice(slice_as_uninit(&src[..n]));
61 }
62 Some(())
63 }
64
65 #[cfg(target_feature = "rand")]
66 fn is_rndr_available() -> bool {
67 true
68 }
69
70 #[cfg(not(target_feature = "rand"))]
71 fn is_rndr_available() -> bool {
72 #[path = "../utils/lazy_bool.rs"]
73 mod lazy;
74
75 static RNDR_GOOD: lazy::LazyBool = lazy::LazyBool::new();
76
77 cfg_if::cfg_if! {
78 if #[cfg(feature = "std")] {
79 extern crate std;
80 RNDR_GOOD.unsync_init(|| std::arch::is_aarch64_feature_detected!("rand"))
81 } else if #[cfg(target_os = "linux")] {
82 /// Check whether FEAT_RNG is available on the system
83 ///
84 /// Requires the caller either be running in EL1 or be on a system supporting MRS
85 /// emulation. Due to the above, the implementation is currently restricted to Linux.
86 ///
87 /// Relying on runtime detection bumps minimum supported Linux kernel version to 4.11.
88 fn mrs_check() -> bool {
89 let mut id_aa64isar0: u64;
90
91 // If FEAT_RNG is implemented, ID_AA64ISAR0_EL1.RNDR (bits 60-63) are 0b0001
92 // This is okay to do from EL0 in Linux because Linux will emulate MRS as per
93 // https://docs.kernel.org/arch/arm64/cpu-feature-registers.html
94 unsafe {
95 asm!(
96 "mrs {id}, ID_AA64ISAR0_EL1",
97 id = out(reg) id_aa64isar0,
98 );
99 }
100
101 (id_aa64isar0 >> 60) & 0xf >= 1
102 }
103
104 RNDR_GOOD.unsync_init(mrs_check)
105 } else {
106 compile_error!(
107 "RNDR `no_std` runtime detection is currently supported only on Linux targets. \
108 Either enable the `std` crate feature, or `rand` target feature at compile time."
109 );
110 }
111 }
112 }
113
114 #[inline]
115 pub fn inner_u32() -> Result<u32, Error> {
116 if !is_rndr_available() {
117 return Err(Error::RNDR_NOT_AVAILABLE);
118 }
119 // SAFETY: after this point, we know the `rand` target feature is enabled
120 let res = unsafe { rndr() };
121 res.map(truncate).ok_or(Error::RNDR_FAILURE)
122 }
123
124 #[inline]
125 pub fn inner_u64() -> Result<u64, Error> {
126 if !is_rndr_available() {
127 return Err(Error::RNDR_NOT_AVAILABLE);
128 }
129 // SAFETY: after this point, we know the `rand` target feature is enabled
130 let res = unsafe { rndr() };
131 res.ok_or(Error::RNDR_FAILURE)
132 }
133
134 #[inline]
135 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
136 if !is_rndr_available() {
137 return Err(Error::RNDR_NOT_AVAILABLE);
138 }
139 // SAFETY: after this point, we know the `rand` target feature is enabled
140 unsafe { rndr_fill(dest).ok_or(Error::RNDR_FAILURE) }
141 }
142
143 impl Error {
144 /// RNDR register read failed due to a hardware issue.
145 pub(crate) const RNDR_FAILURE: Error = Self::new_internal(10);
146 /// RNDR register is not supported on this target.
147 pub(crate) const RNDR_NOT_AVAILABLE: Error = Self::new_internal(11);
148 }