xref: /linux/drivers/char/hw_random/stm32-rng.c (revision f134d5dce9c1f70fb522712b306644deb1e6eccd)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2015, Daniel Thompson
4  */
5 
6 #include <linux/clk.h>
7 #include <linux/delay.h>
8 #include <linux/hw_random.h>
9 #include <linux/io.h>
10 #include <linux/iopoll.h>
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/of.h>
14 #include <linux/of_address.h>
15 #include <linux/platform_device.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/reset.h>
18 #include <linux/slab.h>
19 
20 #define RNG_CR			0x00
21 #define RNG_CR_RNGEN		BIT(2)
22 #define RNG_CR_CED		BIT(5)
23 #define RNG_CR_CONFIG1		GENMASK(11, 8)
24 #define RNG_CR_NISTC		BIT(12)
25 #define RNG_CR_CONFIG2		GENMASK(15, 13)
26 #define RNG_CR_CLKDIV_SHIFT	16
27 #define RNG_CR_CLKDIV		GENMASK(19, 16)
28 #define RNG_CR_CONFIG3		GENMASK(25, 20)
29 #define RNG_CR_CONDRST		BIT(30)
30 #define RNG_CR_CONFLOCK		BIT(31)
31 #define RNG_CR_ENTROPY_SRC_MASK	(RNG_CR_CONFIG1 | RNG_CR_NISTC | RNG_CR_CONFIG2 | RNG_CR_CONFIG3)
32 #define RNG_CR_CONFIG_MASK	(RNG_CR_ENTROPY_SRC_MASK | RNG_CR_CED | RNG_CR_CLKDIV)
33 
34 #define RNG_SR			0x04
35 #define RNG_SR_DRDY		BIT(0)
36 #define RNG_SR_CECS		BIT(1)
37 #define RNG_SR_SECS		BIT(2)
38 #define RNG_SR_CEIS		BIT(5)
39 #define RNG_SR_SEIS		BIT(6)
40 
41 #define RNG_DR			0x08
42 
43 #define RNG_NSCR		0x0C
44 #define RNG_NSCR_MASK		GENMASK(17, 0)
45 
46 #define RNG_HTCR		0x10
47 
48 #define RNG_NB_RECOVER_TRIES	3
49 
50 struct stm32_rng_data {
51 	uint	max_clock_rate;
52 	u32	cr;
53 	u32	nscr;
54 	u32	htcr;
55 	bool	has_cond_reset;
56 };
57 
58 /**
59  * struct stm32_rng_config - RNG configuration data
60  *
61  * @cr:			RNG configuration. 0 means default hardware RNG configuration
62  * @nscr:		Noise sources control configuration.
63  * @htcr:		Health tests configuration.
64  */
65 struct stm32_rng_config {
66 	u32 cr;
67 	u32 nscr;
68 	u32 htcr;
69 };
70 
71 struct stm32_rng_private {
72 	struct hwrng rng;
73 	void __iomem *base;
74 	struct clk *clk;
75 	struct reset_control *rst;
76 	struct stm32_rng_config pm_conf;
77 	const struct stm32_rng_data *data;
78 	bool ced;
79 	bool lock_conf;
80 };
81 
82 /*
83  * Extracts from the STM32 RNG specification when RNG supports CONDRST.
84  *
85  * When a noise source (or seed) error occurs, the RNG stops generating
86  * random numbers and sets to “1” both SEIS and SECS bits to indicate
87  * that a seed error occurred. (...)
88  *
89  * 1. Software reset by writing CONDRST at 1 and at 0 (see bitfield
90  * description for details). This step is needed only if SECS is set.
91  * Indeed, when SEIS is set and SECS is cleared it means RNG performed
92  * the reset automatically (auto-reset).
93  * 2. If SECS was set in step 1 (no auto-reset) wait for CONDRST
94  * to be cleared in the RNG_CR register, then confirm that SEIS is
95  * cleared in the RNG_SR register. Otherwise just clear SEIS bit in
96  * the RNG_SR register.
97  * 3. If SECS was set in step 1 (no auto-reset) wait for SECS to be
98  * cleared by RNG. The random number generation is now back to normal.
99  */
100 static int stm32_rng_conceal_seed_error_cond_reset(struct stm32_rng_private *priv)
101 {
102 	struct device *dev = (struct device *)priv->rng.priv;
103 	u32 sr = readl_relaxed(priv->base + RNG_SR);
104 	u32 cr = readl_relaxed(priv->base + RNG_CR);
105 	int err;
106 
107 	if (sr & RNG_SR_SECS) {
108 		/* Conceal by resetting the subsystem (step 1.) */
109 		writel_relaxed(cr | RNG_CR_CONDRST, priv->base + RNG_CR);
110 		writel_relaxed(cr & ~RNG_CR_CONDRST, priv->base + RNG_CR);
111 	} else {
112 		/* RNG auto-reset (step 2.) */
113 		writel_relaxed(sr & ~RNG_SR_SEIS, priv->base + RNG_SR);
114 		goto end;
115 	}
116 
117 	err = readl_relaxed_poll_timeout_atomic(priv->base + RNG_CR, cr, !(cr & RNG_CR_CONDRST), 10,
118 						100000);
119 	if (err) {
120 		dev_err(dev, "%s: timeout %x\n", __func__, sr);
121 		return err;
122 	}
123 
124 	/* Check SEIS is cleared (step 2.) */
125 	if (readl_relaxed(priv->base + RNG_SR) & RNG_SR_SEIS)
126 		return -EINVAL;
127 
128 	err = readl_relaxed_poll_timeout_atomic(priv->base + RNG_SR, sr, !(sr & RNG_SR_SECS), 10,
129 						100000);
130 	if (err) {
131 		dev_err(dev, "%s: timeout %x\n", __func__, sr);
132 		return err;
133 	}
134 
135 end:
136 	return 0;
137 }
138 
139 /*
140  * Extracts from the STM32 RNG specification, when CONDRST is not supported
141  *
142  * When a noise source (or seed) error occurs, the RNG stops generating
143  * random numbers and sets to “1” both SEIS and SECS bits to indicate
144  * that a seed error occurred. (...)
145  *
146  * The following sequence shall be used to fully recover from a seed
147  * error after the RNG initialization:
148  * 1. Clear the SEIS bit by writing it to “0”.
149  * 2. Read out 12 words from the RNG_DR register, and discard each of
150  * them in order to clean the pipeline.
151  * 3. Confirm that SEIS is still cleared. Random number generation is
152  * back to normal.
153  */
154 static int stm32_rng_conceal_seed_error_sw_reset(struct stm32_rng_private *priv)
155 {
156 	unsigned int i = 0;
157 	u32 sr = readl_relaxed(priv->base + RNG_SR);
158 
159 	writel_relaxed(sr & ~RNG_SR_SEIS, priv->base + RNG_SR);
160 
161 	for (i = 12; i != 0; i--)
162 		(void)readl_relaxed(priv->base + RNG_DR);
163 
164 	if (readl_relaxed(priv->base + RNG_SR) & RNG_SR_SEIS)
165 		return -EINVAL;
166 
167 	return 0;
168 }
169 
170 static int stm32_rng_conceal_seed_error(struct hwrng *rng)
171 {
172 	struct stm32_rng_private *priv = container_of(rng, struct stm32_rng_private, rng);
173 
174 	dev_dbg((struct device *)priv->rng.priv, "Concealing seed error\n");
175 
176 	if (priv->data->has_cond_reset)
177 		return stm32_rng_conceal_seed_error_cond_reset(priv);
178 	else
179 		return stm32_rng_conceal_seed_error_sw_reset(priv);
180 };
181 
182 
183 static int stm32_rng_read(struct hwrng *rng, void *data, size_t max, bool wait)
184 {
185 	struct stm32_rng_private *priv = container_of(rng, struct stm32_rng_private, rng);
186 	unsigned int i = 0;
187 	int retval = 0, err = 0;
188 	u32 sr;
189 
190 	retval = pm_runtime_resume_and_get((struct device *)priv->rng.priv);
191 	if (retval)
192 		return retval;
193 
194 	if (readl_relaxed(priv->base + RNG_SR) & RNG_SR_SEIS)
195 		stm32_rng_conceal_seed_error(rng);
196 
197 	while (max >= sizeof(u32)) {
198 		sr = readl_relaxed(priv->base + RNG_SR);
199 		/*
200 		 * Manage timeout which is based on timer and take
201 		 * care of initial delay time when enabling the RNG.
202 		 */
203 		if (!sr && wait) {
204 			err = readl_relaxed_poll_timeout_atomic(priv->base
205 								   + RNG_SR,
206 								   sr, sr,
207 								   10, 50000);
208 			if (err) {
209 				dev_err((struct device *)priv->rng.priv,
210 					"%s: timeout %x!\n", __func__, sr);
211 				break;
212 			}
213 		} else if (!sr) {
214 			/* The FIFO is being filled up */
215 			break;
216 		}
217 
218 		if (sr != RNG_SR_DRDY) {
219 			if (sr & RNG_SR_SEIS) {
220 				err = stm32_rng_conceal_seed_error(rng);
221 				i++;
222 				if (err && i > RNG_NB_RECOVER_TRIES) {
223 					dev_err((struct device *)priv->rng.priv,
224 						"Couldn't recover from seed error\n");
225 					retval = -ENOTRECOVERABLE;
226 					goto exit_rpm;
227 				}
228 
229 				continue;
230 			}
231 
232 			if (WARN_ONCE((sr & RNG_SR_CEIS), "RNG clock too slow - %x\n", sr))
233 				writel_relaxed(0, priv->base + RNG_SR);
234 		}
235 
236 		/* Late seed error case: DR being 0 is an error status */
237 		*(u32 *)data = readl_relaxed(priv->base + RNG_DR);
238 		if (!*(u32 *)data) {
239 			err = stm32_rng_conceal_seed_error(rng);
240 			i++;
241 			if (err && i > RNG_NB_RECOVER_TRIES) {
242 				dev_err((struct device *)priv->rng.priv,
243 					"Couldn't recover from seed error");
244 				retval = -ENOTRECOVERABLE;
245 				goto exit_rpm;
246 			}
247 
248 			continue;
249 		}
250 
251 		i = 0;
252 		retval += sizeof(u32);
253 		data += sizeof(u32);
254 		max -= sizeof(u32);
255 	}
256 
257 exit_rpm:
258 	pm_runtime_mark_last_busy((struct device *) priv->rng.priv);
259 	pm_runtime_put_sync_autosuspend((struct device *) priv->rng.priv);
260 
261 	return retval || !wait ? retval : -EIO;
262 }
263 
264 static uint stm32_rng_clock_freq_restrain(struct hwrng *rng)
265 {
266 	struct stm32_rng_private *priv =
267 	    container_of(rng, struct stm32_rng_private, rng);
268 	unsigned long clock_rate = 0;
269 	uint clock_div = 0;
270 
271 	clock_rate = clk_get_rate(priv->clk);
272 
273 	/*
274 	 * Get the exponent to apply on the CLKDIV field in RNG_CR register
275 	 * No need to handle the case when clock-div > 0xF as it is physically
276 	 * impossible
277 	 */
278 	while ((clock_rate >> clock_div) > priv->data->max_clock_rate)
279 		clock_div++;
280 
281 	pr_debug("RNG clk rate : %lu\n", clk_get_rate(priv->clk) >> clock_div);
282 
283 	return clock_div;
284 }
285 
286 static int stm32_rng_init(struct hwrng *rng)
287 {
288 	struct stm32_rng_private *priv =
289 	    container_of(rng, struct stm32_rng_private, rng);
290 	int err;
291 	u32 reg;
292 
293 	err = clk_prepare_enable(priv->clk);
294 	if (err)
295 		return err;
296 
297 	/* clear error indicators */
298 	writel_relaxed(0, priv->base + RNG_SR);
299 
300 	reg = readl_relaxed(priv->base + RNG_CR);
301 
302 	/*
303 	 * Keep default RNG configuration if none was specified.
304 	 * 0 is an invalid value as it disables all entropy sources.
305 	 */
306 	if (priv->data->has_cond_reset && priv->data->cr) {
307 		uint clock_div = stm32_rng_clock_freq_restrain(rng);
308 
309 		reg &= ~RNG_CR_CONFIG_MASK;
310 		reg |= RNG_CR_CONDRST | (priv->data->cr & RNG_CR_ENTROPY_SRC_MASK) |
311 		       (clock_div << RNG_CR_CLKDIV_SHIFT);
312 		if (priv->ced)
313 			reg &= ~RNG_CR_CED;
314 		else
315 			reg |= RNG_CR_CED;
316 		writel_relaxed(reg, priv->base + RNG_CR);
317 
318 		/* Health tests and noise control registers */
319 		writel_relaxed(priv->data->htcr, priv->base + RNG_HTCR);
320 		writel_relaxed(priv->data->nscr & RNG_NSCR_MASK, priv->base + RNG_NSCR);
321 
322 		reg &= ~RNG_CR_CONDRST;
323 		reg |= RNG_CR_RNGEN;
324 		if (priv->lock_conf)
325 			reg |= RNG_CR_CONFLOCK;
326 
327 		writel_relaxed(reg, priv->base + RNG_CR);
328 
329 		err = readl_relaxed_poll_timeout_atomic(priv->base + RNG_CR, reg,
330 							(!(reg & RNG_CR_CONDRST)),
331 							10, 50000);
332 		if (err) {
333 			clk_disable_unprepare(priv->clk);
334 			dev_err((struct device *)priv->rng.priv,
335 				"%s: timeout %x!\n", __func__, reg);
336 			return -EINVAL;
337 		}
338 	} else {
339 		/* Handle all RNG versions by checking if conditional reset should be set */
340 		if (priv->data->has_cond_reset)
341 			reg |= RNG_CR_CONDRST;
342 
343 		if (priv->ced)
344 			reg &= ~RNG_CR_CED;
345 		else
346 			reg |= RNG_CR_CED;
347 
348 		writel_relaxed(reg, priv->base + RNG_CR);
349 
350 		if (priv->data->has_cond_reset)
351 			reg &= ~RNG_CR_CONDRST;
352 
353 		reg |= RNG_CR_RNGEN;
354 
355 		writel_relaxed(reg, priv->base + RNG_CR);
356 	}
357 
358 	err = readl_relaxed_poll_timeout_atomic(priv->base + RNG_SR, reg,
359 						reg & RNG_SR_DRDY,
360 						10, 100000);
361 	if (err || (reg & ~RNG_SR_DRDY)) {
362 		clk_disable_unprepare(priv->clk);
363 		dev_err((struct device *)priv->rng.priv,
364 			"%s: timeout:%x SR: %x!\n", __func__, err, reg);
365 		return -EINVAL;
366 	}
367 
368 	clk_disable_unprepare(priv->clk);
369 
370 	return 0;
371 }
372 
373 static void stm32_rng_remove(struct platform_device *ofdev)
374 {
375 	pm_runtime_disable(&ofdev->dev);
376 }
377 
378 static int __maybe_unused stm32_rng_runtime_suspend(struct device *dev)
379 {
380 	struct stm32_rng_private *priv = dev_get_drvdata(dev);
381 	u32 reg;
382 
383 	reg = readl_relaxed(priv->base + RNG_CR);
384 	reg &= ~RNG_CR_RNGEN;
385 	writel_relaxed(reg, priv->base + RNG_CR);
386 	clk_disable_unprepare(priv->clk);
387 
388 	return 0;
389 }
390 
391 static int __maybe_unused stm32_rng_suspend(struct device *dev)
392 {
393 	struct stm32_rng_private *priv = dev_get_drvdata(dev);
394 	int err;
395 
396 	err = clk_prepare_enable(priv->clk);
397 	if (err)
398 		return err;
399 
400 	if (priv->data->has_cond_reset) {
401 		priv->pm_conf.nscr = readl_relaxed(priv->base + RNG_NSCR);
402 		priv->pm_conf.htcr = readl_relaxed(priv->base + RNG_HTCR);
403 	}
404 
405 	/* Do not save that RNG is enabled as it will be handled at resume */
406 	priv->pm_conf.cr = readl_relaxed(priv->base + RNG_CR) & ~RNG_CR_RNGEN;
407 
408 	writel_relaxed(priv->pm_conf.cr, priv->base + RNG_CR);
409 
410 	clk_disable_unprepare(priv->clk);
411 
412 	return 0;
413 }
414 
415 static int __maybe_unused stm32_rng_runtime_resume(struct device *dev)
416 {
417 	struct stm32_rng_private *priv = dev_get_drvdata(dev);
418 	int err;
419 	u32 reg;
420 
421 	err = clk_prepare_enable(priv->clk);
422 	if (err)
423 		return err;
424 
425 	/* Clean error indications */
426 	writel_relaxed(0, priv->base + RNG_SR);
427 
428 	reg = readl_relaxed(priv->base + RNG_CR);
429 	reg |= RNG_CR_RNGEN;
430 	writel_relaxed(reg, priv->base + RNG_CR);
431 
432 	return 0;
433 }
434 
435 static int __maybe_unused stm32_rng_resume(struct device *dev)
436 {
437 	struct stm32_rng_private *priv = dev_get_drvdata(dev);
438 	int err;
439 	u32 reg;
440 
441 	err = clk_prepare_enable(priv->clk);
442 	if (err)
443 		return err;
444 
445 	/* Clean error indications */
446 	writel_relaxed(0, priv->base + RNG_SR);
447 
448 	if (priv->data->has_cond_reset) {
449 		/*
450 		 * Correct configuration in bits [29:4] must be set in the same
451 		 * access that set RNG_CR_CONDRST bit. Else config setting is
452 		 * not taken into account. CONFIGLOCK bit must also be unset but
453 		 * it is not handled at the moment.
454 		 */
455 		writel_relaxed(priv->pm_conf.cr | RNG_CR_CONDRST, priv->base + RNG_CR);
456 
457 		writel_relaxed(priv->pm_conf.nscr, priv->base + RNG_NSCR);
458 		writel_relaxed(priv->pm_conf.htcr, priv->base + RNG_HTCR);
459 
460 		reg = readl_relaxed(priv->base + RNG_CR);
461 		reg |= RNG_CR_RNGEN;
462 		reg &= ~RNG_CR_CONDRST;
463 		writel_relaxed(reg, priv->base + RNG_CR);
464 
465 		err = readl_relaxed_poll_timeout_atomic(priv->base + RNG_CR, reg,
466 							reg & ~RNG_CR_CONDRST, 10, 100000);
467 
468 		if (err) {
469 			clk_disable_unprepare(priv->clk);
470 			dev_err((struct device *)priv->rng.priv,
471 				"%s: timeout:%x CR: %x!\n", __func__, err, reg);
472 			return -EINVAL;
473 		}
474 	} else {
475 		reg = priv->pm_conf.cr;
476 		reg |= RNG_CR_RNGEN;
477 		writel_relaxed(reg, priv->base + RNG_CR);
478 	}
479 
480 	clk_disable_unprepare(priv->clk);
481 
482 	return 0;
483 }
484 
485 static const struct dev_pm_ops __maybe_unused stm32_rng_pm_ops = {
486 	SET_RUNTIME_PM_OPS(stm32_rng_runtime_suspend,
487 			   stm32_rng_runtime_resume, NULL)
488 	SET_SYSTEM_SLEEP_PM_OPS(stm32_rng_suspend,
489 				stm32_rng_resume)
490 };
491 
492 static const struct stm32_rng_data stm32mp13_rng_data = {
493 	.has_cond_reset = true,
494 	.max_clock_rate = 48000000,
495 	.cr = 0x00F00D00,
496 	.nscr = 0x2B5BB,
497 	.htcr = 0x969D,
498 };
499 
500 static const struct stm32_rng_data stm32_rng_data = {
501 	.has_cond_reset = false,
502 	.max_clock_rate = 3000000,
503 };
504 
505 static const struct of_device_id stm32_rng_match[] = {
506 	{
507 		.compatible = "st,stm32mp13-rng",
508 		.data = &stm32mp13_rng_data,
509 	},
510 	{
511 		.compatible = "st,stm32-rng",
512 		.data = &stm32_rng_data,
513 	},
514 	{},
515 };
516 MODULE_DEVICE_TABLE(of, stm32_rng_match);
517 
518 static int stm32_rng_probe(struct platform_device *ofdev)
519 {
520 	struct device *dev = &ofdev->dev;
521 	struct device_node *np = ofdev->dev.of_node;
522 	struct stm32_rng_private *priv;
523 	struct resource *res;
524 
525 	priv = devm_kzalloc(dev, sizeof(struct stm32_rng_private), GFP_KERNEL);
526 	if (!priv)
527 		return -ENOMEM;
528 
529 	priv->base = devm_platform_get_and_ioremap_resource(ofdev, 0, &res);
530 	if (IS_ERR(priv->base))
531 		return PTR_ERR(priv->base);
532 
533 	priv->clk = devm_clk_get(&ofdev->dev, NULL);
534 	if (IS_ERR(priv->clk))
535 		return PTR_ERR(priv->clk);
536 
537 	priv->rst = devm_reset_control_get(&ofdev->dev, NULL);
538 	if (!IS_ERR(priv->rst)) {
539 		reset_control_assert(priv->rst);
540 		udelay(2);
541 		reset_control_deassert(priv->rst);
542 	}
543 
544 	priv->ced = of_property_read_bool(np, "clock-error-detect");
545 	priv->lock_conf = of_property_read_bool(np, "st,rng-lock-conf");
546 
547 	priv->data = of_device_get_match_data(dev);
548 	if (!priv->data)
549 		return -ENODEV;
550 
551 	dev_set_drvdata(dev, priv);
552 
553 	priv->rng.name = dev_driver_string(dev);
554 	priv->rng.init = stm32_rng_init;
555 	priv->rng.read = stm32_rng_read;
556 	priv->rng.priv = (unsigned long) dev;
557 	priv->rng.quality = 900;
558 
559 	pm_runtime_set_autosuspend_delay(dev, 100);
560 	pm_runtime_use_autosuspend(dev);
561 	pm_runtime_enable(dev);
562 
563 	return devm_hwrng_register(dev, &priv->rng);
564 }
565 
566 static struct platform_driver stm32_rng_driver = {
567 	.driver = {
568 		.name = "stm32-rng",
569 		.pm = pm_ptr(&stm32_rng_pm_ops),
570 		.of_match_table = stm32_rng_match,
571 	},
572 	.probe = stm32_rng_probe,
573 	.remove_new = stm32_rng_remove,
574 };
575 
576 module_platform_driver(stm32_rng_driver);
577 
578 MODULE_LICENSE("GPL");
579 MODULE_AUTHOR("Daniel Thompson <daniel.thompson@linaro.org>");
580 MODULE_DESCRIPTION("STMicroelectronics STM32 RNG device driver");
581