prandom.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __TOOLS_LINUX_PRANDOM_H
  3. #define __TOOLS_LINUX_PRANDOM_H
  4. #include <linux/types.h>
  5. struct rnd_state {
  6. __u32 s1, s2, s3, s4;
  7. };
  8. /*
  9. * Handle minimum values for seeds
  10. */
  11. static inline u32 __seed(u32 x, u32 m)
  12. {
  13. return (x < m) ? x + m : x;
  14. }
  15. /**
  16. * prandom_seed_state - set seed for prandom_u32_state().
  17. * @state: pointer to state structure to receive the seed.
  18. * @seed: arbitrary 64-bit value to use as a seed.
  19. */
  20. static inline void prandom_seed_state(struct rnd_state *state, u64 seed)
  21. {
  22. u32 i = ((seed >> 32) ^ (seed << 10) ^ seed) & 0xffffffffUL;
  23. state->s1 = __seed(i, 2U);
  24. state->s2 = __seed(i, 8U);
  25. state->s3 = __seed(i, 16U);
  26. state->s4 = __seed(i, 128U);
  27. }
  28. /**
  29. * prandom_u32_state - seeded pseudo-random number generator.
  30. * @state: pointer to state structure holding seeded state.
  31. *
  32. * This is used for pseudo-randomness with no outside seeding.
  33. * For more random results, use get_random_u32().
  34. */
  35. static inline u32 prandom_u32_state(struct rnd_state *state)
  36. {
  37. #define TAUSWORTHE(s, a, b, c, d) (((s & c) << d) ^ (((s << a) ^ s) >> b))
  38. state->s1 = TAUSWORTHE(state->s1, 6U, 13U, 4294967294U, 18U);
  39. state->s2 = TAUSWORTHE(state->s2, 2U, 27U, 4294967288U, 2U);
  40. state->s3 = TAUSWORTHE(state->s3, 13U, 21U, 4294967280U, 7U);
  41. state->s4 = TAUSWORTHE(state->s4, 3U, 12U, 4294967168U, 13U);
  42. return (state->s1 ^ state->s2 ^ state->s3 ^ state->s4);
  43. }
  44. #endif // __TOOLS_LINUX_PRANDOM_H