initscript: pass complete path to pidfile to status command
[sliver-openvswitch.git] / lib / random.c
1 /*
2  * Copyright (c) 2008, 2009 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 void
27 random_init(void)
28 {
29     static bool inited = false;
30     if (!inited) {
31         struct timeval tv;
32         inited = true;
33         if (gettimeofday(&tv, NULL) < 0) {
34             ovs_fatal(errno, "gettimeofday");
35         }
36         srand(tv.tv_sec ^ tv.tv_usec);
37     }
38 }
39
40 void
41 random_bytes(void *p_, size_t n)
42 {
43     uint8_t *p = p_;
44     random_init();
45     while (n--) {
46         *p++ = rand();
47     }
48 }
49
50 uint8_t
51 random_uint8(void)
52 {
53     random_init();
54     return rand();
55 }
56
57 uint16_t
58 random_uint16(void)
59 {
60     if (RAND_MAX >= UINT16_MAX) {
61         random_init();
62         return rand();
63     } else {
64         uint16_t x;
65         random_bytes(&x, sizeof x);
66         return x;
67     }
68 }
69
70 uint32_t
71 random_uint32(void)
72 {
73     if (RAND_MAX >= UINT32_MAX) {
74         random_init();
75         return rand();
76     } else if (RAND_MAX == INT32_MAX) {
77         random_init();
78         return rand() | ((rand() & 1u) << 31);
79     } else {
80         uint32_t x;
81         random_bytes(&x, sizeof x);
82         return x;
83     }
84 }
85
86 int
87 random_range(int max) 
88 {
89     return random_uint32() % max;
90 }