2 * Copyright (C) 2016 HiSilicon Co., Ltd.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
10 #include <linux/kernel.h>
11 #include <linux/hw_random.h>
13 #include <linux/module.h>
15 #include <linux/platform_device.h>
16 #include <linux/random.h>
20 #define RNG_SEED_SEL BIT(2)
21 #define RNG_RING_EN BIT(1)
23 #define RNG_RAN_NUM 0x10
24 #define RNG_PHY_SEED 0x14
26 #define to_hisi_rng(p) container_of(p, struct hisi_rng, rng)
29 module_param(seed_sel
, int, S_IRUGO
);
30 MODULE_PARM_DESC(seed_sel
, "Auto reload seed. 0, use LFSR(default); 1, use ring oscillator.");
37 static int hisi_rng_init(struct hwrng
*rng
)
39 struct hisi_rng
*hrng
= to_hisi_rng(rng
);
43 /* get a random number as initial seed */
44 get_random_bytes(&seed
, sizeof(seed
));
46 writel_relaxed(seed
, hrng
->base
+ RNG_SEED
);
49 * The seed is reload periodically, there are two choice
50 * of seeds, default seed using the value from LFSR, or
51 * will use seed generated by ring oscillator.
54 val
|= RNG_RING_EN
| RNG_SEED_SEL
;
56 writel_relaxed(val
, hrng
->base
+ RNG_CTRL
);
60 static void hisi_rng_cleanup(struct hwrng
*rng
)
62 struct hisi_rng
*hrng
= to_hisi_rng(rng
);
64 writel_relaxed(0, hrng
->base
+ RNG_CTRL
);
67 static int hisi_rng_read(struct hwrng
*rng
, void *buf
, size_t max
, bool wait
)
69 struct hisi_rng
*hrng
= to_hisi_rng(rng
);
72 *data
= readl_relaxed(hrng
->base
+ RNG_RAN_NUM
);
76 static int hisi_rng_probe(struct platform_device
*pdev
)
82 rng
= devm_kzalloc(&pdev
->dev
, sizeof(*rng
), GFP_KERNEL
);
86 platform_set_drvdata(pdev
, rng
);
88 res
= platform_get_resource(pdev
, IORESOURCE_MEM
, 0);
89 rng
->base
= devm_ioremap_resource(&pdev
->dev
, res
);
90 if (IS_ERR(rng
->base
))
91 return PTR_ERR(rng
->base
);
93 rng
->rng
.name
= pdev
->name
;
94 rng
->rng
.init
= hisi_rng_init
;
95 rng
->rng
.cleanup
= hisi_rng_cleanup
;
96 rng
->rng
.read
= hisi_rng_read
;
98 ret
= devm_hwrng_register(&pdev
->dev
, &rng
->rng
);
100 dev_err(&pdev
->dev
, "failed to register hwrng\n");
107 static const struct of_device_id hisi_rng_dt_ids
[] = {
108 { .compatible
= "hisilicon,hip04-rng" },
109 { .compatible
= "hisilicon,hip05-rng" },
112 MODULE_DEVICE_TABLE(of
, hisi_rng_dt_ids
);
114 static struct platform_driver hisi_rng_driver
= {
115 .probe
= hisi_rng_probe
,
118 .of_match_table
= of_match_ptr(hisi_rng_dt_ids
),
122 module_platform_driver(hisi_rng_driver
);
124 MODULE_LICENSE("GPL");
125 MODULE_AUTHOR("Kefeng Wang <wangkefeng.wang@huawei>");
126 MODULE_DESCRIPTION("Hisilicon random number generator driver");