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
59static void __set_random32(struct rnd_state *state, unsigned long s)
60{
61 if (s == 0)
62 s = 1;
63
64#define LCG(n) (69069 * n)
65 state->s1 = LCG(s);
66 state->s2 = LCG(state->s1);
67 state->s3 = LCG(state->s2);
68
69
70 __random32(state);
71 __random32(state);
72 __random32(state);
73 __random32(state);
74 __random32(state);
75 __random32(state);
76}
77
78
79
80
81
82
83
84
85u32 random32(void)
86{
87 unsigned long r;
88 struct rnd_state *state = &get_cpu_var(net_rand_state);
89 r = __random32(state);
90 put_cpu_var(state);
91 return r;
92}
93EXPORT_SYMBOL(random32);
94
95
96
97
98
99
100
101
102void srandom32(u32 entropy)
103{
104 struct rnd_state *state = &get_cpu_var(net_rand_state);
105 __set_random32(state, state->s1 ^ entropy);
106 put_cpu_var(state);
107}
108EXPORT_SYMBOL(srandom32);
109
110
111
112
113
114static int __init random32_init(void)
115{
116 int i;
117
118 for_each_possible_cpu(i) {
119 struct rnd_state *state = &per_cpu(net_rand_state,i);
120 __set_random32(state, i + jiffies);
121 }
122 return 0;
123}
124core_initcall(random32_init);
125
126
127
128
129
130static int __init random32_reseed(void)
131{
132 int i;
133 unsigned long seed;
134
135 for_each_possible_cpu(i) {
136 struct rnd_state *state = &per_cpu(net_rand_state,i);
137
138 get_random_bytes(&seed, sizeof(seed));
139 __set_random32(state, seed);
140 }
141 return 0;
142}
143late_initcall(random32_reseed);
144