1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#include <linux/types.h>
37#include <linux/percpu.h>
38#include <linux/module.h>
39#include <linux/jiffies.h>
40#include <linux/random.h>
41
42struct rnd_state {
43 u32 s1, s2, s3;
44};
45
46static DEFINE_PER_CPU(struct rnd_state, net_rand_state);
47
48static u32 __random32(struct rnd_state *state)
49{
50#define TAUSWORTHE(s,a,b,c,d) ((s&c)<<d) ^ (((s <<a) ^ s)>>b)
51
52 state->s1 = TAUSWORTHE(state->s1, 13, 19, 4294967294UL, 12);
53 state->s2 = TAUSWORTHE(state->s2, 2, 25, 4294967288UL, 4);
54 state->s3 = TAUSWORTHE(state->s3, 3, 11, 4294967280UL, 17);
55
56 return (state->s1 ^ state->s2 ^ state->s3);
57}
58
59
60
61
62static inline u32 __seed(u32 x, u32 m)
63{
64 return (x < m) ? x + m : x;
65}
66
67
68
69
70
71
72
73
74u32 random32(void)
75{
76 unsigned long r;
77 struct rnd_state *state = &get_cpu_var(net_rand_state);
78 r = __random32(state);
79 put_cpu_var(state);
80 return r;
81}
82EXPORT_SYMBOL(random32);
83
84
85
86
87
88
89
90void srandom32(u32 entropy)
91{
92 int i;
93
94
95
96
97 for_each_possible_cpu (i) {
98 struct rnd_state *state = &per_cpu(net_rand_state, i);
99 state->s1 = __seed(state->s1 ^ entropy, 1);
100 }
101}
102EXPORT_SYMBOL(srandom32);
103
104
105
106
107
108static int __init random32_init(void)
109{
110 int i;
111
112 for_each_possible_cpu(i) {
113 struct rnd_state *state = &per_cpu(net_rand_state,i);
114
115#define LCG(x) ((x) * 69069)
116 state->s1 = __seed(LCG(i + jiffies), 1);
117 state->s2 = __seed(LCG(state->s1), 7);
118 state->s3 = __seed(LCG(state->s2), 15);
119
120
121 __random32(state);
122 __random32(state);
123 __random32(state);
124 __random32(state);
125 __random32(state);
126 __random32(state);
127 }
128 return 0;
129}
130core_initcall(random32_init);
131
132
133
134
135
136static int __init random32_reseed(void)
137{
138 int i;
139
140 for_each_possible_cpu(i) {
141 struct rnd_state *state = &per_cpu(net_rand_state,i);
142 u32 seeds[3];
143
144 get_random_bytes(&seeds, sizeof(seeds));
145 state->s1 = __seed(seeds[0], 1);
146 state->s2 = __seed(seeds[1], 7);
147 state->s3 = __seed(seeds[2], 15);
148
149
150 __random32(state);
151 }
152 return 0;
153}
154late_initcall(random32_reseed);
155