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