1 // SPDX-License-Identifier: GPL-2.0-only
6 * Copyright (C) 2016 Microchip Technology Inc. All rights reserved.
10 #include <linux/clkdev.h>
11 #include <linux/err.h>
12 #include <linux/hw_random.h>
14 #include <linux/kernel.h>
15 #include <linux/mod_devicetable.h>
16 #include <linux/module.h>
17 #include <linux/platform_device.h>
18 #include <linux/slab.h>
22 #define TRNGMOD BIT(11)
26 #define RCNT_MASK 0x7F
34 * The TRNG can generate up to 24Mbps. This is a timeout that should be safe
35 * enough given the instructions in the loop and that the TRNG may not always
38 #define RNG_TIMEOUT 500
40 static int pic32_rng_init(struct hwrng *rng)
42 struct pic32_rng *priv = container_of(rng, struct pic32_rng, rng);
44 /* enable TRNG in enhanced mode */
45 writel(TRNGEN | TRNGMOD, priv->base + RNGCON);
49 static int pic32_rng_read(struct hwrng *rng, void *buf, size_t max,
52 struct pic32_rng *priv = container_of(rng, struct pic32_rng, rng);
55 unsigned int timeout = RNG_TIMEOUT;
58 t = readl(priv->base + RNGRCNT) & RCNT_MASK;
60 /* TRNG value comes through the seed registers */
61 *data = ((u64)readl(priv->base + RNGSEED2) << 32) +
62 readl(priv->base + RNGSEED1);
65 } while (wait && --timeout);
70 static void pic32_rng_cleanup(struct hwrng *rng)
72 struct pic32_rng *priv = container_of(rng, struct pic32_rng, rng);
74 writel(0, priv->base + RNGCON);
77 static int pic32_rng_probe(struct platform_device *pdev)
79 struct pic32_rng *priv;
82 priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
86 priv->base = devm_platform_ioremap_resource(pdev, 0);
87 if (IS_ERR(priv->base))
88 return PTR_ERR(priv->base);
90 clk = devm_clk_get_enabled(&pdev->dev, NULL);
94 priv->rng.name = pdev->name;
95 priv->rng.init = pic32_rng_init;
96 priv->rng.read = pic32_rng_read;
97 priv->rng.cleanup = pic32_rng_cleanup;
99 return devm_hwrng_register(&pdev->dev, &priv->rng);
102 static const struct of_device_id pic32_rng_of_match[] __maybe_unused = {
103 { .compatible = "microchip,pic32mzda-rng", },
106 MODULE_DEVICE_TABLE(of, pic32_rng_of_match);
108 static struct platform_driver pic32_rng_driver = {
109 .probe = pic32_rng_probe,
112 .of_match_table = pic32_rng_of_match,
116 module_platform_driver(pic32_rng_driver);
118 MODULE_LICENSE("GPL");
120 MODULE_DESCRIPTION("Microchip PIC32 RNG Driver");