2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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.
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. */
34 /* Current random state. */
37 static uint32_t random_next(void);
45 if (gettimeofday(&tv, NULL) < 0) {
46 ovs_fatal(errno, "gettimeofday");
49 seed = tv.tv_sec ^ tv.tv_usec;
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);
59 random_bytes(void *p_, size_t n)
65 for (; n > 4; p += 4, n -= 4) {
66 uint32_t x = random_next();
71 uint32_t x = random_next();
79 return random_uint32();
85 return random_uint32();
98 return random_uint32() % max;