1 From 3537a855e3858b1f8b6cee545a22b8b67037235c Mon Sep 17 00:00:00 2001
2 From: Phil Elwell <phil@raspberrypi.com>
3 Date: Wed, 22 Mar 2023 15:30:38 +0000
4 Subject: [PATCH] hwrng: bcm2835 - sleep more intelligently
6 While waiting for random data, use sleeps that are proportional
7 to the amount of data expected. Prevent indefinite waits by
8 giving up if nothing is received for a second.
10 See: https://github.com/raspberrypi/linux/issues/5390
12 Signed-off-by: Phil Elwell <phil@raspberrypi.com>
14 drivers/char/hw_random/bcm2835-rng.c | 20 ++++++++++++++------
15 1 file changed, 14 insertions(+), 6 deletions(-)
17 --- a/drivers/char/hw_random/bcm2835-rng.c
18 +++ b/drivers/char/hw_random/bcm2835-rng.c
20 #include <linux/printk.h>
21 #include <linux/clk.h>
22 #include <linux/reset.h>
23 +#include <linux/delay.h>
26 #define RNG_STATUS 0x4
29 #define RNG_INT_OFF 0x1
31 +#define RNG_FIFO_WORDS 4
32 +#define RNG_US_PER_WORD 34 /* Tuned for throughput */
34 struct bcm2835_rng_priv {
37 @@ -64,19 +68,23 @@ static inline void rng_writel(struct bcm
38 static int bcm2835_rng_read(struct hwrng *rng, void *buf, size_t max,
41 + u32 retries = 1000000/(RNG_FIFO_WORDS * RNG_US_PER_WORD);
42 struct bcm2835_rng_priv *priv = to_rng_priv(rng);
43 u32 max_words = max / sizeof(u32);
46 - while ((rng_readl(priv, RNG_STATUS) >> 24) == 0) {
48 + num_words = rng_readl(priv, RNG_STATUS) >> 24;
50 + while (!num_words) {
51 + if (!wait || !retries)
55 + usleep_range((u32)RNG_US_PER_WORD,
56 + (u32)RNG_US_PER_WORD * RNG_FIFO_WORDS);
57 + num_words = rng_readl(priv, RNG_STATUS) >> 24;
60 - num_words = rng_readl(priv, RNG_STATUS) >> 24;
61 - if (num_words > max_words)
62 - num_words = max_words;
63 + num_words = min(num_words, max_words);
65 for (count = 0; count < num_words; count++)
66 ((u32 *)buf)[count] = rng_readl(priv, RNG_DATA);