xref: /titanic_52/usr/src/lib/libbc/libc/gen/common/random.c (revision ba4e3c84e6b9390bbf7df80b5f1d11dec34cc525)
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  * Copyright 1999 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 
32 /*
33  * random.c:
34  * An improved random number generation package.  In addition to the standard
35  * rand()/srand() like interface, this package also has a special state info
36  * interface.  The initstate() routine is called with a seed, an array of
37  * bytes, and a count of how many bytes are being passed in; this array is then
38  * initialized to contain information for random number generation with that
39  * much state information.  Good sizes for the amount of state information are
40  * 32, 64, 128, and 256 bytes.  The state can be switched by calling the
41  * setstate() routine with the same array as was initiallized with initstate().
42  * By default, the package runs with 128 bytes of state information and
43  * generates far better random numbers than a linear congruential generator.
44  * If the amount of state information is less than 32 bytes, a simple linear
45  * congruential R.N.G. is used.
46  * Internally, the state information is treated as an array of longs; the
47  * zeroeth element of the array is the type of R.N.G. being used (small
48  * integer); the remainder of the array is the state information for the
49  * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
50  * state information, which will allow a degree seven polynomial.  (Note: the
51  * zeroeth word of state information also has some other information stored
52  * in it -- see setstate() for details).
53  * The random number generation technique is a linear feedback shift register
54  * approach, employing trinomials (since there are fewer terms to sum up that
55  * way).  In this approach, the least significant bit of all the numbers in
56  * the state table will act as a linear feedback shift register, and will have
57  * period 2^deg - 1 (where deg is the degree of the polynomial being used,
58  * assuming that the polynomial is irreducible and primitive).  The higher
59  * order bits will have longer periods, since their values are also influenced
60  * by pseudo-random carries out of the lower bits.  The total period of the
61  * generator is approximately deg*(2**deg - 1); thus doubling the amount of
62  * state information has a vast influence on the period of the generator.
63  * Note: the deg*(2**deg - 1) is an approximation only good for large deg,
64  * when the period of the shift register is the dominant factor.  With deg
65  * equal to seven, the period is actually much longer than the 7*(2**7 - 1)
66  * predicted by this formula.
67  */
68 
69 
70 
71 /*
72  * For each of the currently supported random number generators, we have a
73  * break value on the amount of state information (you need at least this
74  * many bytes of state info to support this random number generator), a degree
75  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
76  * the separation between the two lower order coefficients of the trinomial.
77  */
78 
79 #define		TYPE_0		0		/* linear congruential */
80 #define		BREAK_0		8
81 #define		DEG_0		0
82 #define		SEP_0		0
83 
84 #define		TYPE_1		1		/* x**7 + x**3 + 1 */
85 #define		BREAK_1		32
86 #define		DEG_1		7
87 #define		SEP_1		3
88 
89 #define		TYPE_2		2		/* x**15 + x + 1 */
90 #define		BREAK_2		64
91 #define		DEG_2		15
92 #define		SEP_2		1
93 
94 #define		TYPE_3		3		/* x**31 + x**3 + 1 */
95 #define		BREAK_3		128
96 #define		DEG_3		31
97 #define		SEP_3		3
98 
99 #define		TYPE_4		4		/* x**63 + x + 1 */
100 #define		BREAK_4		256
101 #define		DEG_4		63
102 #define		SEP_4		1
103 
104 
105 /*
106  * Array versions of the above information to make code run faster -- relies
107  * on fact that TYPE_i == i.
108  */
109 
110 #define		MAX_TYPES	5		/* max number of types above */
111 
112 static struct _randomjunk {
113 	int	degrees[MAX_TYPES];
114 	int	seps[MAX_TYPES];
115 	long	randtbl[ DEG_3 + 1 ];
116 /*
117  * fptr and rptr are two pointers into the state info, a front and a rear
118  * pointer.  These two pointers are always rand_sep places aparts, as they cycle
119  * cyclically through the state information.  (Yes, this does mean we could get
120  * away with just one pointer, but the code for random() is more efficient this
121  * way).  The pointers are left positioned as they would be from the call
122  *			initstate(1, randtbl, 128)
123  * (The position of the rear pointer, rptr, is really 0 (as explained above
124  * in the initialization of randtbl) because the state table pointer is set
125  * to point to randtbl[1] (as explained below).
126  */
127 	long	*fptr, *rptr;
128 /*
129  * The following things are the pointer to the state information table,
130  * the type of the current generator, the degree of the current polynomial
131  * being used, and the separation between the two pointers.
132  * Note that for efficiency of random(), we remember the first location of
133  * the state information, not the zeroeth.  Hence it is valid to access
134  * state[-1], which is used to store the type of the R.N.G.
135  * Also, we remember the last location, since this is more efficient than
136  * indexing every time to find the address of the last element to see if
137  * the front and rear pointers have wrapped.
138  */
139 	long	*state;
140 	int	rand_type, rand_deg, rand_sep;
141 	long	*end_ptr;
142 } *__randomjunk, *_randomjunk(void), _randominit = {
143 	/*
144 	 * Initially, everything is set up as if from :
145 	 *		initstate(1, &randtbl, 128);
146 	 * Note that this initialization takes advantage of the fact
147 	 * that srandom() advances the front and rear pointers 10*rand_deg
148 	 * times, and hence the rear pointer which starts at 0 will also
149 	 * end up at zero; thus the zeroeth element of the state
150 	 * information, which contains info about the current
151 	 * position of the rear pointer is just
152 	 *	MAX_TYPES*(rptr - state) + TYPE_3 == TYPE_3.
153 	 */
154 	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 },
155 	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 },
156 	{ TYPE_3,
157 	(long)0x9a319039, (long)0x32d9c024, (long)0x9b663182, (long)0x5da1f342,
158 	(long)0xde3b81e0, (long)0xdf0a6fb5, (long)0xf103bc02, (long)0x48f340fb,
159 	(long)0x7449e56b, (long)0xbeb1dbb0, (long)0xab5c5918, (long)0x946554fd,
160 	(long)0x8c2e680f, (long)0xeb3d799f, (long)0xb11ee0b7, (long)0x2d436b86,
161 	(long)0xda672e2a, (long)0x1588ca88, (long)0xe369735d, (long)0x904f35f7,
162 	(long)0xd7158fd6, (long)0x6fa6f051, (long)0x616e6b96, (long)0xac94efdc,
163 	(long)0x36413f93, (long)0xc622c298, (long)0xf5a42ab8, (long)0x8a88d77b,
164 	(long)0xf5ad9d0e, (long)0x8999220b, (long)0x27fb47b9 },
165 	&_randominit.randtbl[ SEP_3 + 1 ],
166 	&_randominit.randtbl[1],
167 	&_randominit.randtbl[1],
168 	TYPE_3, DEG_3, SEP_3,
169 	&_randominit.randtbl[ DEG_3 + 1]
170 };
171 
172 long random(void);
173 
174 static struct _randomjunk *
175 _randomjunk(void)
176 {
177 	struct _randomjunk *rp = __randomjunk;
178 
179 	if (rp == 0) {
180 		rp = (struct _randomjunk *)malloc(sizeof (*rp));
181 		if (rp == 0)
182 			return (0);
183 		*rp = _randominit;
184 		__randomjunk = rp;
185 	}
186 	return (rp);
187 }
188 
189 /*
190  * srandom:
191  * Initialize the random number generator based on the given seed.  If the
192  * type is the trivial no-state-information type, just remember the seed.
193  * Otherwise, initializes state[] based on the given "seed" via a linear
194  * congruential generator.  Then, the pointers are set to known locations
195  * that are exactly rand_sep places apart.  Lastly, it cycles the state
196  * information a given number of times to get rid of any initial dependencies
197  * introduced by the L.C.R.N.G.
198  * Note that the initialization of randtbl[] for default usage relies on
199  * values produced by this routine.
200  */
201 
202 void
203 srandom(unsigned x)
204 {
205 	struct _randomjunk *rp = _randomjunk();
206 	int		i;
207 
208 	if (rp == 0)
209 		return;
210 	if (rp->rand_type  ==  TYPE_0)  {
211 	    rp->state[0] = x;
212 	} else  {
213 	    rp->state[0] = x;
214 	    for (i = 1; i < rp->rand_deg; i++)  {
215 		rp->state[i] = 1103515245*rp->state[i - 1] + 12345;
216 	    }
217 	    rp->fptr = &rp->state[rp->rand_sep];
218 	    rp->rptr = &rp->state[0];
219 	    for (i = 0; i < 10 * rp->rand_deg; i++)
220 		random();
221 	}
222 }
223 
224 
225 
226 /*
227  * initstate:
228  * Initialize the state information in the given array of n bytes for
229  * future random number generation.  Based on the number of bytes we
230  * are given, and the break values for the different R.N.G.'s, we choose
231  * the best (largest) one we can and set things up for it.  srandom() is
232  * then called to initialize the state information.
233  * Note that on return from srandom(), we set state[-1] to be the type
234  * multiplexed with the current value of the rear pointer; this is so
235  * successive calls to initstate() won't lose this information and will
236  * be able to restart with setstate().
237  * Note: the first thing we do is save the current state, if any, just like
238  * setstate() so that it doesn't matter when initstate is called.
239  * Returns a pointer to the old state.
240  *
241  * Arguments:
242  *	seed:		seed for R. N. G.
243  *	arg_state:	pointer to state array
244  *	n:		# bytes of state info
245  */
246 
247 char  *
248 initstate(unsigned seed, char *arg_state, int n)
249 {
250 	struct _randomjunk *rp = _randomjunk();
251 	char		*ostate;
252 
253 	if (rp == 0)
254 		return (0);
255 	ostate = (char *)(&rp->state[-1]);
256 
257 	if (rp->rand_type  ==  TYPE_0)  rp->state[-1] = rp->rand_type;
258 	else  rp->state[-1] =
259 	    MAX_TYPES*(rp->rptr - rp->state) + rp->rand_type;
260 	if (n < BREAK_0) {
261 		fprintf(stderr,
262 	"initstate: state array too small, ignored; minimum size is %d bytes\n",
263 			BREAK_0);
264 		return (0);
265 	} else if (n < BREAK_1) {
266 		rp->rand_type = TYPE_0;
267 		rp->rand_deg = DEG_0;
268 		rp->rand_sep = SEP_0;
269 	} else if (n < BREAK_2) {
270 		rp->rand_type = TYPE_1;
271 		rp->rand_deg = DEG_1;
272 		rp->rand_sep = SEP_1;
273 	} else if (n < BREAK_3) {
274 		rp->rand_type = TYPE_2;
275 		rp->rand_deg = DEG_2;
276 		rp->rand_sep = SEP_2;
277 	} else if (n < BREAK_4) {
278 		rp->rand_type = TYPE_3;
279 		rp->rand_deg = DEG_3;
280 		rp->rand_sep = SEP_3;
281 	} else  {
282 		rp->rand_type = TYPE_4;
283 		rp->rand_deg = DEG_4;
284 		rp->rand_sep = SEP_4;
285 	}
286 	rp->state = &((long *)arg_state)[1];	/* first location */
287 	rp->end_ptr = &rp->state[rp->rand_deg];	/* set end_ptr before srandom */
288 	srandom(seed);
289 	rp->state[-1] = (rp->rand_type == TYPE_0) ? rp->rand_type
290 			: MAX_TYPES * (rp->rptr - rp->state) + rp->rand_type;
291 	return (ostate);
292 }
293 
294 
295 /*
296  * setstate:
297  * Restore the state from the given state array.
298  * Note: it is important that we also remember the locations of the pointers
299  * in the current state information, and restore the locations of the pointers
300  * from the old state information.  This is done by multiplexing the pointer
301  * location into the zeroeth word of the state information.
302  * Note that due to the order in which things are done, it is OK to call
303  * setstate() with the same state as the current state.
304  * Returns a pointer to the old state information.
305  */
306 
307 char  *
308 setstate(char *arg_state)
309 {
310 	struct _randomjunk *rp = _randomjunk();
311 	long		*new_state;
312 	int		type;
313 	int		rear;
314 	char			*ostate;
315 
316 	if (rp == 0)
317 		return (0);
318 	new_state = (long *)arg_state;
319 	type = new_state[0] % MAX_TYPES;
320 	rear = new_state[0] / MAX_TYPES;
321 	ostate = (char *)(&rp->state[-1]);
322 
323 	rp->state[-1] = (rp->rand_type == TYPE_0) ? rp->rand_type
324 			: MAX_TYPES*(rp->rptr - rp->state) + rp->rand_type;
325 	switch (type)  {
326 	case  TYPE_0:
327 	case  TYPE_1:
328 	case  TYPE_2:
329 	case  TYPE_3:
330 	case  TYPE_4:
331 		rp->rand_type = type;
332 		rp->rand_deg = rp->degrees[type];
333 		rp->rand_sep = rp->seps[type];
334 		break;
335 
336 	default:
337 		fprintf(stderr, "setstate: invalid state info; not changed.\n");
338 	}
339 	rp->state = &new_state[1];
340 	if (rp->rand_type != TYPE_0)  {
341 	    rp->rptr = &rp->state[rear];
342 	    rp->fptr = &rp->state[(rear + rp->rand_sep) % rp->rand_deg];
343 	}
344 	rp->end_ptr = &rp->state[rp->rand_deg];	/* set end_ptr too */
345 	return (ostate);
346 }
347 
348 
349 /*
350  * random:
351  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
352  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is the
353  * same in all ther other cases due to all the global variables that have been
354  * set up.  The basic operation is to add the number at the rear pointer into
355  * the one at the front pointer.  Then both pointers are advanced to the next
356  * location cyclically in the table.  The value returned is the sum generated,
357  * reduced to 31 bits by throwing away the "least random" low bit.
358  * Note: the code takes advantage of the fact that both the front and
359  * rear pointers can't wrap on the same call by not testing the rear
360  * pointer if the front one has wrapped.
361  * Returns a 31-bit random number.
362  */
363 
364 long
365 random(void)
366 {
367 	struct _randomjunk *rp = _randomjunk();
368 	long		i;
369 
370 	if (rp == 0)
371 		return (0);
372 	if (rp->rand_type  ==  TYPE_0)  {
373 	    i = rp->state[0] = (rp->state[0]*1103515245 + 12345)&0x7fffffff;
374 	} else  {
375 	    *rp->fptr += *rp->rptr;
376 	    i = (*rp->fptr >> 1)&0x7fffffff;	/* chucking least random bit */
377 	    if (++rp->fptr  >=  rp->end_ptr)  {
378 		rp->fptr = rp->state;
379 		++rp->rptr;
380 	    } else if (++rp->rptr  >=  rp->end_ptr)
381 		rp->rptr = rp->state;
382 	}
383 	return (i);
384 }
385