1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright 2013 Michael Ellerman, Guo Chao, IBM Corp.
4  */
5 
6 #define pr_fmt(fmt)	KBUILD_MODNAME ": " fmt
7 
8 #include <linux/module.h>
9 #include <linux/mod_devicetable.h>
10 #include <linux/kernel.h>
11 #include <linux/platform_device.h>
12 #include <linux/random.h>
13 #include <linux/hw_random.h>
14 
15 static int powernv_rng_read(struct hwrng *rng, void *data, size_t max, bool wait)
16 {
17 	unsigned long *buf;
18 	int i, len;
19 
20 	/* We rely on rng_buffer_size() being >= sizeof(unsigned long) */
21 	len = max / sizeof(unsigned long);
22 
23 	buf = (unsigned long *)data;
24 
25 	for (i = 0; i < len; i++)
26 		powernv_get_random_long(buf++);
27 
28 	return len * sizeof(unsigned long);
29 }
30 
31 static struct hwrng powernv_hwrng = {
32 	.name = "powernv-rng",
33 	.read = powernv_rng_read,
34 };
35 
36 static int powernv_rng_remove(struct platform_device *pdev)
37 {
38 	hwrng_unregister(&powernv_hwrng);
39 
40 	return 0;
41 }
42 
43 static int powernv_rng_probe(struct platform_device *pdev)
44 {
45 	int rc;
46 
47 	rc = hwrng_register(&powernv_hwrng);
48 	if (rc) {
49 		/* We only register one device, ignore any others */
50 		if (rc == -EEXIST)
51 			rc = -ENODEV;
52 
53 		return rc;
54 	}
55 
56 	pr_info("Registered powernv hwrng.\n");
57 
58 	return 0;
59 }
60 
61 static const struct of_device_id powernv_rng_match[] = {
62 	{ .compatible	= "ibm,power-rng",},
63 	{},
64 };
65 MODULE_DEVICE_TABLE(of, powernv_rng_match);
66 
67 static struct platform_driver powernv_rng_driver = {
68 	.driver = {
69 		.name = "powernv_rng",
70 		.of_match_table = powernv_rng_match,
71 	},
72 	.probe	= powernv_rng_probe,
73 	.remove = powernv_rng_remove,
74 };
75 module_platform_driver(powernv_rng_driver);
76 
77 MODULE_LICENSE("GPL");
78 MODULE_DESCRIPTION("Bare metal HWRNG driver for POWER7+ and above");
79