xref: /freebsd/lib/libc/stdlib/random.c (revision 0b37c1590418417c894529d371800dfac71ef887)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if defined(LIBC_SCCS) && !defined(lint)
33 static char sccsid[] = "@(#)random.c	8.2 (Berkeley) 5/19/95";
34 #endif /* LIBC_SCCS and not lint */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "namespace.h"
39 #include <sys/param.h>
40 #include <sys/sysctl.h>
41 #include <errno.h>
42 #include <stdint.h>
43 #include <stdlib.h>
44 #include "un-namespace.h"
45 
46 #include "random.h"
47 
48 /*
49  * random.c:
50  *
51  * An improved random number generation package.  In addition to the standard
52  * rand()/srand() like interface, this package also has a special state info
53  * interface.  The initstate() routine is called with a seed, an array of
54  * bytes, and a count of how many bytes are being passed in; this array is
55  * then initialized to contain information for random number generation with
56  * that much state information.  Good sizes for the amount of state
57  * information are 32, 64, 128, and 256 bytes.  The state can be switched by
58  * calling the setstate() routine with the same array as was initiallized
59  * with initstate().  By default, the package runs with 128 bytes of state
60  * information and generates far better random numbers than a linear
61  * congruential generator.  If the amount of state information is less than
62  * 32 bytes, a simple linear congruential R.N.G. is used.
63  *
64  * Internally, the state information is treated as an array of uint32_t's; the
65  * zeroeth element of the array is the type of R.N.G. being used (small
66  * integer); the remainder of the array is the state information for the
67  * R.N.G.  Thus, 32 bytes of state information will give 7 ints worth of
68  * state information, which will allow a degree seven polynomial.  (Note:
69  * the zeroeth word of state information also has some other information
70  * stored in it -- see setstate() for details).
71  *
72  * The random number generation technique is a linear feedback shift register
73  * approach, employing trinomials (since there are fewer terms to sum up that
74  * way).  In this approach, the least significant bit of all the numbers in
75  * the state table will act as a linear feedback shift register, and will
76  * have period 2^deg - 1 (where deg is the degree of the polynomial being
77  * used, assuming that the polynomial is irreducible and primitive).  The
78  * higher order bits will have longer periods, since their values are also
79  * influenced by pseudo-random carries out of the lower bits.  The total
80  * period of the generator is approximately deg*(2**deg - 1); thus doubling
81  * the amount of state information has a vast influence on the period of the
82  * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
83  * large deg, when the period of the shift is the dominant factor.
84  * With deg equal to seven, the period is actually much longer than the
85  * 7*(2**7 - 1) predicted by this formula.
86  *
87  * Modified 28 December 1994 by Jacob S. Rosenberg.
88  * The following changes have been made:
89  * All references to the type u_int have been changed to unsigned long.
90  * All references to type int have been changed to type long.  Other
91  * cleanups have been made as well.  A warning for both initstate and
92  * setstate has been inserted to the effect that on Sparc platforms
93  * the 'arg_state' variable must be forced to begin on word boundaries.
94  * This can be easily done by casting a long integer array to char *.
95  * The overall logic has been left STRICTLY alone.  This software was
96  * tested on both a VAX and Sun SpacsStation with exactly the same
97  * results.  The new version and the original give IDENTICAL results.
98  * The new version is somewhat faster than the original.  As the
99  * documentation says:  "By default, the package runs with 128 bytes of
100  * state information and generates far better random numbers than a linear
101  * congruential generator.  If the amount of state information is less than
102  * 32 bytes, a simple linear congruential R.N.G. is used."  For a buffer of
103  * 128 bytes, this new version runs about 19 percent faster and for a 16
104  * byte buffer it is about 5 percent faster.
105  */
106 
107 /*
108  * For each of the currently supported random number generators, we have a
109  * break value on the amount of state information (you need at least this
110  * many bytes of state info to support this random number generator), a degree
111  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
112  * the separation between the two lower order coefficients of the trinomial.
113  */
114 #define	TYPE_0		0		/* linear congruential */
115 #define	BREAK_0		8
116 #define	DEG_0		0
117 #define	SEP_0		0
118 
119 #define	TYPE_1		1		/* x**7 + x**3 + 1 */
120 #define	BREAK_1		32
121 #define	DEG_1		7
122 #define	SEP_1		3
123 
124 #define	TYPE_2		2		/* x**15 + x + 1 */
125 #define	BREAK_2		64
126 #define	DEG_2		15
127 #define	SEP_2		1
128 
129 #define	TYPE_3		3		/* x**31 + x**3 + 1 */
130 #define	BREAK_3		128
131 #define	DEG_3		31
132 #define	SEP_3		3
133 
134 #define	TYPE_4		4		/* x**63 + x + 1 */
135 #define	BREAK_4		256
136 #define	DEG_4		63
137 #define	SEP_4		1
138 
139 /*
140  * Array versions of the above information to make code run faster --
141  * relies on fact that TYPE_i == i.
142  */
143 #define	MAX_TYPES	5		/* max number of types above */
144 
145 #define NSHUFF 50       /* to drop some "seed -> 1st value" linearity */
146 
147 static const int degrees[MAX_TYPES] =	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
148 static const int seps [MAX_TYPES] =	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
149 
150 /*
151  * Initially, everything is set up as if from:
152  *
153  *	initstate(1, randtbl, 128);
154  *
155  * Note that this initialization takes advantage of the fact that srandom()
156  * advances the front and rear pointers 10*rand_deg times, and hence the
157  * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
158  * element of the state information, which contains info about the current
159  * position of the rear pointer is just
160  *
161  *	MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
162  */
163 static struct __random_state implicit = {
164 	.rst_randtbl = {
165 		TYPE_3,
166 		0x2cf41758, 0x27bb3711, 0x4916d4d1, 0x7b02f59f, 0x9b8e28eb, 0xc0e80269,
167 		0x696f5c16, 0x878f1ff5, 0x52d9c07f, 0x916a06cd, 0xb50b3a20, 0x2776970a,
168 		0xee4eb2a6, 0xe94640ec, 0xb1d65612, 0x9d1ed968, 0x1043f6b7, 0xa3432a76,
169 		0x17eacbb9, 0x3c09e2eb, 0x4f8c2b3,  0x708a1f57, 0xee341814, 0x95d0e4d2,
170 		0xb06f216c, 0x8bd2e72e, 0x8f7c38d7, 0xcfc6a8fc, 0x2a59495,  0xa20d2a69,
171 		0xe29d12d1
172 	},
173 
174 	/*
175 	 * fptr and rptr are two pointers into the state info, a front and a rear
176 	 * pointer.  These two pointers are always rand_sep places aparts, as they
177 	 * cycle cyclically through the state information.  (Yes, this does mean we
178 	 * could get away with just one pointer, but the code for random() is more
179 	 * efficient this way).  The pointers are left positioned as they would be
180 	 * from the call
181 	 *
182 	 *	initstate(1, randtbl, 128);
183 	 *
184 	 * (The position of the rear pointer, rptr, is really 0 (as explained above
185 	 * in the initialization of randtbl) because the state table pointer is set
186 	 * to point to randtbl[1] (as explained below).
187 	 */
188 	.rst_fptr = &implicit.rst_randtbl[SEP_3 + 1],
189 	.rst_rptr = &implicit.rst_randtbl[1],
190 
191 	/*
192 	 * The following things are the pointer to the state information table, the
193 	 * type of the current generator, the degree of the current polynomial being
194 	 * used, and the separation between the two pointers.  Note that for efficiency
195 	 * of random(), we remember the first location of the state information, not
196 	 * the zeroeth.  Hence it is valid to access state[-1], which is used to
197 	 * store the type of the R.N.G.  Also, we remember the last location, since
198 	 * this is more efficient than indexing every time to find the address of
199 	 * the last element to see if the front and rear pointers have wrapped.
200 	 */
201 	.rst_state = &implicit.rst_randtbl[1],
202 	.rst_type = TYPE_3,
203 	.rst_deg = DEG_3,
204 	.rst_sep = SEP_3,
205 	.rst_end_ptr = &implicit.rst_randtbl[DEG_3 + 1],
206 };
207 
208 /*
209  * This is the same low quality PRNG used in rand(3) in FreeBSD 12 and prior.
210  * It may be sufficient for distributing bits and expanding a small seed
211  * integer into a larger state.
212  */
213 static inline uint32_t
214 parkmiller32(uint32_t ctx)
215 {
216 /*
217  * Compute x = (7^5 * x) mod (2^31 - 1)
218  * wihout overflowing 31 bits:
219  *      (2^31 - 1) = 127773 * (7^5) + 2836
220  * From "Random number generators: good ones are hard to find",
221  * Park and Miller, Communications of the ACM, vol. 31, no. 10,
222  * October 1988, p. 1195.
223  */
224 	int32_t hi, lo, x;
225 
226 	/* Transform to [1, 0x7ffffffe] range. */
227 	x = (ctx % 0x7ffffffe) + 1;
228 	hi = x / 127773;
229 	lo = x % 127773;
230 	x = 16807 * lo - 2836 * hi;
231 	if (x < 0)
232 		x += 0x7fffffff;
233 	/* Transform to [0, 0x7ffffffd] range. */
234 	return (x - 1);
235 }
236 
237 /*
238  * srandom:
239  *
240  * Initialize the random number generator based on the given seed.  If the
241  * type is the trivial no-state-information type, just remember the seed.
242  * Otherwise, initializes state[] based on the given "seed" via a linear
243  * congruential generator.  Then, the pointers are set to known locations
244  * that are exactly rand_sep places apart.  Lastly, it cycles the state
245  * information a given number of times to get rid of any initial dependencies
246  * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
247  * for default usage relies on values produced by this routine.
248  */
249 void
250 srandom_r(struct __random_state *estate, unsigned x)
251 {
252 	int i, lim;
253 
254 	estate->rst_state[0] = (uint32_t)x;
255 	if (estate->rst_type == TYPE_0)
256 		lim = NSHUFF;
257 	else {
258 		for (i = 1; i < estate->rst_deg; i++)
259 			estate->rst_state[i] =
260 			    parkmiller32(estate->rst_state[i - 1]);
261 		estate->rst_fptr = &estate->rst_state[estate->rst_sep];
262 		estate->rst_rptr = &estate->rst_state[0];
263 		lim = 10 * estate->rst_deg;
264 	}
265 	for (i = 0; i < lim; i++)
266 		(void)random_r(estate);
267 }
268 
269 void
270 srandom(unsigned x)
271 {
272 	srandom_r(&implicit, x);
273 }
274 
275 /*
276  * srandomdev:
277  *
278  * Many programs choose the seed value in a totally predictable manner.
279  * This often causes problems.  We seed the generator using pseudo-random
280  * data from the kernel.
281  *
282  * Note that this particular seeding procedure can generate states
283  * which are impossible to reproduce by calling srandom() with any
284  * value, since the succeeding terms in the state buffer are no longer
285  * derived from the LC algorithm applied to a fixed seed.
286  */
287 void
288 srandomdev_r(struct __random_state *estate)
289 {
290 	int mib[2];
291 	size_t expected, len;
292 
293 	if (estate->rst_type == TYPE_0)
294 		len = sizeof(estate->rst_state[0]);
295 	else
296 		len = estate->rst_deg * sizeof(estate->rst_state[0]);
297 	expected = len;
298 
299 	mib[0] = CTL_KERN;
300 	mib[1] = KERN_ARND;
301 	if (sysctl(mib, 2, estate->rst_state, &len, NULL, 0) == -1 ||
302 	    len != expected) {
303 		/*
304 		 * The sysctl cannot fail. If it does fail on some FreeBSD
305 		 * derivative or after some future change, just abort so that
306 		 * the problem will be found and fixed. abort is not normally
307 		 * suitable for a library but makes sense here.
308 		 */
309 		abort();
310 	}
311 
312 	if (estate->rst_type != TYPE_0) {
313 		estate->rst_fptr = &estate->rst_state[estate->rst_sep];
314 		estate->rst_rptr = &estate->rst_state[0];
315 	}
316 }
317 
318 void
319 srandomdev(void)
320 {
321 	srandomdev_r(&implicit);
322 }
323 
324 /*
325  * initstate_r:
326  *
327  * Initialize the state information in the given array of n bytes for future
328  * random number generation.  Based on the number of bytes we are given, and
329  * the break values for the different R.N.G.'s, we choose the best (largest)
330  * one we can and set things up for it.  srandom() is then called to
331  * initialize the state information.
332  *
333  * Returns zero on success, or an error number on failure.
334  *
335  * Note: There is no need for a setstate_r(); just use a new context.
336  */
337 int
338 initstate_r(struct __random_state *estate, unsigned seed, uint32_t *arg_state,
339     size_t sz)
340 {
341 	if (sz < BREAK_0)
342 		return (EINVAL);
343 
344 	if (sz < BREAK_1) {
345 		estate->rst_type = TYPE_0;
346 		estate->rst_deg = DEG_0;
347 		estate->rst_sep = SEP_0;
348 	} else if (sz < BREAK_2) {
349 		estate->rst_type = TYPE_1;
350 		estate->rst_deg = DEG_1;
351 		estate->rst_sep = SEP_1;
352 	} else if (sz < BREAK_3) {
353 		estate->rst_type = TYPE_2;
354 		estate->rst_deg = DEG_2;
355 		estate->rst_sep = SEP_2;
356 	} else if (sz < BREAK_4) {
357 		estate->rst_type = TYPE_3;
358 		estate->rst_deg = DEG_3;
359 		estate->rst_sep = SEP_3;
360 	} else {
361 		estate->rst_type = TYPE_4;
362 		estate->rst_deg = DEG_4;
363 		estate->rst_sep = SEP_4;
364 	}
365 	estate->rst_state = arg_state + 1;
366 	estate->rst_end_ptr = &estate->rst_state[estate->rst_deg];
367 	srandom_r(estate, seed);
368 	return (0);
369 }
370 
371 /*
372  * initstate:
373  *
374  * Note: the first thing we do is save the current state, if any, just like
375  * setstate() so that it doesn't matter when initstate is called.
376  *
377  * Note that on return from initstate_r(), we set state[-1] to be the type
378  * multiplexed with the current value of the rear pointer; this is so
379  * successive calls to initstate() won't lose this information and will be able
380  * to restart with setstate().
381  *
382  * Returns a pointer to the old state.
383  *
384  * Despite the misleading "char *" type, arg_state must alias an array of
385  * 32-bit unsigned integer values.  Naturally, such an array is 32-bit aligned.
386  * Usually objects are naturally aligned to at least 32-bits on all platforms,
387  * but if you treat the provided 'state' as char* you may inadvertently
388  * misalign it.  Don't do that.
389  */
390 char *
391 initstate(unsigned int seed, char *arg_state, size_t n)
392 {
393 	char *ostate = (char *)(&implicit.rst_state[-1]);
394 	uint32_t *int_arg_state = (uint32_t *)arg_state;
395 	int error;
396 
397 	/*
398 	 * Persist rptr offset and rst_type in the first word of the prior
399 	 * state we are replacing.
400 	 */
401 	if (implicit.rst_type == TYPE_0)
402 		implicit.rst_state[-1] = implicit.rst_type;
403 	else
404 		implicit.rst_state[-1] = MAX_TYPES *
405 		    (implicit.rst_rptr - implicit.rst_state) +
406 		    implicit.rst_type;
407 
408 	error = initstate_r(&implicit, seed, int_arg_state, n);
409 	if (error != 0)
410 		return (NULL);
411 
412 	/*
413 	 * Persist rptr offset and rst_type of the new state in its first word.
414 	 */
415 	if (implicit.rst_type == TYPE_0)
416 		int_arg_state[0] = implicit.rst_type;
417 	else
418 		int_arg_state[0] = MAX_TYPES *
419 		    (implicit.rst_rptr - implicit.rst_state) +
420 		    implicit.rst_type;
421 
422 	return (ostate);
423 }
424 
425 /*
426  * setstate:
427  *
428  * Restore the state from the given state array.
429  *
430  * Note: it is important that we also remember the locations of the pointers
431  * in the current state information, and restore the locations of the pointers
432  * from the old state information.  This is done by multiplexing the pointer
433  * location into the zeroeth word of the state information.
434  *
435  * Note that due to the order in which things are done, it is OK to call
436  * setstate() with the same state as the current state.
437  *
438  * Returns a pointer to the old state information.
439  *
440  * Note: The Sparc platform requires that arg_state begin on an int
441  * word boundary; otherwise a bus error will occur. Even so, lint will
442  * complain about mis-alignment, but you should disregard these messages.
443  */
444 char *
445 setstate(char *arg_state)
446 {
447 	uint32_t *new_state = (uint32_t *)arg_state;
448 	uint32_t type = new_state[0] % MAX_TYPES;
449 	uint32_t rear = new_state[0] / MAX_TYPES;
450 	char *ostate = (char *)(&implicit.rst_state[-1]);
451 
452 	if (type != TYPE_0 && rear >= degrees[type])
453 		return (NULL);
454 	if (implicit.rst_type == TYPE_0)
455 		implicit.rst_state[-1] = implicit.rst_type;
456 	else
457 		implicit.rst_state[-1] = MAX_TYPES *
458 		    (implicit.rst_rptr - implicit.rst_state) +
459 		    implicit.rst_type;
460 	implicit.rst_type = type;
461 	implicit.rst_deg = degrees[type];
462 	implicit.rst_sep = seps[type];
463 	implicit.rst_state = new_state + 1;
464 	if (implicit.rst_type != TYPE_0) {
465 		implicit.rst_rptr = &implicit.rst_state[rear];
466 		implicit.rst_fptr = &implicit.rst_state[
467 		    (rear + implicit.rst_sep) % implicit.rst_deg];
468 	}
469 	implicit.rst_end_ptr = &implicit.rst_state[implicit.rst_deg];
470 	return (ostate);
471 }
472 
473 /*
474  * random:
475  *
476  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
477  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
478  * the same in all the other cases due to all the global variables that have
479  * been set up.  The basic operation is to add the number at the rear pointer
480  * into the one at the front pointer.  Then both pointers are advanced to
481  * the next location cyclically in the table.  The value returned is the sum
482  * generated, reduced to 31 bits by throwing away the "least random" low bit.
483  *
484  * Note: the code takes advantage of the fact that both the front and
485  * rear pointers can't wrap on the same call by not testing the rear
486  * pointer if the front one has wrapped.
487  *
488  * Returns a 31-bit random number.
489  */
490 long
491 random_r(struct __random_state *estate)
492 {
493 	uint32_t i;
494 	uint32_t *f, *r;
495 
496 	if (estate->rst_type == TYPE_0) {
497 		i = estate->rst_state[0];
498 		i = parkmiller32(i);
499 		estate->rst_state[0] = i;
500 	} else {
501 		/*
502 		 * Use local variables rather than static variables for speed.
503 		 */
504 		f = estate->rst_fptr;
505 		r = estate->rst_rptr;
506 		*f += *r;
507 		i = *f >> 1;	/* chucking least random bit */
508 		if (++f >= estate->rst_end_ptr) {
509 			f = estate->rst_state;
510 			++r;
511 		}
512 		else if (++r >= estate->rst_end_ptr) {
513 			r = estate->rst_state;
514 		}
515 
516 		estate->rst_fptr = f;
517 		estate->rst_rptr = r;
518 	}
519 	return ((long)i);
520 }
521 
522 long
523 random(void)
524 {
525 	return (random_r(&implicit));
526 }
527