[RFC/RFT PATCH 3/6] random: Use u32 to keep track of batched entropy generation

Ard Biesheuvel
2025-11-27T09:22:57Z

From: Ard Biesheuvel <ardb@kernel.org>

The batched entropy containers each have a generation field, to keep
track of the base_crng generation from which it was last reseeded.

This use case does not require all bits of the unsigned long to be
stored: storing only 32 bits is sufficient to determine whether or not
we're at most 4 billion generations behind, which seems ample.

So use an unsigned int instead: this will allow a future patch to treat
the generation and position as a single 64-bit quantity, which can be
used locklessly in a compare-and-exchange() operation.

Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
---
drivers/char/random.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/drivers/char/random.c b/drivers/char/random.c
index b8b24b6ed3fe..0e04bc60d034 100644
--- a/drivers/char/random.c
+++ b/drivers/char/random.c
@@ -507,7 +507,7 @@ struct batch_ ##type { \
*/ \
type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))]; \
local_lock_t lock; \
- unsigned long generation; \
+ unsigned int generation; \
unsigned int position; \
}; \
\
@@ -521,7 +521,7 @@ type get_random_ ##type(void) \
type ret; \
unsigned long flags; \
struct batch_ ##type *batch; \
- unsigned long next_gen; \
+ unsigned int next_gen; \
\
warn_unseeded_randomness(); \
\
@@ -533,7 +533,7 @@ type get_random_ ##type(void) \
local_lock_irqsave(&batched_entropy_ ##type.lock, flags); \
batch = raw_cpu_ptr(&batched_entropy_##type); \
\
- next_gen = READ_ONCE(base_crng.generation); \
+ next_gen = (unsigned int)READ_ONCE(base_crng.generation); \
if (batch->position >= ARRAY_SIZE(batch->entropy) || \
next_gen != batch->generation) { \
_get_random_bytes(batch->entropy, sizeof(batch->entropy)); \
--
2.52.0.107.ga0afd4fd5b-goog