xref: /openbmc/u-boot/drivers/mtd/ubi/crc32.c (revision de757a7a)
1 /*
2  * Oct 15, 2000 Matt Domsch <Matt_Domsch@dell.com>
3  * Nicer crc32 functions/docs submitted by linux@horizon.com.  Thanks!
4  * Code was from the public domain, copyright abandoned.  Code was
5  * subsequently included in the kernel, thus was re-licensed under the
6  * GNU GPL v2.
7  *
8  * Oct 12, 2000 Matt Domsch <Matt_Domsch@dell.com>
9  * Same crc32 function was used in 5 other places in the kernel.
10  * I made one version, and deleted the others.
11  * There are various incantations of crc32().  Some use a seed of 0 or ~0.
12  * Some xor at the end with ~0.  The generic crc32() function takes
13  * seed as an argument, and doesn't xor at the end.  Then individual
14  * users can do whatever they need.
15  *   drivers/net/smc9194.c uses seed ~0, doesn't xor with ~0.
16  *   fs/jffs2 uses seed 0, doesn't xor with ~0.
17  *   fs/partitions/efi.c uses seed ~0, xor's with ~0.
18  *
19  * This source code is licensed under the GNU General Public License,
20  * Version 2.  See the file COPYING for more details.
21  */
22 
23 #ifdef UBI_LINUX
24 #include <linux/crc32.h>
25 #include <linux/kernel.h>
26 #include <linux/module.h>
27 #include <linux/compiler.h>
28 #endif
29 #include <linux/types.h>
30 
31 #include <asm/byteorder.h>
32 
33 #ifdef UBI_LINUX
34 #include <linux/slab.h>
35 #include <linux/init.h>
36 #include <asm/atomic.h>
37 #endif
38 #include "crc32defs.h"
39 #define CRC_LE_BITS 8
40 
41 #if CRC_LE_BITS == 8
42 #define tole(x) cpu_to_le32(x)
43 #define tobe(x) cpu_to_be32(x)
44 #else
45 #define tole(x) (x)
46 #define tobe(x) (x)
47 #endif
48 #include "crc32table.h"
49 #ifdef UBI_LINUX
50 MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
51 MODULE_DESCRIPTION("Ethernet CRC32 calculations");
52 MODULE_LICENSE("GPL");
53 #endif
54 /**
55  * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
56  * @crc: seed value for computation.  ~0 for Ethernet, sometimes 0 for
57  *	other uses, or the previous crc32 value if computing incrementally.
58  * @p: pointer to buffer over which CRC is run
59  * @len: length of buffer @p
60  */
61 u32  crc32_le(u32 crc, unsigned char const *p, size_t len);
62 
63 #if CRC_LE_BITS == 1
64 /*
65  * In fact, the table-based code will work in this case, but it can be
66  * simplified by inlining the table in ?: form.
67  */
68 
69 u32 crc32_le(u32 crc, unsigned char const *p, size_t len)
70 {
71 	int i;
72 	while (len--) {
73 		crc ^= *p++;
74 		for (i = 0; i < 8; i++)
75 			crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
76 	}
77 	return crc;
78 }
79 #else				/* Table-based approach */
80 
81 u32 crc32_le(u32 crc, unsigned char const *p, size_t len)
82 {
83 # if CRC_LE_BITS == 8
84 	const u32      *b =(u32 *)p;
85 	const u32      *tab = crc32table_le;
86 
87 # ifdef __LITTLE_ENDIAN
88 #  define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
89 # else
90 #  define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
91 # endif
92 	/* printf("Crc32_le crc=%x\n",crc); */
93 	crc = __cpu_to_le32(crc);
94 	/* Align it */
95 	if((((long)b)&3 && len)){
96 		do {
97 			u8 *p = (u8 *)b;
98 			DO_CRC(*p++);
99 			b = (void *)p;
100 		} while ((--len) && ((long)b)&3 );
101 	}
102 	if((len >= 4)){
103 		/* load data 32 bits wide, xor data 32 bits wide. */
104 		size_t save_len = len & 3;
105 	        len = len >> 2;
106 		--b; /* use pre increment below(*++b) for speed */
107 		do {
108 			crc ^= *++b;
109 			DO_CRC(0);
110 			DO_CRC(0);
111 			DO_CRC(0);
112 			DO_CRC(0);
113 		} while (--len);
114 		b++; /* point to next byte(s) */
115 		len = save_len;
116 	}
117 	/* And the last few bytes */
118 	if(len){
119 		do {
120 			u8 *p = (u8 *)b;
121 			DO_CRC(*p++);
122 			b = (void *)p;
123 		} while (--len);
124 	}
125 
126 	return __le32_to_cpu(crc);
127 #undef ENDIAN_SHIFT
128 #undef DO_CRC
129 
130 # elif CRC_LE_BITS == 4
131 	while (len--) {
132 		crc ^= *p++;
133 		crc = (crc >> 4) ^ crc32table_le[crc & 15];
134 		crc = (crc >> 4) ^ crc32table_le[crc & 15];
135 	}
136 	return crc;
137 # elif CRC_LE_BITS == 2
138 	while (len--) {
139 		crc ^= *p++;
140 		crc = (crc >> 2) ^ crc32table_le[crc & 3];
141 		crc = (crc >> 2) ^ crc32table_le[crc & 3];
142 		crc = (crc >> 2) ^ crc32table_le[crc & 3];
143 		crc = (crc >> 2) ^ crc32table_le[crc & 3];
144 	}
145 	return crc;
146 # endif
147 }
148 #endif
149 #ifdef UBI_LINUX
150 /**
151  * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
152  * @crc: seed value for computation.  ~0 for Ethernet, sometimes 0 for
153  *	other uses, or the previous crc32 value if computing incrementally.
154  * @p: pointer to buffer over which CRC is run
155  * @len: length of buffer @p
156  */
157 u32 __attribute_pure__ crc32_be(u32 crc, unsigned char const *p, size_t len);
158 
159 #if CRC_BE_BITS == 1
160 /*
161  * In fact, the table-based code will work in this case, but it can be
162  * simplified by inlining the table in ?: form.
163  */
164 
165 u32 __attribute_pure__ crc32_be(u32 crc, unsigned char const *p, size_t len)
166 {
167 	int i;
168 	while (len--) {
169 		crc ^= *p++ << 24;
170 		for (i = 0; i < 8; i++)
171 			crc =
172 			    (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :
173 					  0);
174 	}
175 	return crc;
176 }
177 
178 #else				/* Table-based approach */
179 u32 __attribute_pure__ crc32_be(u32 crc, unsigned char const *p, size_t len)
180 {
181 # if CRC_BE_BITS == 8
182 	const u32      *b =(u32 *)p;
183 	const u32      *tab = crc32table_be;
184 
185 # ifdef __LITTLE_ENDIAN
186 #  define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
187 # else
188 #  define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
189 # endif
190 
191 	crc = __cpu_to_be32(crc);
192 	/* Align it */
193 	if(unlikely(((long)b)&3 && len)){
194 		do {
195 			u8 *p = (u8 *)b;
196 			DO_CRC(*p++);
197 			b = (u32 *)p;
198 		} while ((--len) && ((long)b)&3 );
199 	}
200 	if(likely(len >= 4)){
201 		/* load data 32 bits wide, xor data 32 bits wide. */
202 		size_t save_len = len & 3;
203 	        len = len >> 2;
204 		--b; /* use pre increment below(*++b) for speed */
205 		do {
206 			crc ^= *++b;
207 			DO_CRC(0);
208 			DO_CRC(0);
209 			DO_CRC(0);
210 			DO_CRC(0);
211 		} while (--len);
212 		b++; /* point to next byte(s) */
213 		len = save_len;
214 	}
215 	/* And the last few bytes */
216 	if(len){
217 		do {
218 			u8 *p = (u8 *)b;
219 			DO_CRC(*p++);
220 			b = (void *)p;
221 		} while (--len);
222 	}
223 	return __be32_to_cpu(crc);
224 #undef ENDIAN_SHIFT
225 #undef DO_CRC
226 
227 # elif CRC_BE_BITS == 4
228 	while (len--) {
229 		crc ^= *p++ << 24;
230 		crc = (crc << 4) ^ crc32table_be[crc >> 28];
231 		crc = (crc << 4) ^ crc32table_be[crc >> 28];
232 	}
233 	return crc;
234 # elif CRC_BE_BITS == 2
235 	while (len--) {
236 		crc ^= *p++ << 24;
237 		crc = (crc << 2) ^ crc32table_be[crc >> 30];
238 		crc = (crc << 2) ^ crc32table_be[crc >> 30];
239 		crc = (crc << 2) ^ crc32table_be[crc >> 30];
240 		crc = (crc << 2) ^ crc32table_be[crc >> 30];
241 	}
242 	return crc;
243 # endif
244 }
245 #endif
246 
247 EXPORT_SYMBOL(crc32_le);
248 EXPORT_SYMBOL(crc32_be);
249 #endif
250 /*
251  * A brief CRC tutorial.
252  *
253  * A CRC is a long-division remainder.  You add the CRC to the message,
254  * and the whole thing (message+CRC) is a multiple of the given
255  * CRC polynomial.  To check the CRC, you can either check that the
256  * CRC matches the recomputed value, *or* you can check that the
257  * remainder computed on the message+CRC is 0.  This latter approach
258  * is used by a lot of hardware implementations, and is why so many
259  * protocols put the end-of-frame flag after the CRC.
260  *
261  * It's actually the same long division you learned in school, except that
262  * - We're working in binary, so the digits are only 0 and 1, and
263  * - When dividing polynomials, there are no carries.  Rather than add and
264  *   subtract, we just xor.  Thus, we tend to get a bit sloppy about
265  *   the difference between adding and subtracting.
266  *
267  * A 32-bit CRC polynomial is actually 33 bits long.  But since it's
268  * 33 bits long, bit 32 is always going to be set, so usually the CRC
269  * is written in hex with the most significant bit omitted.  (If you're
270  * familiar with the IEEE 754 floating-point format, it's the same idea.)
271  *
272  * Note that a CRC is computed over a string of *bits*, so you have
273  * to decide on the endianness of the bits within each byte.  To get
274  * the best error-detecting properties, this should correspond to the
275  * order they're actually sent.  For example, standard RS-232 serial is
276  * little-endian; the most significant bit (sometimes used for parity)
277  * is sent last.  And when appending a CRC word to a message, you should
278  * do it in the right order, matching the endianness.
279  *
280  * Just like with ordinary division, the remainder is always smaller than
281  * the divisor (the CRC polynomial) you're dividing by.  Each step of the
282  * division, you take one more digit (bit) of the dividend and append it
283  * to the current remainder.  Then you figure out the appropriate multiple
284  * of the divisor to subtract to being the remainder back into range.
285  * In binary, it's easy - it has to be either 0 or 1, and to make the
286  * XOR cancel, it's just a copy of bit 32 of the remainder.
287  *
288  * When computing a CRC, we don't care about the quotient, so we can
289  * throw the quotient bit away, but subtract the appropriate multiple of
290  * the polynomial from the remainder and we're back to where we started,
291  * ready to process the next bit.
292  *
293  * A big-endian CRC written this way would be coded like:
294  * for (i = 0; i < input_bits; i++) {
295  * 	multiple = remainder & 0x80000000 ? CRCPOLY : 0;
296  * 	remainder = (remainder << 1 | next_input_bit()) ^ multiple;
297  * }
298  * Notice how, to get at bit 32 of the shifted remainder, we look
299  * at bit 31 of the remainder *before* shifting it.
300  *
301  * But also notice how the next_input_bit() bits we're shifting into
302  * the remainder don't actually affect any decision-making until
303  * 32 bits later.  Thus, the first 32 cycles of this are pretty boring.
304  * Also, to add the CRC to a message, we need a 32-bit-long hole for it at
305  * the end, so we have to add 32 extra cycles shifting in zeros at the
306  * end of every message,
307  *
308  * So the standard trick is to rearrage merging in the next_input_bit()
309  * until the moment it's needed.  Then the first 32 cycles can be precomputed,
310  * and merging in the final 32 zero bits to make room for the CRC can be
311  * skipped entirely.
312  * This changes the code to:
313  * for (i = 0; i < input_bits; i++) {
314  *      remainder ^= next_input_bit() << 31;
315  * 	multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
316  * 	remainder = (remainder << 1) ^ multiple;
317  * }
318  * With this optimization, the little-endian code is simpler:
319  * for (i = 0; i < input_bits; i++) {
320  *      remainder ^= next_input_bit();
321  * 	multiple = (remainder & 1) ? CRCPOLY : 0;
322  * 	remainder = (remainder >> 1) ^ multiple;
323  * }
324  *
325  * Note that the other details of endianness have been hidden in CRCPOLY
326  * (which must be bit-reversed) and next_input_bit().
327  *
328  * However, as long as next_input_bit is returning the bits in a sensible
329  * order, we can actually do the merging 8 or more bits at a time rather
330  * than one bit at a time:
331  * for (i = 0; i < input_bytes; i++) {
332  * 	remainder ^= next_input_byte() << 24;
333  * 	for (j = 0; j < 8; j++) {
334  * 		multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
335  * 		remainder = (remainder << 1) ^ multiple;
336  * 	}
337  * }
338  * Or in little-endian:
339  * for (i = 0; i < input_bytes; i++) {
340  * 	remainder ^= next_input_byte();
341  * 	for (j = 0; j < 8; j++) {
342  * 		multiple = (remainder & 1) ? CRCPOLY : 0;
343  * 		remainder = (remainder << 1) ^ multiple;
344  * 	}
345  * }
346  * If the input is a multiple of 32 bits, you can even XOR in a 32-bit
347  * word at a time and increase the inner loop count to 32.
348  *
349  * You can also mix and match the two loop styles, for example doing the
350  * bulk of a message byte-at-a-time and adding bit-at-a-time processing
351  * for any fractional bytes at the end.
352  *
353  * The only remaining optimization is to the byte-at-a-time table method.
354  * Here, rather than just shifting one bit of the remainder to decide
355  * in the correct multiple to subtract, we can shift a byte at a time.
356  * This produces a 40-bit (rather than a 33-bit) intermediate remainder,
357  * but again the multiple of the polynomial to subtract depends only on
358  * the high bits, the high 8 bits in this case.
359  *
360  * The multile we need in that case is the low 32 bits of a 40-bit
361  * value whose high 8 bits are given, and which is a multiple of the
362  * generator polynomial.  This is simply the CRC-32 of the given
363  * one-byte message.
364  *
365  * Two more details: normally, appending zero bits to a message which
366  * is already a multiple of a polynomial produces a larger multiple of that
367  * polynomial.  To enable a CRC to detect this condition, it's common to
368  * invert the CRC before appending it.  This makes the remainder of the
369  * message+crc come out not as zero, but some fixed non-zero value.
370  *
371  * The same problem applies to zero bits prepended to the message, and
372  * a similar solution is used.  Instead of starting with a remainder of
373  * 0, an initial remainder of all ones is used.  As long as you start
374  * the same way on decoding, it doesn't make a difference.
375  */
376 
377 #ifdef UNITTEST
378 
379 #include <stdlib.h>
380 #include <stdio.h>
381 
382 #ifdef UBI_LINUX				/*Not used at present */
383 static void
384 buf_dump(char const *prefix, unsigned char const *buf, size_t len)
385 {
386 	fputs(prefix, stdout);
387 	while (len--)
388 		printf(" %02x", *buf++);
389 	putchar('\n');
390 
391 }
392 #endif
393 
394 static void bytereverse(unsigned char *buf, size_t len)
395 {
396 	while (len--) {
397 		unsigned char x = bitrev8(*buf);
398 		*buf++ = x;
399 	}
400 }
401 
402 static void random_garbage(unsigned char *buf, size_t len)
403 {
404 	while (len--)
405 		*buf++ = (unsigned char) random();
406 }
407 
408 #ifdef UBI_LINUX				/* Not used at present */
409 static void store_le(u32 x, unsigned char *buf)
410 {
411 	buf[0] = (unsigned char) x;
412 	buf[1] = (unsigned char) (x >> 8);
413 	buf[2] = (unsigned char) (x >> 16);
414 	buf[3] = (unsigned char) (x >> 24);
415 }
416 #endif
417 
418 static void store_be(u32 x, unsigned char *buf)
419 {
420 	buf[0] = (unsigned char) (x >> 24);
421 	buf[1] = (unsigned char) (x >> 16);
422 	buf[2] = (unsigned char) (x >> 8);
423 	buf[3] = (unsigned char) x;
424 }
425 
426 /*
427  * This checks that CRC(buf + CRC(buf)) = 0, and that
428  * CRC commutes with bit-reversal.  This has the side effect
429  * of bytewise bit-reversing the input buffer, and returns
430  * the CRC of the reversed buffer.
431  */
432 static u32 test_step(u32 init, unsigned char *buf, size_t len)
433 {
434 	u32 crc1, crc2;
435 	size_t i;
436 
437 	crc1 = crc32_be(init, buf, len);
438 	store_be(crc1, buf + len);
439 	crc2 = crc32_be(init, buf, len + 4);
440 	if (crc2)
441 		printf("\nCRC cancellation fail: 0x%08x should be 0\n",
442 		       crc2);
443 
444 	for (i = 0; i <= len + 4; i++) {
445 		crc2 = crc32_be(init, buf, i);
446 		crc2 = crc32_be(crc2, buf + i, len + 4 - i);
447 		if (crc2)
448 			printf("\nCRC split fail: 0x%08x\n", crc2);
449 	}
450 
451 	/* Now swap it around for the other test */
452 
453 	bytereverse(buf, len + 4);
454 	init = bitrev32(init);
455 	crc2 = bitrev32(crc1);
456 	if (crc1 != bitrev32(crc2))
457 		printf("\nBit reversal fail: 0x%08x -> 0x%08x -> 0x%08x\n",
458 		       crc1, crc2, bitrev32(crc2));
459 	crc1 = crc32_le(init, buf, len);
460 	if (crc1 != crc2)
461 		printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,
462 		       crc2);
463 	crc2 = crc32_le(init, buf, len + 4);
464 	if (crc2)
465 		printf("\nCRC cancellation fail: 0x%08x should be 0\n",
466 		       crc2);
467 
468 	for (i = 0; i <= len + 4; i++) {
469 		crc2 = crc32_le(init, buf, i);
470 		crc2 = crc32_le(crc2, buf + i, len + 4 - i);
471 		if (crc2)
472 			printf("\nCRC split fail: 0x%08x\n", crc2);
473 	}
474 
475 	return crc1;
476 }
477 
478 #define SIZE 64
479 #define INIT1 0
480 #define INIT2 0
481 
482 int main(void)
483 {
484 	unsigned char buf1[SIZE + 4];
485 	unsigned char buf2[SIZE + 4];
486 	unsigned char buf3[SIZE + 4];
487 	int i, j;
488 	u32 crc1, crc2, crc3;
489 
490 	for (i = 0; i <= SIZE; i++) {
491 		printf("\rTesting length %d...", i);
492 		fflush(stdout);
493 		random_garbage(buf1, i);
494 		random_garbage(buf2, i);
495 		for (j = 0; j < i; j++)
496 			buf3[j] = buf1[j] ^ buf2[j];
497 
498 		crc1 = test_step(INIT1, buf1, i);
499 		crc2 = test_step(INIT2, buf2, i);
500 		/* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */
501 		crc3 = test_step(INIT1 ^ INIT2, buf3, i);
502 		if (crc3 != (crc1 ^ crc2))
503 			printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",
504 			       crc3, crc1, crc2);
505 	}
506 	printf("\nAll test complete.  No failures expected.\n");
507 	return 0;
508 }
509 
510 #endif				/* UNITTEST */
511