Skip to contentSkip to conversation

lib/random32.c: Change to SFC32 PRNG

RFC PATCH In review George Spelvin 1 participant 1 message Mar 28, 2020

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

RFC PATCH 21/50 lib/random32.c: Change to SFC32 PRNG

Compared to lfsr113, this is faster, smaller code, has a full 128 bits of state, and better statistical properties on its output.

Because it has a (non-invertible) "chaotic" pseudorandom function component, it has a 2^-k chance of being in a a state with period less than 2^(128-k), so the average period is 2^127, and the chance of a period shorter than 2^113 is 1/32768.

It has an absolute minimum worst-case period of 2^32, which is still plenty to last 80 seconds between reseedings.

An alternative xoshiro128** implementation (similar size and speed, almost as strong, period 2^128 - 1) is provided as well. This is primarily for pre-merge discussion, but could be left in permanently if people want.

I'm not sure the self-test is worth keeping, as I had to generate the test vectors myself. But for now it's there, although simplified: each test's seed and number of iterations is taken from the previous test.

Cc Daniel Borkmann <[email protected]>
Cc Stephen Hemminger <[email protected]>
Cc Hannes Frederic Sowa <[email protected]>
---
 include/linux/random.h |  16 +-
 lib/random32.c         | 417 +++++++++++++++++++++--------------------
 2 files changed, 219 insertions(+), 214 deletions(-)
include/linux/random.h +4 -12
index 82dd0d613e75c..9e30f0bb3e50b 100644
@@ -115,7 +115,7 @@ void prandom_seed(u32 seed);
 void prandom_reseed_late(void);
 
 struct rnd_state {
-	__u32 s1, s2, s3, s4;
+	__u32 s[4];
 };
 
 u32 prandom_u32_state(struct rnd_state *state);
@@ -206,27 +206,19 @@ static inline u32 prandom_u32_max(u32 range)
 	}
 }
 
-/*
- * Handle minimum values for seeds
- */
-static inline u32 __seed(u32 x, u32 m)
-{
-	return (x < m) ? x + m : x;
-}
+void prandom_seed_early(struct rnd_state *state, u32 seed, bool);
 
 /**
  * prandom_seed_state - set seed for prandom_u32_state().
  * @state: pointer to state structure to receive the seed.
  * @seed: arbitrary 64-bit value to use as a seed.
+ *        (only 32 bits are actually used)
  */
 static inline void prandom_seed_state(struct rnd_state *state, u64 seed)
 {
 	u32 i = (seed >> 32) ^ (seed << 10) ^ seed;
 
-	state->s1 = __seed(i,   2U);
-	state->s2 = __seed(i,   8U);
-	state->s3 = __seed(i,  16U);
-	state->s4 = __seed(i, 128U);
+	prandom_seed_early(state, i, false);
 }
 
 #ifdef CONFIG_ARCH_RANDOM
lib/random32.c +215 -202

506 lines not on this page · raw message

Signature · 1 line
2.26.0