coldboot: add lfsr.h by Anton Blanchard
[ls2.git] / coldboot / lfsr.h
1 #include <limits.h>
2
3 /*
4 * Copyright (C) 2020, Anton Blanchard <anton@linux.ibm.com>, IBM
5 *
6 * Redistribution and use in source and binary forms, with or without modification,
7 * are permitted provided that the following conditions are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright notice, this
10 * list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
19 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
22 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 /*
28 * Galois LFSR
29 *
30 * Polynomials verified with https://bitbucket.org/gallen/mlpolygen/
31 */
32 static inline unsigned long lfsr(unsigned long bits, unsigned long prev)
33 {
34 static const unsigned long lfsr_taps[] = {
35 0x0,
36 0x0,
37 0x3,
38 0x6,
39 0xc,
40 0x14,
41 0x30,
42 0x60,
43 0xb8,
44 0x110,
45 0x240,
46 0x500,
47 0x829,
48 0x100d,
49 0x2015,
50 0x6000,
51 0xd008,
52 0x12000,
53 0x20400,
54 0x40023,
55 0x90000,
56 0x140000,
57 0x300000,
58 0x420000,
59 0xe10000,
60 0x1200000,
61 0x2000023,
62 0x4000013,
63 0x9000000,
64 0x14000000,
65 0x20000029,
66 0x48000000,
67 0x80200003,
68 #ifdef __LP64__
69 0x100080000,
70 0x204000003,
71 0x500000000,
72 0x801000000,
73 0x100000001f,
74 0x2000000031,
75 0x4400000000,
76 0xa000140000,
77 0x12000000000,
78 0x300000c0000,
79 0x63000000000,
80 0xc0000030000,
81 0x1b0000000000,
82 0x300003000000,
83 0x420000000000,
84 0xc00000180000,
85 0x1008000000000,
86 0x3000000c00000,
87 0x6000c00000000,
88 0x9000000000000,
89 0x18003000000000,
90 0x30000000030000,
91 0x40000040000000,
92 0xc0000600000000,
93 0x102000000000000,
94 0x200004000000000,
95 0x600003000000000,
96 0xc00000000000000,
97 0x1800300000000000,
98 0x3000000000000030,
99 0x6000000000000000,
100 0x800000000000000d
101 #endif
102 };
103 unsigned long lsb = prev & 1;
104
105 prev >>= 1;
106 prev ^= (-lsb) & lfsr_taps[bits];
107
108 return prev;
109 }