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