random: Implement a decent random number generator.
[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 <errno.h>
21 #include <stdlib.h>
22 #include <sys/time.h>
23
24 #include "util.h"
25
26 /* This is the 32-bit PRNG recommended in G. Marsaglia, "Xorshift RNGs",
27  * _Journal of Statistical Software_ 8:14 (July 2003).  According to the paper,
28  * it has a period of 2**32 - 1 and passes almost all tests of randomness.
29  *
30  * We use this PRNG instead of libc's rand() because rand() varies in quality
31  * and because its maximum value also varies between 32767 and INT_MAX, whereas
32  * we often want random numbers in the full range of uint32_t.  */
33
34 /* Current random state. */
35 static uint32_t seed;
36
37 static uint32_t random_next(void);
38
39 void
40 random_init(void)
41 {
42     if (!seed) {
43         struct timeval tv;
44
45         if (gettimeofday(&tv, NULL) < 0) {
46             ovs_fatal(errno, "gettimeofday");
47         }
48
49         seed = tv.tv_sec ^ tv.tv_usec;
50         if (!seed) {
51             /* A 'seed' of 0 is fatal to randomness--the random value will
52              * always be 0--so use the initial seed mentioned by Marsaglia. */
53             seed = UINT32_C(2463534242);
54         }
55     }
56 }
57
58 void
59 random_bytes(void *p_, size_t n)
60 {
61     uint8_t *p = p_;
62
63     random_init();
64
65     for (; n > 4; p += 4, n -= 4) {
66         uint32_t x = random_next();
67         memcpy(p, &x, 4);
68     }
69
70     if (n) {
71         uint32_t x = random_next();
72         memcpy(p, &x, n);
73     }
74 }
75
76 uint8_t
77 random_uint8(void)
78 {
79     return random_uint32();
80 }
81
82 uint16_t
83 random_uint16(void)
84 {
85     return random_uint32();
86 }
87
88 uint32_t
89 random_uint32(void)
90 {
91     random_init();
92     return random_next();
93 }
94
95 int
96 random_range(int max)
97 {
98     return random_uint32() % max;
99 }
100
101 static uint32_t
102 random_next(void)
103 {
104     seed ^= seed << 13;
105     seed >>= 17;
106     seed ^= seed << 5;
107
108     return seed;
109 }