[PATCH 2/4] clock: always seed Xorshift* from clocksource on startup

Ahmad Fatoum a.fatoum at pengutronix.de
Wed Apr 16 23:58:44 PDT 2025


We currently seed the RNG at following places:

  - ubiformat with get_time_ns()
  - MAC address randomization with get_time_ns()
  - seed and nandtest commands retrieve seed via command line

The latter needs to remain to make tests reproducible, but for general
use, let's collect the initial cycle count at clocksource registration
time and feed that to the PRNG.

Additional entropy can be mixed via the same interface at a later time.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 common/clock.c | 3 +++
 lib/random.c   | 2 +-
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/common/clock.c b/common/clock.c
index b300e5798a16..8d00edca4651 100644
--- a/common/clock.c
+++ b/common/clock.c
@@ -14,6 +14,7 @@
 #include <linux/math64.h>
 #include <clock.h>
 #include <sched.h>
+#include <stdlib.h>
 
 static uint64_t time_ns;
 
@@ -224,5 +225,7 @@ int init_clock(struct clocksource *cs)
 	cs->cycle_last = cs->read() & cs->mask;
 	current_clock = cs;
 
+	srand_xor(cs->cycle_last);
+
 	return 0;
 }
diff --git a/lib/random.c b/lib/random.c
index fc4ecdfd3a1d..51c68dcd427b 100644
--- a/lib/random.c
+++ b/lib/random.c
@@ -2,7 +2,7 @@
 /*
  * The barebox random number generator provides mainly two APIs:
  *
- *   - get_noncrypto_bytes: Xorshift*
+ *   - get_noncrypto_bytes: Xorshift* seeded initially with the cycle counter
  *     - https://en.wikipedia.org/wiki/Xorshift#xorshift*)
  *     - https://forum.pjrc.com/index.php?threads/teensy-4-1-random-number-generator.61125/#post-243895
  *
-- 
2.39.5




More information about the barebox mailing list