xref: /illumos-gate/usr/src/lib/libc/port/gen/random.c (revision d48be21240dfd051b689384ce2b23479d757f2d8)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 /*
31  * University Copyright- Copyright (c) 1982, 1986, 1988
32  * The Regents of the University of California
33  * All Rights Reserved
34  *
35  * University Acknowledgment- Portions of this document are derived from
36  * software developed by the University of California, Berkeley, and its
37  * contributors.
38  */
39 
40 #include "lint.h"
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include <limits.h>
46 
47 /*
48  * random.c:
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 then
53  * initialized to contain information for random number generation with that
54  * much state information.  Good sizes for the amount of state information are
55  * 32, 64, 128, and 256 bytes.  The state can be switched by calling the
56  * setstate() routine with the same array as was initiallized with initstate().
57  * By default, the package runs with 128 bytes of state information and
58  * generates far better random numbers than a linear congruential generator.
59  * If the amount of state information is less than 32 bytes, a simple linear
60  * congruential R.N.G. is used.
61  * Internally, the state information is treated as an array of ints; the
62  * zeroeth element of the array is the type of R.N.G. being used (small
63  * integer); the remainder of the array is the state information for the
64  * R.N.G.  Thus, 32 bytes of state information will give 7 ints worth of
65  * state information, which will allow a degree seven polynomial.  (Note: the
66  * zeroeth word of state information also has some other information stored
67  * in it -- see setstate() for details).
68  * The random number generation technique is a linear feedback shift register
69  * approach, employing trinomials (since there are fewer terms to sum up that
70  * way).  In this approach, the least significant bit of all the numbers in
71  * the state table will act as a linear feedback shift register, and will have
72  * period 2^deg - 1 (where deg is the degree of the polynomial being used,
73  * assuming that the polynomial is irreducible and primitive).  The higher
74  * order bits will have longer periods, since their values are also influenced
75  * by pseudo-random carries out of the lower bits.  The total period of the
76  * generator is approximately deg*(2**deg - 1); thus doubling the amount of
77  * state information has a vast influence on the period of the generator.
78  * Note: the deg*(2**deg - 1) is an approximation only good for large deg,
79  * when the period of the shift register is the dominant factor.  With deg
80  * equal to seven, the period is actually much longer than the 7*(2**7 - 1)
81  * predicted by this formula.
82  */
83 
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 
94 #define		TYPE_0		0		/* linear congruential */
95 #define		BREAK_0		8
96 #define		DEG_0		0
97 #define		SEP_0		0
98 
99 #define		TYPE_1		1		/* x**7 + x**3 + 1 */
100 #define		BREAK_1		32
101 #define		DEG_1		7
102 #define		SEP_1		3
103 
104 #define		TYPE_2		2		/* x**15 + x + 1 */
105 #define		BREAK_2		64
106 #define		DEG_2		15
107 #define		SEP_2		1
108 
109 #define		TYPE_3		3		/* x**31 + x**3 + 1 */
110 #define		BREAK_3		128
111 #define		DEG_3		31
112 #define		SEP_3		3
113 
114 #define		TYPE_4		4		/* x**63 + x + 1 */
115 #define		BREAK_4		256
116 #define		DEG_4		63
117 #define		SEP_4		1
118 
119 
120 /*
121  * Array versions of the above information to make code run faster -- relies
122  * on fact that TYPE_i == i.
123  */
124 
125 #define		MAX_TYPES	5		/* max number of types above */
126 
127 static struct _randomjunk {
128 	unsigned int	degrees[MAX_TYPES];
129 	unsigned int	seps[MAX_TYPES];
130 	unsigned int	randtbl[ DEG_3 + 1 ];
131 /*
132  * fptr and rptr are two pointers into the state info, a front and a rear
133  * pointer.  These two pointers are always rand_sep places aparts, as they cycle
134  * cyclically through the state information.  (Yes, this does mean we could get
135  * away with just one pointer, but the code for random() is more efficient this
136  * way).  The pointers are left positioned as they would be from the call
137  *			initstate( 1, randtbl, 128 )
138  * (The position of the rear pointer, rptr, is really 0 (as explained above
139  * in the initialization of randtbl) because the state table pointer is set
140  * to point to randtbl[1] (as explained below).
141  */
142 	unsigned int	*fptr, *rptr;
143 /*
144  * The following things are the pointer to the state information table,
145  * the type of the current generator, the degree of the current polynomial
146  * being used, and the separation between the two pointers.
147  * Note that for efficiency of random(), we remember the first location of
148  * the state information, not the zeroeth.  Hence it is valid to access
149  * state[-1], which is used to store the type of the R.N.G.
150  * Also, we remember the last location, since this is more efficient than
151  * indexing every time to find the address of the last element to see if
152  * the front and rear pointers have wrapped.
153  */
154 	unsigned int	*state;
155 	unsigned int	rand_type, rand_deg, rand_sep;
156 	unsigned int	*end_ptr;
157 } *__randomjunk, *_randomjunk(void), _randominit = {
158 	/*
159 	 * Initially, everything is set up as if from :
160 	 *		initstate( 1, &randtbl, 128 );
161 	 * Note that this initialization takes advantage of the fact
162 	 * that srandom() advances the front and rear pointers 10*rand_deg
163 	 * times, and hence the rear pointer which starts at 0 will also
164 	 * end up at zero; thus the zeroeth element of the state
165 	 * information, which contains info about the current
166 	 * position of the rear pointer is just
167 	 *	MAX_TYPES*(rptr - state) + TYPE_3 == TYPE_3.
168 	 */
169 	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 },
170 	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 },
171 	{ TYPE_3,
172 	    0x9a319039U, 0x32d9c024U, 0x9b663182U, 0x5da1f342U,
173 	    0xde3b81e0U, 0xdf0a6fb5U, 0xf103bc02U, 0x48f340fbU,
174 	    0x7449e56bU, 0xbeb1dbb0U, 0xab5c5918U, 0x946554fdU,
175 	    0x8c2e680fU, 0xeb3d799fU, 0xb11ee0b7U, 0x2d436b86U,
176 	    0xda672e2aU, 0x1588ca88U, 0xe369735dU, 0x904f35f7U,
177 	    0xd7158fd6U, 0x6fa6f051U, 0x616e6b96U, 0xac94efdcU,
178 	    0x36413f93U, 0xc622c298U, 0xf5a42ab8U, 0x8a88d77bU,
179 			0xf5ad9d0eU, 0x8999220bU, 0x27fb47b9U },
180 	&_randominit.randtbl[ SEP_3 + 1 ],
181 	&_randominit.randtbl[ 1 ],
182 	&_randominit.randtbl[ 1 ],
183 	TYPE_3, DEG_3, SEP_3,
184 	&_randominit.randtbl[ DEG_3 + 1]
185 };
186 
187 static struct _randomjunk *
188 _randomjunk(void)
189 {
190 	struct _randomjunk *rp = __randomjunk;
191 
192 	if (rp == NULL) {
193 		rp = (struct _randomjunk *)malloc(sizeof (*rp));
194 		if (rp == NULL)
195 			return (NULL);
196 		(void) memcpy(rp, &_randominit, sizeof (*rp));
197 		__randomjunk = rp;
198 	}
199 	return (rp);
200 }
201 
202 
203 /*
204  * initstate:
205  * Initialize the state information in the given array of n bytes for
206  * future random number generation.  Based on the number of bytes we
207  * are given, and the break values for the different R.N.G.'s, we choose
208  * the best (largest) one we can and set things up for it.  srandom() is
209  * then called to initialize the state information.
210  * Note that on return from srandom(), we set state[-1] to be the type
211  * multiplexed with the current value of the rear pointer; this is so
212  * successive calls to initstate() won't lose this information and will
213  * be able to restart with setstate().
214  * Note: the first thing we do is save the current state, if any, just like
215  * setstate() so that it doesn't matter when initstate is called.
216  * Returns a pointer to the old state.
217  */
218 
219 char  *
220 initstate(
221 	unsigned int seed,	/* seed for R. N. G. */
222 	char *arg_state,	/* pointer to state array */
223 	size_t size)		/* # bytes of state info */
224 {
225 	unsigned int n;
226 	struct _randomjunk *rp = _randomjunk();
227 	char		*ostate;
228 
229 	if (size > UINT_MAX)
230 		n = UINT_MAX;
231 	else
232 		n = (unsigned int)size;
233 
234 	if (rp == NULL)
235 		return (NULL);
236 	ostate = (char *)(&rp->state[ -1 ]);
237 
238 	if (rp->rand_type  ==  TYPE_0)  rp->state[ -1 ] = rp->rand_type;
239 	else  rp->state[ -1 ] =
240 	    (unsigned int)(MAX_TYPES*(rp->rptr - rp->state) + rp->rand_type);
241 	if (n  <  BREAK_1)  {
242 	    if (n  <  BREAK_0)  {
243 		return (NULL);
244 	    }
245 	    rp->rand_type = TYPE_0;
246 	    rp->rand_deg = DEG_0;
247 	    rp->rand_sep = SEP_0;
248 	} else  {
249 	    if (n  <  BREAK_2)  {
250 		rp->rand_type = TYPE_1;
251 		rp->rand_deg = DEG_1;
252 		rp->rand_sep = SEP_1;
253 	    } else  {
254 		if (n  <  BREAK_3)  {
255 		    rp->rand_type = TYPE_2;
256 		    rp->rand_deg = DEG_2;
257 		    rp->rand_sep = SEP_2;
258 		} else  {
259 		    if (n  <  BREAK_4)  {
260 			rp->rand_type = TYPE_3;
261 			rp->rand_deg = DEG_3;
262 			rp->rand_sep = SEP_3;
263 		    } else  {
264 			rp->rand_type = TYPE_4;
265 			rp->rand_deg = DEG_4;
266 			rp->rand_sep = SEP_4;
267 		    }
268 		}
269 	    }
270 	}
271 	/* first location */
272 	rp->state = &(((unsigned int *)(uintptr_t)arg_state)[1]);
273 	/* must set end_ptr before srandom */
274 	rp->end_ptr = &rp->state[rp->rand_deg];
275 	srandom(seed);
276 	if (rp->rand_type  ==  TYPE_0)  rp->state[ -1 ] = rp->rand_type;
277 	else
278 		rp->state[-1] = (unsigned int)(MAX_TYPES*
279 		    (rp->rptr - rp->state) + rp->rand_type);
280 	return (ostate);
281 }
282 
283 
284 
285 /*
286  * setstate:
287  * Restore the state from the given state array.
288  * Note: it is important that we also remember the locations of the pointers
289  * in the current state information, and restore the locations of the pointers
290  * from the old state information.  This is done by multiplexing the pointer
291  * location into the zeroeth word of the state information.
292  * Note that due to the order in which things are done, it is OK to call
293  * setstate() with the same state as the current state.
294  * Returns a pointer to the old state information.
295  */
296 
297 char  *
298 setstate(const char *arg_state)
299 {
300 	struct _randomjunk *rp = _randomjunk();
301 	unsigned int	*new_state;
302 	unsigned int	type;
303 	unsigned int	rear;
304 	char		*ostate;
305 
306 	if (rp == NULL)
307 		return (NULL);
308 	new_state = (unsigned int *)(uintptr_t)arg_state;
309 	type = new_state[0]%MAX_TYPES;
310 	rear = new_state[0]/MAX_TYPES;
311 	ostate = (char *)(&rp->state[ -1 ]);
312 
313 	if (rp->rand_type  ==  TYPE_0) rp->state[ -1 ] = rp->rand_type;
314 	else
315 		rp->state[-1] = (unsigned int)(MAX_TYPES*
316 		    (rp->rptr - rp->state) + rp->rand_type);
317 	switch (type)  {
318 	    case  TYPE_0:
319 	    case  TYPE_1:
320 	    case  TYPE_2:
321 	    case  TYPE_3:
322 	    case  TYPE_4:
323 		rp->rand_type = type;
324 		rp->rand_deg = rp->degrees[ type ];
325 		rp->rand_sep = rp->seps[ type ];
326 		break;
327 
328 	    default:
329 		return (NULL);
330 	}
331 	rp->state = &new_state[ 1 ];
332 	if (rp->rand_type  !=  TYPE_0)  {
333 	    rp->rptr = &rp->state[ rear ];
334 	    rp->fptr = &rp->state[ (rear + rp->rand_sep)%rp->rand_deg ];
335 	}
336 	rp->end_ptr = &rp->state[ rp->rand_deg ];	/* set end_ptr too */
337 	return (ostate);
338 }
339 
340 
341 
342 /*
343  * random:
344  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
345  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is the
346  * same in all ther other cases due to all the global variables that have been
347  * set up.  The basic operation is to add the number at the rear pointer into
348  * the one at the front pointer.  Then both pointers are advanced to the next
349  * location cyclically in the table.  The value returned is the sum generated,
350  * reduced to 31 bits by throwing away the "least random" low bit.
351  * Note: the code takes advantage of the fact that both the front and
352  * rear pointers can't wrap on the same call by not testing the rear
353  * pointer if the front one has wrapped.
354  * Returns a 31-bit random number.
355  */
356 
357 long
358 random(void)
359 {
360 	struct _randomjunk *rp = _randomjunk();
361 	unsigned int	i;
362 
363 	if (rp == NULL)
364 		return (0L);
365 	if (rp->rand_type  ==  TYPE_0)  {
366 	    i = rp->state[0] = (rp->state[0]*1103515245 + 12345)&0x7fffffff;
367 	} else  {
368 	    *rp->fptr += *rp->rptr;
369 	    i = (*rp->fptr >> 1)&0x7fffffff;	/* chucking least random bit */
370 	    if (++rp->fptr  >=  rp->end_ptr)  {
371 		rp->fptr = rp->state;
372 		++rp->rptr;
373 	    } else  {
374 		if (++rp->rptr  >=  rp->end_ptr)  rp->rptr = rp->state;
375 	    }
376 	}
377 	return ((long)i);
378 }
379 
380 /*
381  * srandom:
382  * Initialize the random number generator based on the given seed.  If the
383  * type is the trivial no-state-information type, just remember the seed.
384  * Otherwise, initializes state[] based on the given "seed" via a linear
385  * congruential generator.  Then, the pointers are set to known locations
386  * that are exactly rand_sep places apart.  Lastly, it cycles the state
387  * information a given number of times to get rid of any initial dependencies
388  * introduced by the L.C.R.N.G.
389  * Note that the initialization of randtbl[] for default usage relies on
390  * values produced by this routine.
391  */
392 
393 void
394 srandom(unsigned int x)
395 {
396 	struct _randomjunk *rp = _randomjunk();
397 	unsigned int	i;
398 
399 	if (rp == NULL)
400 		return;
401 	if (rp->rand_type  ==  TYPE_0)  {
402 	    rp->state[ 0 ] = x;
403 	} else  {
404 	    rp->state[ 0 ] = x;
405 	    for (i = 1; i < rp->rand_deg; i++)  {
406 		rp->state[i] = 1103515245*rp->state[i - 1] + 12345;
407 	    }
408 	    rp->fptr = &rp->state[ rp->rand_sep ];
409 	    rp->rptr = &rp->state[ 0 ];
410 	    for (i = 0; i < 10*rp->rand_deg; i++)  (void)random();
411 	}
412 }
413