1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _ASM_ARCHRANDOM_H
3 #define _ASM_ARCHRANDOM_H
5 #ifdef CONFIG_ARCH_RANDOM
7 #include <linux/arm-smccc.h>
9 #include <linux/kernel.h>
10 #include <asm/cpufeature.h>
12 #define ARM_SMCCC_TRNG_MIN_VERSION 0x10000UL
14 extern bool smccc_trng_available;
16 static inline bool __init smccc_probe_trng(void)
18 struct arm_smccc_res res;
20 arm_smccc_1_1_invoke(ARM_SMCCC_TRNG_VERSION, &res);
24 return res.a0 >= ARM_SMCCC_TRNG_MIN_VERSION;
27 static inline bool __arm64_rndr(unsigned long *v)
32 * Reads of RNDR set PSTATE.NZCV to 0b0000 on success,
33 * and set PSTATE.NZCV to 0b0100 otherwise.
36 __mrs_s("%0", SYS_RNDR_EL0) "\n"
38 : "=r" (*v), "=r" (ok)
45 static inline bool __must_check arch_get_random_long(unsigned long *v)
50 static inline bool __must_check arch_get_random_int(unsigned int *v)
55 static inline bool __must_check arch_get_random_seed_long(unsigned long *v)
57 struct arm_smccc_res res;
60 * We prefer the SMCCC call, since its semantics (return actual
61 * hardware backed entropy) is closer to the idea behind this
62 * function here than what even the RNDRSS register provides
63 * (the output of a pseudo RNG freshly seeded by a TRNG).
65 if (smccc_trng_available) {
66 arm_smccc_1_1_invoke(ARM_SMCCC_TRNG_RND64, 64, &res);
67 if ((int)res.a0 >= 0) {
74 * Only support the generic interface after we have detected
75 * the system wide capability, avoiding complexity with the
76 * cpufeature code and with potential scheduling between CPUs
77 * with and without the feature.
79 if (cpus_have_const_cap(ARM64_HAS_RNG) && __arm64_rndr(v))
85 static inline bool __must_check arch_get_random_seed_int(unsigned int *v)
87 struct arm_smccc_res res;
90 if (smccc_trng_available) {
91 arm_smccc_1_1_invoke(ARM_SMCCC_TRNG_RND64, 32, &res);
92 if ((int)res.a0 >= 0) {
93 *v = res.a3 & GENMASK(31, 0);
98 if (cpus_have_const_cap(ARM64_HAS_RNG)) {
99 if (__arm64_rndr(&val)) {
108 static inline bool __init __early_cpu_has_rndr(void)
110 /* Open code as we run prior to the first call to cpufeature. */
111 unsigned long ftr = read_sysreg_s(SYS_ID_AA64ISAR0_EL1);
112 return (ftr >> ID_AA64ISAR0_RNDR_SHIFT) & 0xf;
115 static inline bool __init __must_check
116 arch_get_random_seed_long_early(unsigned long *v)
118 WARN_ON(system_state != SYSTEM_BOOTING);
120 if (smccc_trng_available) {
121 struct arm_smccc_res res;
123 arm_smccc_1_1_invoke(ARM_SMCCC_TRNG_RND64, 64, &res);
124 if ((int)res.a0 >= 0) {
130 if (__early_cpu_has_rndr() && __arm64_rndr(v))
135 #define arch_get_random_seed_long_early arch_get_random_seed_long_early
137 #else /* !CONFIG_ARCH_RANDOM */
139 static inline bool __init smccc_probe_trng(void)
144 #endif /* CONFIG_ARCH_RANDOM */
145 #endif /* _ASM_ARCHRANDOM_H */