1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Microchip PolarFire SoC (MPFS) hardware random driver
4  *
5  * Copyright (c) 2020-2022 Microchip Corporation. All rights reserved.
6  *
7  * Author: Conor Dooley <conor.dooley@microchip.com>
8  */
9 
10 #include <linux/module.h>
11 #include <linux/hw_random.h>
12 #include <linux/platform_device.h>
13 #include <soc/microchip/mpfs.h>
14 
15 #define CMD_OPCODE	0x21
16 #define CMD_DATA_SIZE	0U
17 #define CMD_DATA	NULL
18 #define MBOX_OFFSET	0U
19 #define RESP_OFFSET	0U
20 #define RNG_RESP_BYTES	32U
21 
22 struct mpfs_rng {
23 	struct mpfs_sys_controller *sys_controller;
24 	struct hwrng rng;
25 };
26 
27 static int mpfs_rng_read(struct hwrng *rng, void *buf, size_t max, bool wait)
28 {
29 	struct mpfs_rng *rng_priv = container_of(rng, struct mpfs_rng, rng);
30 	u32 response_msg[RNG_RESP_BYTES / sizeof(u32)];
31 	unsigned int count = 0, copy_size_bytes;
32 	int ret;
33 
34 	struct mpfs_mss_response response = {
35 		.resp_status = 0U,
36 		.resp_msg = (u32 *)response_msg,
37 		.resp_size = RNG_RESP_BYTES
38 	};
39 	struct mpfs_mss_msg msg = {
40 		.cmd_opcode = CMD_OPCODE,
41 		.cmd_data_size = CMD_DATA_SIZE,
42 		.response = &response,
43 		.cmd_data = CMD_DATA,
44 		.mbox_offset = MBOX_OFFSET,
45 		.resp_offset = RESP_OFFSET
46 	};
47 
48 	while (count < max) {
49 		ret = mpfs_blocking_transaction(rng_priv->sys_controller, &msg);
50 		if (ret)
51 			return ret;
52 
53 		copy_size_bytes = max - count > RNG_RESP_BYTES ? RNG_RESP_BYTES : max - count;
54 		memcpy(buf + count, response_msg, copy_size_bytes);
55 
56 		count += copy_size_bytes;
57 		if (!wait)
58 			break;
59 	}
60 
61 	return count;
62 }
63 
64 static int mpfs_rng_probe(struct platform_device *pdev)
65 {
66 	struct device *dev = &pdev->dev;
67 	struct mpfs_rng *rng_priv;
68 	int ret;
69 
70 	rng_priv = devm_kzalloc(dev, sizeof(*rng_priv), GFP_KERNEL);
71 	if (!rng_priv)
72 		return -ENOMEM;
73 
74 	rng_priv->sys_controller =  mpfs_sys_controller_get(&pdev->dev);
75 	if (IS_ERR(rng_priv->sys_controller))
76 		return dev_err_probe(dev, PTR_ERR(rng_priv->sys_controller),
77 				     "Failed to register system controller hwrng sub device\n");
78 
79 	rng_priv->rng.read = mpfs_rng_read;
80 	rng_priv->rng.name = pdev->name;
81 
82 	platform_set_drvdata(pdev, rng_priv);
83 
84 	ret = devm_hwrng_register(&pdev->dev, &rng_priv->rng);
85 	if (ret)
86 		return dev_err_probe(&pdev->dev, ret, "Failed to register MPFS hwrng\n");
87 
88 	dev_info(&pdev->dev, "Registered MPFS hwrng\n");
89 
90 	return 0;
91 }
92 
93 static struct platform_driver mpfs_rng_driver = {
94 	.driver = {
95 		.name = "mpfs-rng",
96 	},
97 	.probe = mpfs_rng_probe,
98 };
99 module_platform_driver(mpfs_rng_driver);
100 
101 MODULE_LICENSE("GPL");
102 MODULE_AUTHOR("Conor Dooley <conor.dooley@microchip.com>");
103 MODULE_DESCRIPTION("PolarFire SoC (MPFS) hardware random driver");
104