1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /*
3  * Copyright (c) 2016 BayLibre, SAS.
4  * Author: Neil Armstrong <narmstrong@baylibre.com>
5  * Copyright (C) 2014 Amlogic, Inc.
6  */
7 #include <linux/err.h>
8 #include <linux/module.h>
9 #include <linux/io.h>
10 #include <linux/platform_device.h>
11 #include <linux/hw_random.h>
12 #include <linux/slab.h>
13 #include <linux/types.h>
14 #include <linux/of.h>
15 #include <linux/clk.h>
16 
17 #define RNG_DATA 0x00
18 
19 struct meson_rng_data {
20 	void __iomem *base;
21 	struct hwrng rng;
22 };
23 
meson_rng_read(struct hwrng * rng,void * buf,size_t max,bool wait)24 static int meson_rng_read(struct hwrng *rng, void *buf, size_t max, bool wait)
25 {
26 	struct meson_rng_data *data =
27 			container_of(rng, struct meson_rng_data, rng);
28 
29 	*(u32 *)buf = readl_relaxed(data->base + RNG_DATA);
30 
31 	return sizeof(u32);
32 }
33 
meson_rng_probe(struct platform_device * pdev)34 static int meson_rng_probe(struct platform_device *pdev)
35 {
36 	struct device *dev = &pdev->dev;
37 	struct meson_rng_data *data;
38 	struct clk *core_clk;
39 
40 	data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
41 	if (!data)
42 		return -ENOMEM;
43 
44 	data->base = devm_platform_ioremap_resource(pdev, 0);
45 	if (IS_ERR(data->base))
46 		return PTR_ERR(data->base);
47 
48 	core_clk = devm_clk_get_optional_enabled(dev, "core");
49 	if (IS_ERR(core_clk))
50 		return dev_err_probe(dev, PTR_ERR(core_clk),
51 				     "Failed to get core clock\n");
52 
53 	data->rng.name = pdev->name;
54 	data->rng.read = meson_rng_read;
55 
56 	return devm_hwrng_register(dev, &data->rng);
57 }
58 
59 static const struct of_device_id meson_rng_of_match[] = {
60 	{ .compatible = "amlogic,meson-rng", },
61 	{},
62 };
63 MODULE_DEVICE_TABLE(of, meson_rng_of_match);
64 
65 static struct platform_driver meson_rng_driver = {
66 	.probe	= meson_rng_probe,
67 	.driver	= {
68 		.name = "meson-rng",
69 		.of_match_table = meson_rng_of_match,
70 	},
71 };
72 
73 module_platform_driver(meson_rng_driver);
74 
75 MODULE_DESCRIPTION("Meson H/W Random Number Generator driver");
76 MODULE_AUTHOR("Lawrence Mok <lawrence.mok@amlogic.com>");
77 MODULE_AUTHOR("Neil Armstrong <narmstrong@baylibre.com>");
78 MODULE_LICENSE("Dual BSD/GPL");
79