Path: blob/master/drivers/char/hw_random/arm_smccc_trng.c
29269 views
// SPDX-License-Identifier: GPL-2.01/*2* Randomness driver for the ARM SMCCC TRNG Firmware Interface3* https://developer.arm.com/documentation/den0098/latest/4*5* Copyright (C) 2020 Arm Ltd.6*7* The ARM TRNG firmware interface specifies a protocol to read entropy8* from a higher exception level, to abstract from any machine specific9* implemenations and allow easier use in hypervisors.10*11* The firmware interface is realised using the SMCCC specification.12*/1314#include <linux/bits.h>15#include <linux/device.h>16#include <linux/hw_random.h>17#include <linux/module.h>18#include <linux/platform_device.h>19#include <linux/arm-smccc.h>2021#ifdef CONFIG_ARM6422#define ARM_SMCCC_TRNG_RND ARM_SMCCC_TRNG_RND6423#define MAX_BITS_PER_CALL (3 * 64UL)24#else25#define ARM_SMCCC_TRNG_RND ARM_SMCCC_TRNG_RND3226#define MAX_BITS_PER_CALL (3 * 32UL)27#endif2829/* We don't want to allow the firmware to stall us forever. */30#define SMCCC_TRNG_MAX_TRIES 203132#define SMCCC_RET_TRNG_INVALID_PARAMETER -233#define SMCCC_RET_TRNG_NO_ENTROPY -33435static int copy_from_registers(char *buf, struct arm_smccc_res *res,36size_t bytes)37{38unsigned int chunk, copied;3940if (bytes == 0)41return 0;4243chunk = min(bytes, sizeof(long));44memcpy(buf, &res->a3, chunk);45copied = chunk;46if (copied >= bytes)47return copied;4849chunk = min((bytes - copied), sizeof(long));50memcpy(&buf[copied], &res->a2, chunk);51copied += chunk;52if (copied >= bytes)53return copied;5455chunk = min((bytes - copied), sizeof(long));56memcpy(&buf[copied], &res->a1, chunk);5758return copied + chunk;59}6061static int smccc_trng_read(struct hwrng *rng, void *data, size_t max, bool wait)62{63struct arm_smccc_res res;64u8 *buf = data;65unsigned int copied = 0;66int tries = 0;6768while (copied < max) {69size_t bits = min_t(size_t, (max - copied) * BITS_PER_BYTE,70MAX_BITS_PER_CALL);7172arm_smccc_1_1_invoke(ARM_SMCCC_TRNG_RND, bits, &res);7374switch ((int)res.a0) {75case SMCCC_RET_SUCCESS:76copied += copy_from_registers(buf + copied, &res,77bits / BITS_PER_BYTE);78tries = 0;79break;80case SMCCC_RET_TRNG_NO_ENTROPY:81if (!wait)82return copied;83tries++;84if (tries >= SMCCC_TRNG_MAX_TRIES)85return copied;86cond_resched();87break;88default:89return -EIO;90}91}9293return copied;94}9596static int smccc_trng_probe(struct platform_device *pdev)97{98struct hwrng *trng;99100trng = devm_kzalloc(&pdev->dev, sizeof(*trng), GFP_KERNEL);101if (!trng)102return -ENOMEM;103104trng->name = "smccc_trng";105trng->read = smccc_trng_read;106107return devm_hwrng_register(&pdev->dev, trng);108}109110static struct platform_driver smccc_trng_driver = {111.driver = {112.name = "smccc_trng",113},114.probe = smccc_trng_probe,115};116module_platform_driver(smccc_trng_driver);117118MODULE_ALIAS("platform:smccc_trng");119MODULE_AUTHOR("Andre Przywara");120MODULE_DESCRIPTION("Arm SMCCC TRNG firmware interface support");121MODULE_LICENSE("GPL");122123124