1 //! RDRAND backend for x86(-64) targets
2 use crate::{lazy::LazyBool, util::slice_as_uninit, Error};
3 use core::mem::{size_of, MaybeUninit};
4
5 cfg_if! {
6 if #[cfg(target_arch = "x86_64")] {
7 use core::arch::x86_64 as arch;
8 use arch::_rdrand64_step as rdrand_step;
9 } else if #[cfg(target_arch = "x86")] {
10 use core::arch::x86 as arch;
11 use arch::_rdrand32_step as rdrand_step;
12 }
13 }
14
15 // Recommendation from "Intel® Digital Random Number Generator (DRNG) Software
16 // Implementation Guide" - Section 5.2.1 and "Intel® 64 and IA-32 Architectures
17 // Software Developer’s Manual" - Volume 1 - Section 7.3.17.1.
18 const RETRY_LIMIT: usize = 10;
19
20 #[target_feature(enable = "rdrand")]
rdrand() -> Option<usize>21 unsafe fn rdrand() -> Option<usize> {
22 for _ in 0..RETRY_LIMIT {
23 let mut val = 0;
24 if rdrand_step(&mut val) == 1 {
25 return Some(val as usize);
26 }
27 }
28 None
29 }
30
31 // "rdrand" target feature requires "+rdrand" flag, see https://github.com/rust-lang/rust/issues/49653.
32 #[cfg(all(target_env = "sgx", not(target_feature = "rdrand")))]
33 compile_error!(
34 "SGX targets require 'rdrand' target feature. Enable by using -C target-feature=+rdrand."
35 );
36
37 // Run a small self-test to make sure we aren't repeating values
38 // Adapted from Linux's test in arch/x86/kernel/cpu/rdrand.c
39 // Fails with probability < 2^(-90) on 32-bit systems
40 #[target_feature(enable = "rdrand")]
self_test() -> bool41 unsafe fn self_test() -> bool {
42 // On AMD, RDRAND returns 0xFF...FF on failure, count it as a collision.
43 let mut prev = !0; // TODO(MSRV 1.43): Move to usize::MAX
44 let mut fails = 0;
45 for _ in 0..8 {
46 match rdrand() {
47 Some(val) if val == prev => fails += 1,
48 Some(val) => prev = val,
49 None => return false,
50 };
51 }
52 fails <= 2
53 }
54
is_rdrand_good() -> bool55 fn is_rdrand_good() -> bool {
56 #[cfg(not(target_feature = "rdrand"))]
57 {
58 // SAFETY: All Rust x86 targets are new enough to have CPUID, and we
59 // check that leaf 1 is supported before using it.
60 let cpuid0 = unsafe { arch::__cpuid(0) };
61 if cpuid0.eax < 1 {
62 return false;
63 }
64 let cpuid1 = unsafe { arch::__cpuid(1) };
65
66 let vendor_id = [
67 cpuid0.ebx.to_le_bytes(),
68 cpuid0.edx.to_le_bytes(),
69 cpuid0.ecx.to_le_bytes(),
70 ];
71 if vendor_id == [*b"Auth", *b"enti", *b"cAMD"] {
72 let mut family = (cpuid1.eax >> 8) & 0xF;
73 if family == 0xF {
74 family += (cpuid1.eax >> 20) & 0xFF;
75 }
76 // AMD CPUs families before 17h (Zen) sometimes fail to set CF when
77 // RDRAND fails after suspend. Don't use RDRAND on those families.
78 // See https://bugzilla.redhat.com/show_bug.cgi?id=1150286
79 if family < 0x17 {
80 return false;
81 }
82 }
83
84 const RDRAND_FLAG: u32 = 1 << 30;
85 if cpuid1.ecx & RDRAND_FLAG == 0 {
86 return false;
87 }
88 }
89
90 // SAFETY: We have already checked that rdrand is available.
91 unsafe { self_test() }
92 }
93
getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>94 pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
95 static RDRAND_GOOD: LazyBool = LazyBool::new();
96 if !RDRAND_GOOD.unsync_init(is_rdrand_good) {
97 return Err(Error::NO_RDRAND);
98 }
99 // SAFETY: After this point, we know rdrand is supported.
100 unsafe { rdrand_exact(dest) }.ok_or(Error::FAILED_RDRAND)
101 }
102
103 // TODO: make this function safe when we have feature(target_feature_11)
104 #[target_feature(enable = "rdrand")]
rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Option<()>105 unsafe fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Option<()> {
106 // We use chunks_exact_mut instead of chunks_mut as it allows almost all
107 // calls to memcpy to be elided by the compiler.
108 let mut chunks = dest.chunks_exact_mut(size_of::<usize>());
109 for chunk in chunks.by_ref() {
110 let src = rdrand()?.to_ne_bytes();
111 chunk.copy_from_slice(slice_as_uninit(&src));
112 }
113
114 let tail = chunks.into_remainder();
115 let n = tail.len();
116 if n > 0 {
117 let src = rdrand()?.to_ne_bytes();
118 tail.copy_from_slice(slice_as_uninit(&src[..n]));
119 }
120 Some(())
121 }
122