iPXE
random.c
Go to the documentation of this file.
00001 /** @file
00002  *
00003  * Random number generation
00004  *
00005  */
00006 
00007 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
00008 
00009 #include <stdlib.h>
00010 #include <ipxe/timer.h>
00011 
00012 static int32_t rnd_seed = 0;
00013 
00014 /**
00015  * Seed the pseudo-random number generator
00016  *
00017  * @v seed              Seed value
00018  */
00019 void srandom ( unsigned int seed ) {
00020         rnd_seed = seed;
00021         if ( ! rnd_seed )
00022                 rnd_seed = 4; /* Chosen by fair dice roll */
00023 }
00024 
00025 /**
00026  * Generate a pseudo-random number between 0 and 2147483647L or 2147483562?
00027  *
00028  * @ret rand            Pseudo-random number
00029  */
00030 long int random ( void ) {
00031         int32_t q;
00032 
00033         if ( ! rnd_seed ) /* Initialize linear congruential generator */
00034                 srandom ( currticks() );
00035 
00036         /* simplified version of the LCG given in Bruce Schneier's
00037            "Applied Cryptography" */
00038         q = ( rnd_seed / 53668 );
00039         rnd_seed = ( 40014 * ( rnd_seed - 53668 * q ) - 12211 * q );
00040         if ( rnd_seed < 0 )
00041                 rnd_seed += 2147483563L;
00042         return rnd_seed;
00043 }