1181834Sroberto/*
2181834Sroberto * Copyright (c) 1983, 1993
3181834Sroberto *	The Regents of the University of California.  All rights reserved.
4181834Sroberto *
5181834Sroberto * Redistribution and use in source and binary forms, with or without
6181834Sroberto * modification, are permitted provided that the following conditions
7181834Sroberto * are met:
8181834Sroberto * 1. Redistributions of source code must retain the above copyright
9181834Sroberto *    notice, this list of conditions and the following disclaimer.
10181834Sroberto * 2. Redistributions in binary form must reproduce the above copyright
11181834Sroberto *    notice, this list of conditions and the following disclaimer in the
12181834Sroberto *    documentation and/or other materials provided with the distribution.
13181834Sroberto * 3. All advertising materials mentioning features or use of this software
14181834Sroberto *    must display the following acknowledgement:
15181834Sroberto *	This product includes software developed by the University of
16181834Sroberto *	California, Berkeley and its contributors.
17181834Sroberto * 4. Neither the name of the University nor the names of its contributors
18181834Sroberto *    may be used to endorse or promote products derived from this software
19181834Sroberto *    without specific prior written permission.
20181834Sroberto *
21181834Sroberto * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22181834Sroberto * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23181834Sroberto * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24181834Sroberto * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25181834Sroberto * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26181834Sroberto * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27181834Sroberto * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28181834Sroberto * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29181834Sroberto * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30181834Sroberto * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31181834Sroberto * SUCH DAMAGE.
32181834Sroberto *
33181834Sroberto * $FreeBSD: src/lib/libc/stdlib/random.c,v 1.4.2.2 1999/09/05 11:16:45 peter Exp $
34181834Sroberto *
35181834Sroberto */
36181834Sroberto
37181834Sroberto#if defined(LIBC_SCCS) && !defined(lint)
38181834Srobertostatic char sccsid[] = "@(#)random.c	8.2 (Berkeley) 5/19/95";
39181834Sroberto#endif /* LIBC_SCCS and not lint */
40181834Sroberto
41181834Sroberto#include "config.h"
42290000Sglebius#include <sys/types.h>
43181834Sroberto#ifdef HAVE_UNISTD_H
44181834Sroberto# include <unistd.h>
45181834Sroberto#endif
46181834Sroberto#include <stdio.h>
47181834Sroberto
48290000Sglebius#include <l_stdlib.h>
49181834Sroberto#include <ntp_random.h>
50181834Sroberto#include <ntp_unixtime.h>
51181834Sroberto
52181834Sroberto/*
53181834Sroberto * random.c:
54181834Sroberto *
55181834Sroberto * An improved random number generation package.  In addition to the standard
56181834Sroberto * rand()/srand() like interface, this package also has a special state info
57181834Sroberto * interface.  The initstate() routine is called with a seed, an array of
58181834Sroberto * bytes, and a count of how many bytes are being passed in; this array is
59181834Sroberto * then initialized to contain information for random number generation with
60181834Sroberto * that much state information.  Good sizes for the amount of state
61181834Sroberto * information are 32, 64, 128, and 256 bytes.  The state can be switched by
62181834Sroberto * calling the setstate() routine with the same array as was initiallized
63181834Sroberto * with initstate().  By default, the package runs with 128 bytes of state
64181834Sroberto * information and generates far better random numbers than a linear
65181834Sroberto * congruential generator.  If the amount of state information is less than
66181834Sroberto * 32 bytes, a simple linear congruential R.N.G. is used.
67181834Sroberto *
68181834Sroberto * Internally, the state information is treated as an array of longs; the
69181834Sroberto * zeroeth element of the array is the type of R.N.G. being used (small
70181834Sroberto * integer); the remainder of the array is the state information for the
71181834Sroberto * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
72181834Sroberto * state information, which will allow a degree seven polynomial.  (Note:
73181834Sroberto * the zeroeth word of state information also has some other information
74181834Sroberto * stored in it -- see setstate() for details).
75181834Sroberto *
76181834Sroberto * The random number generation technique is a linear feedback shift register
77181834Sroberto * approach, employing trinomials (since there are fewer terms to sum up that
78181834Sroberto * way).  In this approach, the least significant bit of all the numbers in
79181834Sroberto * the state table will act as a linear feedback shift register, and will
80181834Sroberto * have period 2^deg - 1 (where deg is the degree of the polynomial being
81181834Sroberto * used, assuming that the polynomial is irreducible and primitive).  The
82181834Sroberto * higher order bits will have longer periods, since their values are also
83181834Sroberto * influenced by pseudo-random carries out of the lower bits.  The total
84181834Sroberto * period of the generator is approximately deg*(2**deg - 1); thus doubling
85181834Sroberto * the amount of state information has a vast influence on the period of the
86181834Sroberto * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
87181834Sroberto * large deg, when the period of the shift register is the dominant factor.
88181834Sroberto * With deg equal to seven, the period is actually much longer than the
89181834Sroberto * 7*(2**7 - 1) predicted by this formula.
90181834Sroberto *
91181834Sroberto * Modified 28 December 1994 by Jacob S. Rosenberg.
92181834Sroberto * The following changes have been made:
93181834Sroberto * All references to the type u_int have been changed to unsigned long.
94181834Sroberto * All references to type int have been changed to type long.  Other
95181834Sroberto * cleanups have been made as well.  A warning for both initstate and
96181834Sroberto * setstate has been inserted to the effect that on Sparc platforms
97181834Sroberto * the 'arg_state' variable must be forced to begin on word boundaries.
98181834Sroberto * This can be easily done by casting a long integer array to char *.
99181834Sroberto * The overall logic has been left STRICTLY alone.  This software was
100181834Sroberto * tested on both a VAX and Sun SpacsStation with exactly the same
101181834Sroberto * results.  The new version and the original give IDENTICAL results.
102181834Sroberto * The new version is somewhat faster than the original.  As the
103181834Sroberto * documentation says:  "By default, the package runs with 128 bytes of
104181834Sroberto * state information and generates far better random numbers than a linear
105181834Sroberto * congruential generator.  If the amount of state information is less than
106181834Sroberto * 32 bytes, a simple linear congruential R.N.G. is used."  For a buffer of
107181834Sroberto * 128 bytes, this new version runs about 19 percent faster and for a 16
108181834Sroberto * byte buffer it is about 5 percent faster.
109181834Sroberto */
110181834Sroberto
111181834Sroberto/*
112181834Sroberto * For each of the currently supported random number generators, we have a
113181834Sroberto * break value on the amount of state information (you need at least this
114181834Sroberto * many bytes of state info to support this random number generator), a degree
115181834Sroberto * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
116181834Sroberto * the separation between the two lower order coefficients of the trinomial.
117181834Sroberto */
118181834Sroberto#define	TYPE_0		0		/* linear congruential */
119181834Sroberto#define	BREAK_0		8
120181834Sroberto#define	DEG_0		0
121181834Sroberto#define	SEP_0		0
122181834Sroberto
123181834Sroberto#define	TYPE_1		1		/* x**7 + x**3 + 1 */
124181834Sroberto#define	BREAK_1		32
125181834Sroberto#define	DEG_1		7
126181834Sroberto#define	SEP_1		3
127181834Sroberto
128181834Sroberto#define	TYPE_2		2		/* x**15 + x + 1 */
129181834Sroberto#define	BREAK_2		64
130181834Sroberto#define	DEG_2		15
131181834Sroberto#define	SEP_2		1
132181834Sroberto
133181834Sroberto#define	TYPE_3		3		/* x**31 + x**3 + 1 */
134181834Sroberto#define	BREAK_3		128
135181834Sroberto#define	DEG_3		31
136181834Sroberto#define	SEP_3		3
137181834Sroberto
138181834Sroberto#define	TYPE_4		4		/* x**63 + x + 1 */
139181834Sroberto#define	BREAK_4		256
140181834Sroberto#define	DEG_4		63
141181834Sroberto#define	SEP_4		1
142181834Sroberto
143181834Sroberto#define	MAX_TYPES	5		/* max number of types above */
144181834Sroberto
145181834Sroberto/*
146181834Sroberto * Initially, everything is set up as if from:
147181834Sroberto *
148181834Sroberto *	initstate(1, randtbl, 128);
149181834Sroberto *
150181834Sroberto * Note that this initialization takes advantage of the fact that srandom()
151181834Sroberto * advances the front and rear pointers 10*rand_deg times, and hence the
152181834Sroberto * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
153181834Sroberto * element of the state information, which contains info about the current
154181834Sroberto * position of the rear pointer is just
155181834Sroberto *
156181834Sroberto *	MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
157181834Sroberto */
158181834Sroberto
159290000Sglebiusstatic unsigned long randtbl[DEG_3 + 1] = {
160181834Sroberto	TYPE_3,
161181834Sroberto#ifdef  USE_WEAK_SEEDING
162181834Sroberto/* Historic implementation compatibility */
163181834Sroberto/* The random sequences do not vary much with the seed */
164181834Sroberto	0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
165181834Sroberto	0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
166181834Sroberto	0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
167181834Sroberto	0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
168181834Sroberto	0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
169181834Sroberto	0x27fb47b9,
170181834Sroberto#else   /* !USE_WEAK_SEEDING */
171181834Sroberto	0x991539b1, 0x16a5bce3, 0x6774a4cd, 0x3e01511e, 0x4e508aaa, 0x61048c05,
172181834Sroberto	0xf5500617, 0x846b7115, 0x6a19892c, 0x896a97af, 0xdb48f936, 0x14898454,
173181834Sroberto	0x37ffd106, 0xb58bff9c, 0x59e17104, 0xcf918a49, 0x09378c83, 0x52c7a471,
174181834Sroberto	0x8d293ea9, 0x1f4fc301, 0xc3db71be, 0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1,
175181834Sroberto	0x19edc328, 0x87bf4bdd, 0xc9b240e5, 0xe9ee4b1b, 0x4382aee7, 0x535b6b41,
176181834Sroberto	0xf3bec5da
177181834Sroberto#endif  /* !USE_WEAK_SEEDING */
178181834Sroberto};
179181834Sroberto
180181834Sroberto/*
181181834Sroberto * fptr and rptr are two pointers into the state info, a front and a rear
182181834Sroberto * pointer.  These two pointers are always rand_sep places aparts, as they
183181834Sroberto * cycle cyclically through the state information.  (Yes, this does mean we
184181834Sroberto * could get away with just one pointer, but the code for random() is more
185181834Sroberto * efficient this way).  The pointers are left positioned as they would be
186181834Sroberto * from the call
187181834Sroberto *
188181834Sroberto *	initstate(1, randtbl, 128);
189181834Sroberto *
190181834Sroberto * (The position of the rear pointer, rptr, is really 0 (as explained above
191181834Sroberto * in the initialization of randtbl) because the state table pointer is set
192181834Sroberto * to point to randtbl[1] (as explained below).
193181834Sroberto */
194290000Sglebiusstatic unsigned long *fptr = &randtbl[SEP_3 + 1];
195290000Sglebiusstatic unsigned long *rptr = &randtbl[1];
196181834Sroberto
197181834Sroberto/*
198181834Sroberto * The following things are the pointer to the state information table, the
199181834Sroberto * type of the current generator, the degree of the current polynomial being
200181834Sroberto * used, and the separation between the two pointers.  Note that for efficiency
201181834Sroberto * of random(), we remember the first location of the state information, not
202181834Sroberto * the zeroeth.  Hence it is valid to access state[-1], which is used to
203181834Sroberto * store the type of the R.N.G.  Also, we remember the last location, since
204181834Sroberto * this is more efficient than indexing every time to find the address of
205181834Sroberto * the last element to see if the front and rear pointers have wrapped.
206181834Sroberto */
207290000Sglebiusstatic unsigned long *state = &randtbl[1];
208181834Srobertostatic long rand_type = TYPE_3;
209181834Srobertostatic long rand_deg = DEG_3;
210181834Srobertostatic long rand_sep = SEP_3;
211290000Sglebiusstatic unsigned long *end_ptr = &randtbl[DEG_3 + 1];
212181834Sroberto
213290000Sglebiusstatic inline long good_rand (long);
214181834Sroberto
215181834Srobertostatic inline long
216181834Srobertogood_rand (
217181834Sroberto	register long x
218181834Sroberto	)
219181834Sroberto{
220181834Sroberto#ifdef  USE_WEAK_SEEDING
221181834Sroberto/*
222181834Sroberto * Historic implementation compatibility.
223181834Sroberto * The random sequences do not vary much with the seed,
224181834Sroberto * even with overflowing.
225181834Sroberto */
226181834Sroberto	return (1103515245 * x + 12345);
227181834Sroberto#else   /* !USE_WEAK_SEEDING */
228181834Sroberto/*
229181834Sroberto * Compute x = (7^5 * x) mod (2^31 - 1)
230181834Sroberto * wihout overflowing 31 bits:
231181834Sroberto *      (2^31 - 1) = 127773 * (7^5) + 2836
232181834Sroberto * From "Random number generators: good ones are hard to find",
233181834Sroberto * Park and Miller, Communications of the ACM, vol. 31, no. 10,
234181834Sroberto * October 1988, p. 1195.
235181834Sroberto */
236181834Sroberto	register long hi, lo;
237181834Sroberto
238181834Sroberto	hi = x / 127773;
239181834Sroberto	lo = x % 127773;
240181834Sroberto	x = 16807 * lo - 2836 * hi;
241181834Sroberto	if (x <= 0)
242181834Sroberto		x += 0x7fffffff;
243181834Sroberto	return (x);
244181834Sroberto#endif  /* !USE_WEAK_SEEDING */
245181834Sroberto}
246181834Sroberto
247181834Sroberto/*
248181834Sroberto * srandom:
249181834Sroberto *
250181834Sroberto * Initialize the random number generator based on the given seed.  If the
251181834Sroberto * type is the trivial no-state-information type, just remember the seed.
252181834Sroberto * Otherwise, initializes state[] based on the given "seed" via a linear
253181834Sroberto * congruential generator.  Then, the pointers are set to known locations
254181834Sroberto * that are exactly rand_sep places apart.  Lastly, it cycles the state
255181834Sroberto * information a given number of times to get rid of any initial dependencies
256181834Sroberto * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
257181834Sroberto * for default usage relies on values produced by this routine.
258181834Sroberto */
259181834Srobertovoid
260181834Srobertontp_srandom(
261181834Sroberto	unsigned long x
262181834Sroberto	)
263181834Sroberto{
264290000Sglebius	long i;
265181834Sroberto
266290000Sglebius	if (rand_type == TYPE_0) {
267181834Sroberto		state[0] = x;
268290000Sglebius	} else {
269181834Sroberto		state[0] = x;
270181834Sroberto		for (i = 1; i < rand_deg; i++)
271181834Sroberto			state[i] = good_rand(state[i - 1]);
272181834Sroberto		fptr = &state[rand_sep];
273181834Sroberto		rptr = &state[0];
274181834Sroberto		for (i = 0; i < 10 * rand_deg; i++)
275290000Sglebius			x = ntp_random();
276181834Sroberto	}
277290000Sglebius
278290000Sglebius	/* seed the likely faster (and poorer) rand() as well */
279290000Sglebius	srand((u_int)x);
280181834Sroberto}
281181834Sroberto
282181834Sroberto/*
283181834Sroberto * srandomdev:
284181834Sroberto *
285181834Sroberto * Many programs choose the seed value in a totally predictable manner.
286181834Sroberto * This often causes problems.  We seed the generator using the much more
287181834Sroberto * secure urandom(4) interface.  Note that this particular seeding
288181834Sroberto * procedure can generate states which are impossible to reproduce by
289181834Sroberto * calling srandom() with any value, since the succeeding terms in the
290181834Sroberto * state buffer are no longer derived from the LC algorithm applied to
291181834Sroberto * a fixed seed.
292181834Sroberto */
293181834Sroberto#ifdef NEED_SRANDOMDEV
294181834Srobertovoid
295181834Srobertontp_srandomdev( void )
296181834Sroberto{
297181834Sroberto	struct timeval tv;
298181834Sroberto	unsigned long junk;	/* Purposely used uninitialized */
299181834Sroberto
300181834Sroberto	GETTIMEOFDAY(&tv, NULL);
301181834Sroberto	ntp_srandom(getpid() ^ tv.tv_sec ^ tv.tv_usec ^ junk);
302181834Sroberto	return;
303181834Sroberto}
304181834Sroberto#endif
305181834Sroberto
306290000Sglebius
307181834Sroberto/*
308290000Sglebius * ntp_initstate() and ntp_setstate() are unused in our codebase and
309290000Sglebius * trigger warnings due to casting to a more-strictly-aligned pointer
310290000Sglebius * on alignment-sensitive platforms.  #ifdef them away to save noise,
311290000Sglebius * build time, and binary space, but retain the code in case we find a
312290000Sglebius * use.
313290000Sglebius */
314290000Sglebius#ifdef COMPILE_UNUSED_FUNCTIONS
315290000Sglebius/*
316290000Sglebius * Array versions of the above information to make code run faster --
317290000Sglebius * relies on fact that TYPE_i == i.
318290000Sglebius */
319290000Sglebius#define	MAX_TYPES	5		/* max number of types above */
320290000Sglebius
321290000Sglebiusstatic long degrees[MAX_TYPES] =	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
322290000Sglebiusstatic long seps [MAX_TYPES] =	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
323290000Sglebius
324290000Sglebius/*
325181834Sroberto * initstate:
326181834Sroberto *
327181834Sroberto * Initialize the state information in the given array of n bytes for future
328181834Sroberto * random number generation.  Based on the number of bytes we are given, and
329181834Sroberto * the break values for the different R.N.G.'s, we choose the best (largest)
330181834Sroberto * one we can and set things up for it.  srandom() is then called to
331181834Sroberto * initialize the state information.
332181834Sroberto *
333181834Sroberto * Note that on return from srandom(), we set state[-1] to be the type
334181834Sroberto * multiplexed with the current value of the rear pointer; this is so
335181834Sroberto * successive calls to initstate() won't lose this information and will be
336181834Sroberto * able to restart with setstate().
337181834Sroberto *
338181834Sroberto * Note: the first thing we do is save the current state, if any, just like
339181834Sroberto * setstate() so that it doesn't matter when initstate is called.
340181834Sroberto *
341181834Sroberto * Returns a pointer to the old state.
342181834Sroberto *
343181834Sroberto * Note: The Sparc platform requires that arg_state begin on a long
344181834Sroberto * word boundary; otherwise a bus error will occur. Even so, lint will
345181834Sroberto * complain about mis-alignment, but you should disregard these messages.
346181834Sroberto */
347181834Srobertochar *
348181834Srobertontp_initstate(
349181834Sroberto	unsigned long seed,		/* seed for R.N.G. */
350181834Sroberto	char *arg_state,		/* pointer to state array */
351181834Sroberto	long n				/* # bytes of state info */
352181834Sroberto	)
353181834Sroberto{
354181834Sroberto	register char *ostate = (char *)(&state[-1]);
355181834Sroberto	register long *long_arg_state = (long *) arg_state;
356181834Sroberto
357181834Sroberto	if (rand_type == TYPE_0)
358181834Sroberto		state[-1] = rand_type;
359181834Sroberto	else
360181834Sroberto		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
361181834Sroberto	if (n < BREAK_0) {
362181834Sroberto		(void)fprintf(stderr,
363181834Sroberto		    "random: not enough state (%ld bytes); ignored.\n", n);
364181834Sroberto		return(0);
365181834Sroberto	}
366181834Sroberto	if (n < BREAK_1) {
367181834Sroberto		rand_type = TYPE_0;
368181834Sroberto		rand_deg = DEG_0;
369181834Sroberto		rand_sep = SEP_0;
370181834Sroberto	} else if (n < BREAK_2) {
371181834Sroberto		rand_type = TYPE_1;
372181834Sroberto		rand_deg = DEG_1;
373181834Sroberto		rand_sep = SEP_1;
374181834Sroberto	} else if (n < BREAK_3) {
375181834Sroberto		rand_type = TYPE_2;
376181834Sroberto		rand_deg = DEG_2;
377181834Sroberto		rand_sep = SEP_2;
378181834Sroberto	} else if (n < BREAK_4) {
379181834Sroberto		rand_type = TYPE_3;
380181834Sroberto		rand_deg = DEG_3;
381181834Sroberto		rand_sep = SEP_3;
382181834Sroberto	} else {
383181834Sroberto		rand_type = TYPE_4;
384181834Sroberto		rand_deg = DEG_4;
385181834Sroberto		rand_sep = SEP_4;
386181834Sroberto	}
387290000Sglebius	state = (unsigned long *) (long_arg_state + 1); /* first location */
388181834Sroberto	end_ptr = &state[rand_deg];	/* must set end_ptr before srandom */
389181834Sroberto	ntp_srandom(seed);
390181834Sroberto	if (rand_type == TYPE_0)
391181834Sroberto		long_arg_state[0] = rand_type;
392181834Sroberto	else
393181834Sroberto		long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
394181834Sroberto	return(ostate);
395181834Sroberto}
396181834Sroberto
397181834Sroberto/*
398181834Sroberto * setstate:
399181834Sroberto *
400181834Sroberto * Restore the state from the given state array.
401181834Sroberto *
402181834Sroberto * Note: it is important that we also remember the locations of the pointers
403181834Sroberto * in the current state information, and restore the locations of the pointers
404181834Sroberto * from the old state information.  This is done by multiplexing the pointer
405181834Sroberto * location into the zeroeth word of the state information.
406181834Sroberto *
407181834Sroberto * Note that due to the order in which things are done, it is OK to call
408181834Sroberto * setstate() with the same state as the current state.
409181834Sroberto *
410181834Sroberto * Returns a pointer to the old state information.
411181834Sroberto *
412181834Sroberto * Note: The Sparc platform requires that arg_state begin on a long
413181834Sroberto * word boundary; otherwise a bus error will occur. Even so, lint will
414181834Sroberto * complain about mis-alignment, but you should disregard these messages.
415181834Sroberto */
416181834Srobertochar *
417181834Srobertontp_setstate(
418181834Sroberto	char *arg_state			/* pointer to state array */
419181834Sroberto	)
420181834Sroberto{
421290000Sglebius	register unsigned long *new_state = (unsigned long *) arg_state;
422181834Sroberto	register long type = new_state[0] % MAX_TYPES;
423181834Sroberto	register long rear = new_state[0] / MAX_TYPES;
424181834Sroberto	char *ostate = (char *)(&state[-1]);
425181834Sroberto
426181834Sroberto	if (rand_type == TYPE_0)
427181834Sroberto		state[-1] = rand_type;
428181834Sroberto	else
429181834Sroberto		state[-1] = MAX_TYPES * (rptr - state) + rand_type;
430181834Sroberto	switch(type) {
431181834Sroberto	case TYPE_0:
432181834Sroberto	case TYPE_1:
433181834Sroberto	case TYPE_2:
434181834Sroberto	case TYPE_3:
435181834Sroberto	case TYPE_4:
436181834Sroberto		rand_type = type;
437181834Sroberto		rand_deg = degrees[type];
438181834Sroberto		rand_sep = seps[type];
439181834Sroberto		break;
440181834Sroberto	default:
441181834Sroberto		(void)fprintf(stderr,
442181834Sroberto		    "random: state info corrupted; not changed.\n");
443181834Sroberto	}
444290000Sglebius	state = (new_state + 1);
445181834Sroberto	if (rand_type != TYPE_0) {
446181834Sroberto		rptr = &state[rear];
447181834Sroberto		fptr = &state[(rear + rand_sep) % rand_deg];
448181834Sroberto	}
449181834Sroberto	end_ptr = &state[rand_deg];		/* set end_ptr too */
450181834Sroberto	return(ostate);
451181834Sroberto}
452290000Sglebius#endif	/* COMPILE_UNUSED_FUNCTIONS */
453181834Sroberto
454290000Sglebius
455181834Sroberto/*
456181834Sroberto * random:
457181834Sroberto *
458181834Sroberto * If we are using the trivial TYPE_0 R.N.G., just do the old linear
459181834Sroberto * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
460181834Sroberto * the same in all the other cases due to all the global variables that have
461181834Sroberto * been set up.  The basic operation is to add the number at the rear pointer
462181834Sroberto * into the one at the front pointer.  Then both pointers are advanced to
463181834Sroberto * the next location cyclically in the table.  The value returned is the sum
464181834Sroberto * generated, reduced to 31 bits by throwing away the "least random" low bit.
465181834Sroberto *
466181834Sroberto * Note: the code takes advantage of the fact that both the front and
467181834Sroberto * rear pointers can't wrap on the same call by not testing the rear
468181834Sroberto * pointer if the front one has wrapped.
469181834Sroberto *
470181834Sroberto * Returns a 31-bit random number.
471181834Sroberto */
472181834Srobertolong
473181834Srobertontp_random( void )
474181834Sroberto{
475181834Sroberto	register long i;
476290000Sglebius	register unsigned long *f, *r;
477181834Sroberto
478181834Sroberto	if (rand_type == TYPE_0) {
479181834Sroberto		i = state[0];
480181834Sroberto		state[0] = i = (good_rand(i)) & 0x7fffffff;
481181834Sroberto	} else {
482181834Sroberto		/*
483181834Sroberto		 * Use local variables rather than static variables for speed.
484181834Sroberto		 */
485181834Sroberto		f = fptr; r = rptr;
486181834Sroberto		*f += *r;
487181834Sroberto		i = (*f >> 1) & 0x7fffffff;	/* chucking least random bit */
488181834Sroberto		if (++f >= end_ptr) {
489181834Sroberto			f = state;
490181834Sroberto			++r;
491181834Sroberto		}
492181834Sroberto		else if (++r >= end_ptr) {
493181834Sroberto			r = state;
494181834Sroberto		}
495181834Sroberto
496181834Sroberto		fptr = f; rptr = r;
497181834Sroberto	}
498181834Sroberto	return(i);
499181834Sroberto}
500