1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2016 HiSilicon Co., Ltd.
7 #include <linux/kernel.h>
8 #include <linux/hw_random.h>
10 #include <linux/module.h>
12 #include <linux/platform_device.h>
13 #include <linux/random.h>
17 #define RNG_SEED_SEL BIT(2)
18 #define RNG_RING_EN BIT(1)
20 #define RNG_RAN_NUM 0x10
21 #define RNG_PHY_SEED 0x14
23 #define to_hisi_rng(p) container_of(p, struct hisi_rng, rng)
26 module_param(seed_sel
, int, S_IRUGO
);
27 MODULE_PARM_DESC(seed_sel
, "Auto reload seed. 0, use LFSR(default); 1, use ring oscillator.");
34 static int hisi_rng_init(struct hwrng
*rng
)
36 struct hisi_rng
*hrng
= to_hisi_rng(rng
);
40 /* get a random number as initial seed */
41 get_random_bytes(&seed
, sizeof(seed
));
43 writel_relaxed(seed
, hrng
->base
+ RNG_SEED
);
46 * The seed is reload periodically, there are two choice
47 * of seeds, default seed using the value from LFSR, or
48 * will use seed generated by ring oscillator.
51 val
|= RNG_RING_EN
| RNG_SEED_SEL
;
53 writel_relaxed(val
, hrng
->base
+ RNG_CTRL
);
57 static void hisi_rng_cleanup(struct hwrng
*rng
)
59 struct hisi_rng
*hrng
= to_hisi_rng(rng
);
61 writel_relaxed(0, hrng
->base
+ RNG_CTRL
);
64 static int hisi_rng_read(struct hwrng
*rng
, void *buf
, size_t max
, bool wait
)
66 struct hisi_rng
*hrng
= to_hisi_rng(rng
);
69 *data
= readl_relaxed(hrng
->base
+ RNG_RAN_NUM
);
73 static int hisi_rng_probe(struct platform_device
*pdev
)
78 rng
= devm_kzalloc(&pdev
->dev
, sizeof(*rng
), GFP_KERNEL
);
82 platform_set_drvdata(pdev
, rng
);
84 rng
->base
= devm_platform_ioremap_resource(pdev
, 0);
85 if (IS_ERR(rng
->base
))
86 return PTR_ERR(rng
->base
);
88 rng
->rng
.name
= pdev
->name
;
89 rng
->rng
.init
= hisi_rng_init
;
90 rng
->rng
.cleanup
= hisi_rng_cleanup
;
91 rng
->rng
.read
= hisi_rng_read
;
93 ret
= devm_hwrng_register(&pdev
->dev
, &rng
->rng
);
95 dev_err(&pdev
->dev
, "failed to register hwrng\n");
102 static const struct of_device_id hisi_rng_dt_ids
[] = {
103 { .compatible
= "hisilicon,hip04-rng" },
104 { .compatible
= "hisilicon,hip05-rng" },
107 MODULE_DEVICE_TABLE(of
, hisi_rng_dt_ids
);
109 static struct platform_driver hisi_rng_driver
= {
110 .probe
= hisi_rng_probe
,
113 .of_match_table
= of_match_ptr(hisi_rng_dt_ids
),
117 module_platform_driver(hisi_rng_driver
);
119 MODULE_LICENSE("GPL");
120 MODULE_AUTHOR("Kefeng Wang <wangkefeng.wang@huawei>");
121 MODULE_DESCRIPTION("Hisilicon random number generator driver");