6b02446014e1f71eb778f3c047fe43ee563ee6f2
[sliver-openvswitch.git] / lib / random.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "random.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <sys/time.h>
24
25 #include "entropy.h"
26 #include "util.h"
27
28 /* This is the 32-bit PRNG recommended in G. Marsaglia, "Xorshift RNGs",
29  * _Journal of Statistical Software_ 8:14 (July 2003).  According to the paper,
30  * it has a period of 2**32 - 1 and passes almost all tests of randomness.
31  *
32  * We use this PRNG instead of libc's rand() because rand() varies in quality
33  * and because its maximum value also varies between 32767 and INT_MAX, whereas
34  * we often want random numbers in the full range of uint32_t.
35  *
36  * This random number generator is intended for purposes that do not require
37  * cryptographic-quality randomness. */
38
39 /* Current random state. */
40 static uint32_t seed;
41
42 static uint32_t random_next(void);
43
44 void
45 random_init(void)
46 {
47     while (!seed) {
48         struct timeval tv;
49         uint32_t entropy;
50
51         if (gettimeofday(&tv, NULL) < 0) {
52             ovs_fatal(errno, "gettimeofday");
53         }
54         get_entropy_or_die(&entropy, 4);
55
56         seed = tv.tv_sec ^ tv.tv_usec ^ entropy;
57     }
58 }
59
60 void
61 random_set_seed(uint32_t seed_)
62 {
63     assert(seed_);
64     seed = seed_;
65 }
66
67 void
68 random_bytes(void *p_, size_t n)
69 {
70     uint8_t *p = p_;
71
72     random_init();
73
74     for (; n > 4; p += 4, n -= 4) {
75         uint32_t x = random_next();
76         memcpy(p, &x, 4);
77     }
78
79     if (n) {
80         uint32_t x = random_next();
81         memcpy(p, &x, n);
82     }
83 }
84
85 uint8_t
86 random_uint8(void)
87 {
88     return random_uint32();
89 }
90
91 uint16_t
92 random_uint16(void)
93 {
94     return random_uint32();
95 }
96
97 uint32_t
98 random_uint32(void)
99 {
100     random_init();
101     return random_next();
102 }
103
104 int
105 random_range(int max)
106 {
107     return random_uint32() % max;
108 }
109
110 static uint32_t
111 random_next(void)
112 {
113     seed ^= seed << 13;
114     seed ^= seed >> 17;
115     seed ^= seed << 5;
116
117     return seed;
118 }