1 // SPDX-License-Identifier: GPL-2.0
3 * Randomness driver for the ARM SMCCC TRNG Firmware Interface
4 * https://developer.arm.com/documentation/den0098/latest/
6 * Copyright (C) 2020 Arm Ltd.
8 * The ARM TRNG firmware interface specifies a protocol to read entropy
9 * from a higher exception level, to abstract from any machine specific
10 * implemenations and allow easier use in hypervisors.
12 * The firmware interface is realised using the SMCCC specification.
15 #include <linux/bits.h>
16 #include <linux/device.h>
17 #include <linux/hw_random.h>
18 #include <linux/module.h>
19 #include <linux/platform_device.h>
20 #include <linux/arm-smccc.h>
23 #define ARM_SMCCC_TRNG_RND ARM_SMCCC_TRNG_RND64
24 #define MAX_BITS_PER_CALL (3 * 64UL)
26 #define ARM_SMCCC_TRNG_RND ARM_SMCCC_TRNG_RND32
27 #define MAX_BITS_PER_CALL (3 * 32UL)
30 /* We don't want to allow the firmware to stall us forever. */
31 #define SMCCC_TRNG_MAX_TRIES 20
33 #define SMCCC_RET_TRNG_INVALID_PARAMETER -2
34 #define SMCCC_RET_TRNG_NO_ENTROPY -3
36 static int copy_from_registers(char *buf, struct arm_smccc_res *res,
39 unsigned int chunk, copied;
44 chunk = min(bytes, sizeof(long));
45 memcpy(buf, &res->a3, chunk);
50 chunk = min((bytes - copied), sizeof(long));
51 memcpy(&buf[copied], &res->a2, chunk);
56 chunk = min((bytes - copied), sizeof(long));
57 memcpy(&buf[copied], &res->a1, chunk);
59 return copied + chunk;
62 static int smccc_trng_read(struct hwrng *rng, void *data, size_t max, bool wait)
64 struct arm_smccc_res res;
66 unsigned int copied = 0;
69 while (copied < max) {
70 size_t bits = min_t(size_t, (max - copied) * BITS_PER_BYTE,
73 arm_smccc_1_1_invoke(ARM_SMCCC_TRNG_RND, bits, &res);
77 switch ((int)res.a0) {
78 case SMCCC_RET_SUCCESS:
79 copied += copy_from_registers(buf + copied, &res,
80 bits / BITS_PER_BYTE);
83 case SMCCC_RET_TRNG_NO_ENTROPY:
87 if (tries >= SMCCC_TRNG_MAX_TRIES)
97 static int smccc_trng_probe(struct platform_device *pdev)
101 trng = devm_kzalloc(&pdev->dev, sizeof(*trng), GFP_KERNEL);
105 trng->name = "smccc_trng";
106 trng->read = smccc_trng_read;
108 platform_set_drvdata(pdev, trng);
110 return devm_hwrng_register(&pdev->dev, trng);
113 static struct platform_driver smccc_trng_driver = {
115 .name = "smccc_trng",
117 .probe = smccc_trng_probe,
119 module_platform_driver(smccc_trng_driver);
121 MODULE_ALIAS("platform:smccc_trng");
122 MODULE_AUTHOR("Andre Przywara");
123 MODULE_LICENSE("GPL");