/*1* Copyright (c) 1983, 19932* The Regents of the University of California. All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12* 3. All advertising materials mentioning features or use of this software13* must display the following acknowledgement:14* This product includes software developed by the University of15* California, Berkeley and its contributors.16* 4. Neither the name of the University nor the names of its contributors17* may be used to endorse or promote products derived from this software18* without specific prior written permission.19*20* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND21* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE22* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE23* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE24* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL25* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS26* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)27* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT28* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY29* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF30* SUCH DAMAGE.31*/3233/*34* From:35* NetBSD: random.c,v 1.19 2000/01/22 22:19:20 mycroft Exp36*37* Hacked gruesomely for OS/161.38*/3940#include <assert.h>41#include <errno.h>42#include <stdlib.h>4344/*45* For a thread-safe libc, declare a lock for this file and change46* these to be nonempty.47*/48#define LOCKME()49#define UNLOCKME()5051static void srandom_unlocked(unsigned long);52static long random_unlocked(void);535455/*56* random.c:57*58* An improved random number generation package. In addition to the standard59* rand()/srand() like interface, this package also has a special state info60* interface. The initstate() routine is called with a seed, an array of61* bytes, and a count of how many bytes are being passed in; this array is62* then initialized to contain information for random number generation with63* that much state information. Good sizes for the amount of state64* information are 32, 64, 128, and 256 bytes. The state can be switched by65* calling the setstate() routine with the same array as was initiallized66* with initstate(). By default, the package runs with 128 bytes of state67* information and generates far better random numbers than a linear68* congruential generator. If the amount of state information is less than69* 32 bytes, a simple linear congruential R.N.G. is used.70*71* Internally, the state information is treated as an array of longs; the72* zeroeth element of the array is the type of R.N.G. being used (small73* integer); the remainder of the array is the state information for the74* R.N.G. Thus, 32 bytes of state information will give 7 longs worth of75* state information, which will allow a degree seven polynomial. (Note:76* the zeroeth word of state information also has some other information77* stored in it -- see setstate() for details).78*79* The random number generation technique is a linear feedback shift register80* approach, employing trinomials (since there are fewer terms to sum up that81* way). In this approach, the least significant bit of all the numbers in82* the state table will act as a linear feedback shift register, and will83* have period 2^deg - 1 (where deg is the degree of the polynomial being84* used, assuming that the polynomial is irreducible and primitive). The85* higher order bits will have longer periods, since their values are also86* influenced by pseudo-random carries out of the lower bits. The total87* period of the generator is approximately deg*(2**deg - 1); thus doubling88* the amount of state information has a vast influence on the period of the89* generator. Note: the deg*(2**deg - 1) is an approximation only good for90* large deg, when the period of the shift register is the dominant factor.91* With deg equal to seven, the period is actually much longer than the92* 7*(2**7 - 1) predicted by this formula.93*94* Modified 28 December 1994 by Jacob S. Rosenberg.95* The following changes have been made:96* All references to the type u_int have been changed to unsigned long.97* All references to type int have been changed to type long. Other98* cleanups have been made as well. A warning for both initstate and99* setstate has been inserted to the effect that on Sparc platforms100* the 'arg_state' variable must be forced to begin on word boundaries.101* This can be easily done by casting a long integer array to char *.102* The overall logic has been left STRICTLY alone. This software was103* tested on both a VAX and Sun SpacsStation with exactly the same104* results. The new version and the original give IDENTICAL results.105* The new version is somewhat faster than the original. As the106* documentation says: "By default, the package runs with 128 bytes of107* state information and generates far better random numbers than a linear108* congruential generator. If the amount of state information is less than109* 32 bytes, a simple linear congruential R.N.G. is used." For a buffer of110* 128 bytes, this new version runs about 19 percent faster and for a 16111* byte buffer it is about 5 percent faster.112*/113114/*115* For each of the currently supported random number generators, we have a116* break value on the amount of state information (you need at least this117* many bytes of state info to support this random number generator), a degree118* for the polynomial (actually a trinomial) that the R.N.G. is based on, and119* the separation between the two lower order coefficients of the trinomial.120*/121#define TYPE_0 0 /* linear congruential */122#define BREAK_0 8123#define DEG_0 0124#define SEP_0 0125126#define TYPE_1 1 /* x**7 + x**3 + 1 */127#define BREAK_1 32128#define DEG_1 7129#define SEP_1 3130131#define TYPE_2 2 /* x**15 + x + 1 */132#define BREAK_2 64133#define DEG_2 15134#define SEP_2 1135136#define TYPE_3 3 /* x**31 + x**3 + 1 */137#define BREAK_3 128138#define DEG_3 31139#define SEP_3 3140141#define TYPE_4 4 /* x**63 + x + 1 */142#define BREAK_4 256143#define DEG_4 63144#define SEP_4 1145146/*147* Array versions of the above information to make code run faster --148* relies on fact that TYPE_i == i.149*/150#define MAX_TYPES 5 /* max number of types above */151152static const int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };153static const int seps[MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };154155/*156* Initially, everything is set up as if from:157*158* initstate(1, &randtbl, 128);159*160* Note that this initialization takes advantage of the fact that srandom()161* advances the front and rear pointers 10*rand_deg times, and hence the162* rear pointer which starts at 0 will also end up at zero; thus the zeroeth163* element of the state information, which contains info about the current164* position of the rear pointer is just165*166* MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.167*/168169static long randtbl[DEG_3 + 1] = {170TYPE_3,171(long)0x9a319039L, (long)0x32d9c024L, (long)0x9b663182L,172(long)0x5da1f342L, (long)0xde3b81e0L, (long)0xdf0a6fb5L,173(long)0xf103bc02L, (long)0x48f340fbL, (long)0x7449e56bL,174(long)0xbeb1dbb0L, (long)0xab5c5918L, (long)0x946554fdL,175(long)0x8c2e680fL, (long)0xeb3d799fL, (long)0xb11ee0b7L,176(long)0x2d436b86L, (long)0xda672e2aL, (long)0x1588ca88L,177(long)0xe369735dL, (long)0x904f35f7L, (long)0xd7158fd6L,178(long)0x6fa6f051L, (long)0x616e6b96L, (long)0xac94efdcL,179(long)0x36413f93L, (long)0xc622c298L, (long)0xf5a42ab8L,180(long)0x8a88d77bL, (long)0xf5ad9d0eL, (long)0x8999220bL,181(long)0x27fb47b9L,182};183184/*185* fptr and rptr are two pointers into the state info, a front and a rear186* pointer. These two pointers are always rand_sep places aparts, as they187* cycle cyclically through the state information. (Yes, this does mean we188* could get away with just one pointer, but the code for random() is more189* efficient this way). The pointers are left positioned as they would be190* from the call191*192* initstate(1, randtbl, 128);193*194* (The position of the rear pointer, rptr, is really 0 (as explained above195* in the initialization of randtbl) because the state table pointer is set196* to point to randtbl[1] (as explained below).197*/198static long *fptr = &randtbl[SEP_3 + 1];199static long *rptr = &randtbl[1];200201/*202* The following things are the pointer to the state information table, the203* type of the current generator, the degree of the current polynomial being204* used, and the separation between the two pointers. Note that for efficiency205* of random(), we remember the first location of the state information, not206* the zeroeth. Hence it is valid to access state[-1], which is used to207* store the type of the R.N.G. Also, we remember the last location, since208* this is more efficient than indexing every time to find the address of209* the last element to see if the front and rear pointers have wrapped.210*/211static long *state = &randtbl[1];212static long rand_type = TYPE_3;213static int rand_deg = DEG_3;214static int rand_sep = SEP_3;215static long *end_ptr = &randtbl[DEG_3 + 1];216217/*218* srandom:219*220* Initialize the random number generator based on the given seed. If the221* type is the trivial no-state-information type, just remember the seed.222* Otherwise, initializes state[] based on the given "seed" via a linear223* congruential generator. Then, the pointers are set to known locations224* that are exactly rand_sep places apart. Lastly, it cycles the state225* information a given number of times to get rid of any initial dependencies226* introduced by the L.C.R.N.G. Note that the initialization of randtbl[]227* for default usage relies on values produced by this routine.228*/229static230void231srandom_unlocked(unsigned long x)232{233int i;234235if (rand_type == TYPE_0)236state[0] = x;237else {238state[0] = x;239for (i = 1; i < rand_deg; i++)240state[i] = 1103515245L * state[i - 1] + 12345L;241fptr = &state[rand_sep];242rptr = &state[0];243for (i = 0; i < 10 * rand_deg; i++)244(void)random_unlocked();245}246}247248void249srandom(unsigned long x)250{251252LOCKME();253srandom_unlocked(x);254UNLOCKME();255}256257/*258* initstate:259*260* Initialize the state information in the given array of n bytes for future261* random number generation. Based on the number of bytes we are given, and262* the break values for the different R.N.G.'s, we choose the best (largest)263* one we can and set things up for it. srandom() is then called to264* initialize the state information.265*266* Note that on return from srandom(), we set state[-1] to be the type267* multiplexed with the current value of the rear pointer; this is so268* successive calls to initstate() won't lose this information and will be269* able to restart with setstate().270*271* Note: the first thing we do is save the current state, if any, just like272* setstate() so that it doesn't matter when initstate is called.273*274* Returns a pointer to the old state.275*276* Note: The Sparc platform requires that arg_state begin on a long277* word boundary; otherwise a bus error will occur. Even so, lint will278* complain about mis-alignment, but you should disregard these messages.279*/280char *281initstate(282unsigned long seed, /* seed for R.N.G. */283char *arg_state, /* pointer to state array */284size_t n) /* # bytes of state info */285{286void *ostate = (void *)(&state[-1]);287long *long_arg_state;288289assert(arg_state != NULL);290291long_arg_state = (long *)(void *)arg_state;292293LOCKME();294if (rand_type == TYPE_0)295state[-1] = rand_type;296else297state[-1] = MAX_TYPES * (rptr - state) + rand_type;298if (n < BREAK_0) {299UNLOCKME();300return (NULL);301} else if (n < BREAK_1) {302rand_type = TYPE_0;303rand_deg = DEG_0;304rand_sep = SEP_0;305} else if (n < BREAK_2) {306rand_type = TYPE_1;307rand_deg = DEG_1;308rand_sep = SEP_1;309} else if (n < BREAK_3) {310rand_type = TYPE_2;311rand_deg = DEG_2;312rand_sep = SEP_2;313} else if (n < BREAK_4) {314rand_type = TYPE_3;315rand_deg = DEG_3;316rand_sep = SEP_3;317} else {318rand_type = TYPE_4;319rand_deg = DEG_4;320rand_sep = SEP_4;321}322state = (long *) (long_arg_state + 1); /* first location */323end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */324srandom_unlocked(seed);325if (rand_type == TYPE_0)326long_arg_state[0] = rand_type;327else328long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;329UNLOCKME();330return((char *)ostate);331}332333/*334* setstate:335*336* Restore the state from the given state array.337*338* Note: it is important that we also remember the locations of the pointers339* in the current state information, and restore the locations of the pointers340* from the old state information. This is done by multiplexing the pointer341* location into the zeroeth word of the state information.342*343* Note that due to the order in which things are done, it is OK to call344* setstate() with the same state as the current state.345*346* Returns a pointer to the old state information.347*348* Note: The Sparc platform requires that arg_state begin on a long349* word boundary; otherwise a bus error will occur. Even so, lint will350* complain about mis-alignment, but you should disregard these messages.351*/352char *353setstate(char *arg_state) /* pointer to state array */354{355long *new_state;356int type;357int rear;358void *ostate = (void *)(&state[-1]);359360assert(arg_state != NULL);361362new_state = (long *)(void *)arg_state;363type = (int)(new_state[0] % MAX_TYPES);364rear = (int)(new_state[0] / MAX_TYPES);365366LOCKME();367if (rand_type == TYPE_0)368state[-1] = rand_type;369else370state[-1] = MAX_TYPES * (rptr - state) + rand_type;371switch(type) {372case TYPE_0:373case TYPE_1:374case TYPE_2:375case TYPE_3:376case TYPE_4:377rand_type = type;378rand_deg = degrees[type];379rand_sep = seps[type];380break;381default:382UNLOCKME();383return (NULL);384}385state = (long *) (new_state + 1);386if (rand_type != TYPE_0) {387rptr = &state[rear];388fptr = &state[(rear + rand_sep) % rand_deg];389}390end_ptr = &state[rand_deg]; /* set end_ptr too */391UNLOCKME();392return((char *)ostate);393}394395/*396* random:397*398* If we are using the trivial TYPE_0 R.N.G., just do the old linear399* congruential bit. Otherwise, we do our fancy trinomial stuff, which is400* the same in all the other cases due to all the global variables that have401* been set up. The basic operation is to add the number at the rear pointer402* into the one at the front pointer. Then both pointers are advanced to403* the next location cyclically in the table. The value returned is the sum404* generated, reduced to 31 bits by throwing away the "least random" low bit.405*406* Note: the code takes advantage of the fact that both the front and407* rear pointers can't wrap on the same call by not testing the rear408* pointer if the front one has wrapped.409*410* Returns a 31-bit random number.411*/412static413long414random_unlocked(void)415{416long i;417long *f, *r;418419if (rand_type == TYPE_0) {420i = state[0];421state[0] = i = (i * 1103515245L + 12345L) & 0x7fffffff;422} else {423/*424* Use local variables rather than static variables for speed.425*/426f = fptr; r = rptr;427*f += *r;428/* chucking least random bit */429i = ((unsigned long)*f >> 1) & 0x7fffffff;430if (++f >= end_ptr) {431f = state;432++r;433}434else if (++r >= end_ptr) {435r = state;436}437438fptr = f; rptr = r;439}440return(i);441}442443long444random(void)445{446long r;447448LOCKME();449r = random_unlocked();450UNLOCKME();451return (r);452}453454455