summaryrefslogtreecommitdiff
path: root/src/lib/libc/stdlib/random.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/libc/stdlib/random.c')
-rw-r--r--src/lib/libc/stdlib/random.c434
1 files changed, 434 insertions, 0 deletions
diff --git a/src/lib/libc/stdlib/random.c b/src/lib/libc/stdlib/random.c
new file mode 100644
index 0000000000..49a5ed1c3e
--- /dev/null
+++ b/src/lib/libc/stdlib/random.c
@@ -0,0 +1,434 @@
1/*
2 * Copyright (c) 1983 Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if defined(LIBC_SCCS) && !defined(lint)
35static char *rcsid = "$OpenBSD: random.c,v 1.11 2003/02/28 21:27:44 millert Exp $";
36#endif /* LIBC_SCCS and not lint */
37
38#include <sys/param.h>
39#include <sys/sysctl.h>
40#include <sys/time.h>
41#include <fcntl.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <unistd.h>
45
46/*
47 * random.c:
48 *
49 * An improved random number generation package. In addition to the standard
50 * rand()/srand() like interface, this package also has a special state info
51 * interface. The initstate() routine is called with a seed, an array of
52 * bytes, and a count of how many bytes are being passed in; this array is
53 * then initialized to contain information for random number generation with
54 * that much state information. Good sizes for the amount of state
55 * information are 32, 64, 128, and 256 bytes. The state can be switched by
56 * calling the setstate() routine with the same array as was initiallized
57 * with initstate(). By default, the package runs with 128 bytes of state
58 * information and generates far better random numbers than a linear
59 * congruential generator. If the amount of state information is less than
60 * 32 bytes, a simple linear congruential R.N.G. is used.
61 *
62 * Internally, the state information is treated as an array of int32_t; the
63 * zeroeth element of the array is the type of R.N.G. being used (small
64 * integer); the remainder of the array is the state information for the
65 * R.N.G. Thus, 32 bytes of state information will give 7 int32_ts worth of
66 * state information, which will allow a degree seven polynomial. (Note:
67 * the zeroeth word of state information also has some other information
68 * stored in it -- see setstate() for details).
69 *
70 * The random number generation technique is a linear feedback shift register
71 * approach, employing trinomials (since there are fewer terms to sum up that
72 * way). In this approach, the least significant bit of all the numbers in
73 * the state table will act as a linear feedback shift register, and will
74 * have period 2^deg - 1 (where deg is the degree of the polynomial being
75 * used, assuming that the polynomial is irreducible and primitive). The
76 * higher order bits will have longer periods, since their values are also
77 * influenced by pseudo-random carries out of the lower bits. The total
78 * period of the generator is approximately deg*(2**deg - 1); thus doubling
79 * the amount of state information has a vast influence on the period of the
80 * generator. Note: the deg*(2**deg - 1) is an approximation only good for
81 * large deg, when the period of the shift register is the dominant factor.
82 * With deg equal to seven, the period is actually much longer than the
83 * 7*(2**7 - 1) predicted by this formula.
84 */
85
86/*
87 * For each of the currently supported random number generators, we have a
88 * break value on the amount of state information (you need at least this
89 * many bytes of state info to support this random number generator), a degree
90 * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
91 * the separation between the two lower order coefficients of the trinomial.
92 */
93#define TYPE_0 0 /* linear congruential */
94#define BREAK_0 8
95#define DEG_0 0
96#define SEP_0 0
97
98#define TYPE_1 1 /* x**7 + x**3 + 1 */
99#define BREAK_1 32
100#define DEG_1 7
101#define SEP_1 3
102
103#define TYPE_2 2 /* x**15 + x + 1 */
104#define BREAK_2 64
105#define DEG_2 15
106#define SEP_2 1
107
108#define TYPE_3 3 /* x**31 + x**3 + 1 */
109#define BREAK_3 128
110#define DEG_3 31
111#define SEP_3 3
112
113#define TYPE_4 4 /* x**63 + x + 1 */
114#define BREAK_4 256
115#define DEG_4 63
116#define SEP_4 1
117
118/*
119 * Array versions of the above information to make code run faster --
120 * relies on fact that TYPE_i == i.
121 */
122#define MAX_TYPES 5 /* max number of types above */
123
124static int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
125static int seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
126
127/*
128 * Initially, everything is set up as if from:
129 *
130 * initstate(1, &randtbl, 128);
131 *
132 * Note that this initialization takes advantage of the fact that srandom()
133 * advances the front and rear pointers 10*rand_deg times, and hence the
134 * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
135 * element of the state information, which contains info about the current
136 * position of the rear pointer is just
137 *
138 * MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
139 */
140
141static int32_t randtbl[DEG_3 + 1] = {
142 TYPE_3,
143 0x991539b1, 0x16a5bce3, 0x6774a4cd, 0x3e01511e, 0x4e508aaa, 0x61048c05,
144 0xf5500617, 0x846b7115, 0x6a19892c, 0x896a97af, 0xdb48f936, 0x14898454,
145 0x37ffd106, 0xb58bff9c, 0x59e17104, 0xcf918a49, 0x09378c83, 0x52c7a471,
146 0x8d293ea9, 0x1f4fc301, 0xc3db71be, 0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1,
147 0x19edc328, 0x87bf4bdd, 0xc9b240e5, 0xe9ee4b1b, 0x4382aee7, 0x535b6b41,
148 0xf3bec5da,
149};
150
151/*
152 * fptr and rptr are two pointers into the state info, a front and a rear
153 * pointer. These two pointers are always rand_sep places aparts, as they
154 * cycle cyclically through the state information. (Yes, this does mean we
155 * could get away with just one pointer, but the code for random() is more
156 * efficient this way). The pointers are left positioned as they would be
157 * from the call
158 *
159 * initstate(1, randtbl, 128);
160 *
161 * (The position of the rear pointer, rptr, is really 0 (as explained above
162 * in the initialization of randtbl) because the state table pointer is set
163 * to point to randtbl[1] (as explained below).
164 */
165static int32_t *fptr = &randtbl[SEP_3 + 1];
166static int32_t *rptr = &randtbl[1];
167
168/*
169 * The following things are the pointer to the state information table, the
170 * type of the current generator, the degree of the current polynomial being
171 * used, and the separation between the two pointers. Note that for efficiency
172 * of random(), we remember the first location of the state information, not
173 * the zeroeth. Hence it is valid to access state[-1], which is used to
174 * store the type of the R.N.G. Also, we remember the last location, since
175 * this is more efficient than indexing every time to find the address of
176 * the last element to see if the front and rear pointers have wrapped.
177 */
178static int32_t *state = &randtbl[1];
179static int32_t *end_ptr = &randtbl[DEG_3 + 1];
180static int rand_type = TYPE_3;
181static int rand_deg = DEG_3;
182static int rand_sep = SEP_3;
183
184/*
185 * srandom:
186 *
187 * Initialize the random number generator based on the given seed. If the
188 * type is the trivial no-state-information type, just remember the seed.
189 * Otherwise, initializes state[] based on the given "seed" via a linear
190 * congruential generator. Then, the pointers are set to known locations
191 * that are exactly rand_sep places apart. Lastly, it cycles the state
192 * information a given number of times to get rid of any initial dependencies
193 * introduced by the L.C.R.N.G. Note that the initialization of randtbl[]
194 * for default usage relies on values produced by this routine.
195 */
196void
197srandom(x)
198 unsigned int x;
199{
200 int i;
201 int32_t test;
202 div_t val;
203
204 if (rand_type == TYPE_0)
205 state[0] = x;
206 else {
207 state[0] = x;
208 for (i = 1; i < rand_deg; i++) {
209 /*
210 * Implement the following, without overflowing 31 bits:
211 *
212 * state[i] = (16807 * state[i - 1]) % 2147483647;
213 *
214 * 2^31-1 (prime) = 2147483647 = 127773*16807+2836
215 */
216 val = div(state[i-1], 127773);
217 test = 16807 * val.rem - 2836 * val.quot;
218 state[i] = test + (test < 0 ? 2147483647 : 0);
219 }
220 fptr = &state[rand_sep];
221 rptr = &state[0];
222 for (i = 0; i < 10 * rand_deg; i++)
223 (void)random();
224 }
225}
226
227/*
228 * srandomdev:
229 *
230 * Many programs choose the seed value in a totally predictable manner.
231 * This often causes problems. We seed the generator using the much more
232 * secure arandom(4) interface. Note that this particular seeding
233 * procedure can generate states which are impossible to reproduce by
234 * calling srandom() with any value, since the succeeding terms in the
235 * state buffer are no longer derived from the LC algorithm applied to
236 * a fixed seed.
237 */
238void
239srandomdev()
240{
241 int fd, i, mib[2], n;
242 size_t len;
243
244 if (rand_type == TYPE_0)
245 len = sizeof(state[0]);
246 else
247 len = rand_deg * sizeof(state[0]);
248
249 /*
250 * To get seed data, first try reading from /dev/arandom.
251 * If that fails, try the KERN_ARND sysctl() (one int at a time).
252 * As a last resort, call srandom().
253 */
254 if ((fd = open("/dev/arandom", O_RDONLY, 0)) != -1 &&
255 read(fd, (void *) state, len) == (ssize_t) len) {
256 close(fd);
257 } else {
258 if (fd != -1)
259 close(fd);
260 mib[0] = CTL_KERN;
261 mib[1] = KERN_ARND;
262 n = len / sizeof(int);
263 len = sizeof(int);
264 for (i = 0; i < n; i++) {
265 if (sysctl(mib, 2, (char *)((int *)state + i), &len,
266 NULL, 0) == -1)
267 break;
268 }
269 if (i != n) {
270 struct timeval tv;
271 u_int junk;
272
273 /* XXX - this could be better */
274 gettimeofday(&tv, NULL);
275 srandom(getpid() ^ tv.tv_sec ^ tv.tv_usec ^ junk);
276 return;
277 }
278 }
279
280 if (rand_type != TYPE_0) {
281 fptr = &state[rand_sep];
282 rptr = &state[0];
283 }
284}
285
286/*
287 * initstate:
288 *
289 * Initialize the state information in the given array of n bytes for future
290 * random number generation. Based on the number of bytes we are given, and
291 * the break values for the different R.N.G.'s, we choose the best (largest)
292 * one we can and set things up for it. srandom() is then called to
293 * initialize the state information.
294 *
295 * Note that on return from srandom(), we set state[-1] to be the type
296 * multiplexed with the current value of the rear pointer; this is so
297 * successive calls to initstate() won't lose this information and will be
298 * able to restart with setstate().
299 *
300 * Note: the first thing we do is save the current state, if any, just like
301 * setstate() so that it doesn't matter when initstate is called.
302 *
303 * Returns a pointer to the old state.
304 */
305char *
306initstate(seed, arg_state, n)
307 u_int seed; /* seed for R.N.G. */
308 char *arg_state; /* pointer to state array */
309 size_t n; /* # bytes of state info */
310{
311 char *ostate = (char *)(&state[-1]);
312
313 if (rand_type == TYPE_0)
314 state[-1] = rand_type;
315 else
316 state[-1] = MAX_TYPES * (rptr - state) + rand_type;
317 if (n < BREAK_0)
318 return(NULL);
319 if (n < BREAK_1) {
320 rand_type = TYPE_0;
321 rand_deg = DEG_0;
322 rand_sep = SEP_0;
323 } else if (n < BREAK_2) {
324 rand_type = TYPE_1;
325 rand_deg = DEG_1;
326 rand_sep = SEP_1;
327 } else if (n < BREAK_3) {
328 rand_type = TYPE_2;
329 rand_deg = DEG_2;
330 rand_sep = SEP_2;
331 } else if (n < BREAK_4) {
332 rand_type = TYPE_3;
333 rand_deg = DEG_3;
334 rand_sep = SEP_3;
335 } else {
336 rand_type = TYPE_4;
337 rand_deg = DEG_4;
338 rand_sep = SEP_4;
339 }
340 state = &(((int32_t *)arg_state)[1]); /* first location */
341 end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */
342 srandom(seed);
343 if (rand_type == TYPE_0)
344 state[-1] = rand_type;
345 else
346 state[-1] = MAX_TYPES*(rptr - state) + rand_type;
347 return(ostate);
348}
349
350/*
351 * setstate:
352 *
353 * Restore the state from the given state array.
354 *
355 * Note: it is important that we also remember the locations of the pointers
356 * in the current state information, and restore the locations of the pointers
357 * from the old state information. This is done by multiplexing the pointer
358 * location into the zeroeth word of the state information.
359 *
360 * Note that due to the order in which things are done, it is OK to call
361 * setstate() with the same state as the current state.
362 *
363 * Returns a pointer to the old state information.
364 */
365char *
366setstate(arg_state)
367 const char *arg_state;
368{
369 int32_t *new_state = (int32_t *)arg_state;
370 int32_t type = new_state[0] % MAX_TYPES;
371 int32_t rear = new_state[0] / MAX_TYPES;
372 char *ostate = (char *)(&state[-1]);
373
374 if (rand_type == TYPE_0)
375 state[-1] = rand_type;
376 else
377 state[-1] = MAX_TYPES * (rptr - state) + rand_type;
378 switch(type) {
379 case TYPE_0:
380 case TYPE_1:
381 case TYPE_2:
382 case TYPE_3:
383 case TYPE_4:
384 rand_type = type;
385 rand_deg = degrees[type];
386 rand_sep = seps[type];
387 break;
388 default:
389 return(NULL);
390 }
391 state = &new_state[1];
392 if (rand_type != TYPE_0) {
393 rptr = &state[rear];
394 fptr = &state[(rear + rand_sep) % rand_deg];
395 }
396 end_ptr = &state[rand_deg]; /* set end_ptr too */
397 return(ostate);
398}
399
400/*
401 * random:
402 *
403 * If we are using the trivial TYPE_0 R.N.G., just do the old linear
404 * congruential bit. Otherwise, we do our fancy trinomial stuff, which is
405 * the same in all the other cases due to all the global variables that have
406 * been set up. The basic operation is to add the number at the rear pointer
407 * into the one at the front pointer. Then both pointers are advanced to
408 * the next location cyclically in the table. The value returned is the sum
409 * generated, reduced to 31 bits by throwing away the "least random" low bit.
410 *
411 * Note: the code takes advantage of the fact that both the front and
412 * rear pointers can't wrap on the same call by not testing the rear
413 * pointer if the front one has wrapped.
414 *
415 * Returns a 31-bit random number.
416 */
417long
418random()
419{
420 int32_t i;
421
422 if (rand_type == TYPE_0)
423 i = state[0] = (state[0] * 1103515245 + 12345) & 0x7fffffff;
424 else {
425 *fptr += *rptr;
426 i = (*fptr >> 1) & 0x7fffffff; /* chucking least random bit */
427 if (++fptr >= end_ptr) {
428 fptr = state;
429 ++rptr;
430 } else if (++rptr >= end_ptr)
431 rptr = state;
432 }
433 return((long)i);
434}