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