xref: /OK3568_Linux_fs/kernel/lib/crc4.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun // SPDX-License-Identifier: GPL-2.0-only
2*4882a593Smuzhiyun /*
3*4882a593Smuzhiyun  * crc4.c - simple crc-4 calculations.
4*4882a593Smuzhiyun  */
5*4882a593Smuzhiyun 
6*4882a593Smuzhiyun #include <linux/crc4.h>
7*4882a593Smuzhiyun #include <linux/module.h>
8*4882a593Smuzhiyun 
9*4882a593Smuzhiyun static const uint8_t crc4_tab[] = {
10*4882a593Smuzhiyun 	0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2,
11*4882a593Smuzhiyun 	0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3,
12*4882a593Smuzhiyun };
13*4882a593Smuzhiyun 
14*4882a593Smuzhiyun /**
15*4882a593Smuzhiyun  * crc4 - calculate the 4-bit crc of a value.
16*4882a593Smuzhiyun  * @c:    starting crc4
17*4882a593Smuzhiyun  * @x:    value to checksum
18*4882a593Smuzhiyun  * @bits: number of bits in @x to checksum
19*4882a593Smuzhiyun  *
20*4882a593Smuzhiyun  * Returns the crc4 value of @x, using polynomial 0b10111.
21*4882a593Smuzhiyun  *
22*4882a593Smuzhiyun  * The @x value is treated as left-aligned, and bits above @bits are ignored
23*4882a593Smuzhiyun  * in the crc calculations.
24*4882a593Smuzhiyun  */
crc4(uint8_t c,uint64_t x,int bits)25*4882a593Smuzhiyun uint8_t crc4(uint8_t c, uint64_t x, int bits)
26*4882a593Smuzhiyun {
27*4882a593Smuzhiyun 	int i;
28*4882a593Smuzhiyun 
29*4882a593Smuzhiyun 	/* mask off anything above the top bit */
30*4882a593Smuzhiyun 	x &= (1ull << bits) - 1;
31*4882a593Smuzhiyun 
32*4882a593Smuzhiyun 	/* Align to 4-bits */
33*4882a593Smuzhiyun 	bits = (bits + 3) & ~0x3;
34*4882a593Smuzhiyun 
35*4882a593Smuzhiyun 	/* Calculate crc4 over four-bit nibbles, starting at the MSbit */
36*4882a593Smuzhiyun 	for (i = bits - 4; i >= 0; i -= 4)
37*4882a593Smuzhiyun 		c = crc4_tab[c ^ ((x >> i) & 0xf)];
38*4882a593Smuzhiyun 
39*4882a593Smuzhiyun 	return c;
40*4882a593Smuzhiyun }
41*4882a593Smuzhiyun EXPORT_SYMBOL_GPL(crc4);
42*4882a593Smuzhiyun 
43*4882a593Smuzhiyun MODULE_DESCRIPTION("CRC4 calculations");
44*4882a593Smuzhiyun MODULE_LICENSE("GPL");
45