1 #include <stdlib.h>
2 #include <stdint.h>
3 #include "los_hwi.h"
4
5 /*
6 this code uses the same lagged fibonacci generator as the
7 original bsd random implementation except for the seeding
8 which was broken in the original
9 */
10
11 static uint32_t init[] = {
12 0x00000000,0x5851f42d,0xc0b18ccf,0xcbb5f646,
13 0xc7033129,0x30705b04,0x20fd5db4,0x9a8b7f78,
14 0x502959d8,0xab894868,0x6c0356a7,0x88cdb7ff,
15 0xb477d43f,0x70a3a52b,0xa8e4baf1,0xfd8341fc,
16 0x8ae16fd9,0x742d2f7a,0x0d1f0796,0x76035e09,
17 0x40f7702c,0x6fa72ca5,0xaaa84157,0x58a0df74,
18 0xc74a0364,0xae533cc4,0x04185faf,0x6de3b115,
19 0x0cab8628,0xf043bfa4,0x398150e9,0x37521657};
20
21 static int n = 31;
22 static int i = 3;
23 static int j = 0;
24 static uint32_t *x = init+1;
25
lcg31(uint32_t x)26 static uint32_t lcg31(uint32_t x) {
27 return (1103515245*x + 12345) & 0x7fffffff;
28 }
29
lcg64(uint64_t x)30 static uint64_t lcg64(uint64_t x) {
31 return 6364136223846793005ull*x + 1;
32 }
33
savestate(void)34 static void *savestate(void) {
35 x[-1] = (n<<16)|(i<<8)|j;
36 return x-1;
37 }
38
loadstate(uint32_t * state)39 static void loadstate(uint32_t *state) {
40 x = state+1;
41 n = x[-1]>>16;
42 i = (x[-1]>>8)&0xff;
43 j = x[-1]&0xff;
44 }
45
__srandom(unsigned seed)46 static void __srandom(unsigned seed) {
47 int k;
48 uint64_t s = seed;
49
50 if (n == 0) {
51 x[0] = s;
52 return;
53 }
54 i = n == 31 || n == 7 ? 3 : 1;
55 j = 0;
56 for (k = 0; k < n; k++) {
57 s = lcg64(s);
58 x[k] = s>>32;
59 }
60 /* make sure x contains at least one odd number */
61 x[0] |= 1;
62 }
63
srandom(unsigned seed)64 void srandom(unsigned seed) {
65 unsigned int intSave;
66
67 intSave = LOS_IntLock();
68 __srandom(seed);
69 LOS_IntRestore(intSave);
70 }
71
initstate(unsigned seed,char * state,size_t size)72 char *initstate(unsigned seed, char *state, size_t size) {
73 void *old;
74 unsigned int intSave;
75
76 if (size < 8)
77 return 0;
78
79 intSave = LOS_IntLock();
80 old = savestate();
81 if (size < 32)
82 n = 0;
83 else if (size < 64)
84 n = 7;
85 else if (size < 128)
86 n = 15;
87 else if (size < 256)
88 n = 31;
89 else
90 n = 63;
91 x = (uint32_t*)state + 1;
92 __srandom(seed);
93 savestate();
94 LOS_IntRestore(intSave);
95 return old;
96 }
97
setstate(char * state)98 char *setstate(char *state) {
99 void *old;
100 unsigned int intSave;
101
102 intSave = LOS_IntLock();
103 old = savestate();
104 loadstate((uint32_t*)state);
105 LOS_IntRestore(intSave);
106 return old;
107 }
108
random(void)109 long random(void) {
110 long k;
111 unsigned int intSave;
112
113 intSave = LOS_IntLock();
114 if (n == 0) {
115 k = x[0] = lcg31(x[0]);
116 goto end;
117 }
118 x[i] += x[j];
119 k = x[i]>>1;
120 if (++i == n)
121 i = 0;
122 if (++j == n)
123 j = 0;
124 end:
125 LOS_IntRestore(intSave);
126 return k;
127 }
128