[PATCH] DVB: Other DVB core updates
[linux-2.6/history.git] / lib / crc32.c
blob33c33fdd5bf17f3ecf744efad94facb2ea92f552
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.
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.
19 * This source code is licensed under the GNU General Public License,
20 * Version 2. See the file COPYING for more details.
23 #include <linux/crc32.h>
24 #include <linux/kernel.h>
25 #include <linux/module.h>
26 #include <linux/types.h>
27 #include <linux/slab.h>
28 #include <linux/init.h>
29 #include <asm/atomic.h>
30 #include "crc32defs.h"
31 #if CRC_LE_BITS == 8
32 #define tole(x) __constant_cpu_to_le32(x)
33 #define tobe(x) __constant_cpu_to_be32(x)
34 #else
35 #define tole(x) (x)
36 #define tobe(x) (x)
37 #endif
38 #include "crc32table.h"
40 #if __GNUC__ >= 3 /* 2.x has "attribute", but only 3.0 has "pure */
41 #define attribute(x) __attribute__(x)
42 #else
43 #define attribute(x)
44 #endif
47 MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
48 MODULE_DESCRIPTION("Ethernet CRC32 calculations");
49 MODULE_LICENSE("GPL");
51 #if CRC_LE_BITS == 1
53 * In fact, the table-based code will work in this case, but it can be
54 * simplified by inlining the table in ?: form.
57 /**
58 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
59 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
60 * other uses, or the previous crc32 value if computing incrementally.
61 * @p - pointer to buffer over which CRC is run
62 * @len - length of buffer @p
65 u32 attribute((pure)) crc32_le(u32 crc, unsigned char const *p, size_t len)
67 int i;
68 while (len--) {
69 crc ^= *p++;
70 for (i = 0; i < 8; i++)
71 crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
73 return crc;
75 #else /* Table-based approach */
77 /**
78 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
79 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
80 * other uses, or the previous crc32 value if computing incrementally.
81 * @p - pointer to buffer over which CRC is run
82 * @len - length of buffer @p
85 u32 attribute((pure)) crc32_le(u32 crc, unsigned char const *p, size_t len)
87 # if CRC_LE_BITS == 8
88 const u32 *b =(u32 *)p;
89 const u32 *tab = crc32table_le;
91 # ifdef __LITTLE_ENDIAN
92 # define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
93 # else
94 # define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
95 # endif
97 crc = __cpu_to_le32(crc);
98 /* Align it */
99 if(unlikely(((long)b)&3 && len)){
100 do {
101 u8 *p = (u8 *)b;
102 DO_CRC(*p++);
103 b = (void *)p;
104 } while ((--len) && ((long)b)&3 );
106 if(likely(len >= 4)){
107 /* load data 32 bits wide, xor data 32 bits wide. */
108 size_t save_len = len & 3;
109 len = len >> 2;
110 --b; /* use pre increment below(*++b) for speed */
111 do {
112 crc ^= *++b;
113 DO_CRC(0);
114 DO_CRC(0);
115 DO_CRC(0);
116 DO_CRC(0);
117 } while (--len);
118 b++; /* point to next byte(s) */
119 len = save_len;
121 /* And the last few bytes */
122 if(len){
123 do {
124 u8 *p = (u8 *)b;
125 DO_CRC(*p++);
126 b = (void *)p;
127 } while (--len);
130 return __le32_to_cpu(crc);
131 #undef ENDIAN_SHIFT
132 #undef DO_CRC
134 # elif CRC_LE_BITS == 4
135 while (len--) {
136 crc ^= *p++;
137 crc = (crc >> 4) ^ crc32table_le[crc & 15];
138 crc = (crc >> 4) ^ crc32table_le[crc & 15];
140 return crc;
141 # elif CRC_LE_BITS == 2
142 while (len--) {
143 crc ^= *p++;
144 crc = (crc >> 2) ^ crc32table_le[crc & 3];
145 crc = (crc >> 2) ^ crc32table_le[crc & 3];
146 crc = (crc >> 2) ^ crc32table_le[crc & 3];
147 crc = (crc >> 2) ^ crc32table_le[crc & 3];
149 return crc;
150 # endif
152 #endif
154 #if CRC_BE_BITS == 1
156 * In fact, the table-based code will work in this case, but it can be
157 * simplified by inlining the table in ?: form.
161 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
162 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
163 * other uses, or the previous crc32 value if computing incrementally.
164 * @p - pointer to buffer over which CRC is run
165 * @len - length of buffer @p
168 u32 attribute((pure)) crc32_be(u32 crc, unsigned char const *p, size_t len)
170 int i;
171 while (len--) {
172 crc ^= *p++ << 24;
173 for (i = 0; i < 8; i++)
174 crc =
175 (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :
178 return crc;
181 #else /* Table-based approach */
183 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
184 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
185 * other uses, or the previous crc32 value if computing incrementally.
186 * @p - pointer to buffer over which CRC is run
187 * @len - length of buffer @p
190 u32 attribute((pure)) crc32_be(u32 crc, unsigned char const *p, size_t len)
192 # if CRC_BE_BITS == 8
193 const u32 *b =(u32 *)p;
194 const u32 *tab = crc32table_be;
196 # ifdef __LITTLE_ENDIAN
197 # define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
198 # else
199 # define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
200 # endif
202 crc = __cpu_to_be32(crc);
203 /* Align it */
204 if(unlikely(((long)b)&3 && len)){
205 do {
206 u8 *p = (u8 *)b;
207 DO_CRC(*p++);
208 b = (u32 *)p;
209 } while ((--len) && ((long)b)&3 );
211 if(likely(len >= 4)){
212 /* load data 32 bits wide, xor data 32 bits wide. */
213 size_t save_len = len & 3;
214 len = len >> 2;
215 --b; /* use pre increment below(*++b) for speed */
216 do {
217 crc ^= *++b;
218 DO_CRC(0);
219 DO_CRC(0);
220 DO_CRC(0);
221 DO_CRC(0);
222 } while (--len);
223 b++; /* point to next byte(s) */
224 len = save_len;
226 /* And the last few bytes */
227 if(len){
228 do {
229 u8 *p = (u8 *)b;
230 DO_CRC(*p++);
231 b = (void *)p;
232 } while (--len);
234 return __be32_to_cpu(crc);
235 #undef ENDIAN_SHIFT
236 #undef DO_CRC
238 # elif CRC_BE_BITS == 4
239 while (len--) {
240 crc ^= *p++ << 24;
241 crc = (crc << 4) ^ crc32table_be[crc >> 28];
242 crc = (crc << 4) ^ crc32table_be[crc >> 28];
244 return crc;
245 # elif CRC_BE_BITS == 2
246 while (len--) {
247 crc ^= *p++ << 24;
248 crc = (crc << 2) ^ crc32table_be[crc >> 30];
249 crc = (crc << 2) ^ crc32table_be[crc >> 30];
250 crc = (crc << 2) ^ crc32table_be[crc >> 30];
251 crc = (crc << 2) ^ crc32table_be[crc >> 30];
253 return crc;
254 # endif
256 #endif
258 u32 bitreverse(u32 x)
260 x = (x >> 16) | (x << 16);
261 x = (x >> 8 & 0x00ff00ff) | (x << 8 & 0xff00ff00);
262 x = (x >> 4 & 0x0f0f0f0f) | (x << 4 & 0xf0f0f0f0);
263 x = (x >> 2 & 0x33333333) | (x << 2 & 0xcccccccc);
264 x = (x >> 1 & 0x55555555) | (x << 1 & 0xaaaaaaaa);
265 return x;
268 EXPORT_SYMBOL(crc32_le);
269 EXPORT_SYMBOL(crc32_be);
270 EXPORT_SYMBOL(bitreverse);
273 * A brief CRC tutorial.
275 * A CRC is a long-division remainder. You add the CRC to the message,
276 * and the whole thing (message+CRC) is a multiple of the given
277 * CRC polynomial. To check the CRC, you can either check that the
278 * CRC matches the recomputed value, *or* you can check that the
279 * remainder computed on the message+CRC is 0. This latter approach
280 * is used by a lot of hardware implementations, and is why so many
281 * protocols put the end-of-frame flag after the CRC.
283 * It's actually the same long division you learned in school, except that
284 * - We're working in binary, so the digits are only 0 and 1, and
285 * - When dividing polynomials, there are no carries. Rather than add and
286 * subtract, we just xor. Thus, we tend to get a bit sloppy about
287 * the difference between adding and subtracting.
289 * A 32-bit CRC polynomial is actually 33 bits long. But since it's
290 * 33 bits long, bit 32 is always going to be set, so usually the CRC
291 * is written in hex with the most significant bit omitted. (If you're
292 * familiar with the IEEE 754 floating-point format, it's the same idea.)
294 * Note that a CRC is computed over a string of *bits*, so you have
295 * to decide on the endianness of the bits within each byte. To get
296 * the best error-detecting properties, this should correspond to the
297 * order they're actually sent. For example, standard RS-232 serial is
298 * little-endian; the most significant bit (sometimes used for parity)
299 * is sent last. And when appending a CRC word to a message, you should
300 * do it in the right order, matching the endianness.
302 * Just like with ordinary division, the remainder is always smaller than
303 * the divisor (the CRC polynomial) you're dividing by. Each step of the
304 * division, you take one more digit (bit) of the dividend and append it
305 * to the current remainder. Then you figure out the appropriate multiple
306 * of the divisor to subtract to being the remainder back into range.
307 * In binary, it's easy - it has to be either 0 or 1, and to make the
308 * XOR cancel, it's just a copy of bit 32 of the remainder.
310 * When computing a CRC, we don't care about the quotient, so we can
311 * throw the quotient bit away, but subtract the appropriate multiple of
312 * the polynomial from the remainder and we're back to where we started,
313 * ready to process the next bit.
315 * A big-endian CRC written this way would be coded like:
316 * for (i = 0; i < input_bits; i++) {
317 * multiple = remainder & 0x80000000 ? CRCPOLY : 0;
318 * remainder = (remainder << 1 | next_input_bit()) ^ multiple;
320 * Notice how, to get at bit 32 of the shifted remainder, we look
321 * at bit 31 of the remainder *before* shifting it.
323 * But also notice how the next_input_bit() bits we're shifting into
324 * the remainder don't actually affect any decision-making until
325 * 32 bits later. Thus, the first 32 cycles of this are pretty boring.
326 * Also, to add the CRC to a message, we need a 32-bit-long hole for it at
327 * the end, so we have to add 32 extra cycles shifting in zeros at the
328 * end of every message,
330 * So the standard trick is to rearrage merging in the next_input_bit()
331 * until the moment it's needed. Then the first 32 cycles can be precomputed,
332 * and merging in the final 32 zero bits to make room for the CRC can be
333 * skipped entirely.
334 * This changes the code to:
335 * for (i = 0; i < input_bits; i++) {
336 * remainder ^= next_input_bit() << 31;
337 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
338 * remainder = (remainder << 1) ^ multiple;
340 * With this optimization, the little-endian code is simpler:
341 * for (i = 0; i < input_bits; i++) {
342 * remainder ^= next_input_bit();
343 * multiple = (remainder & 1) ? CRCPOLY : 0;
344 * remainder = (remainder >> 1) ^ multiple;
347 * Note that the other details of endianness have been hidden in CRCPOLY
348 * (which must be bit-reversed) and next_input_bit().
350 * However, as long as next_input_bit is returning the bits in a sensible
351 * order, we can actually do the merging 8 or more bits at a time rather
352 * than one bit at a time:
353 * for (i = 0; i < input_bytes; i++) {
354 * remainder ^= next_input_byte() << 24;
355 * for (j = 0; j < 8; j++) {
356 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
357 * remainder = (remainder << 1) ^ multiple;
360 * Or in little-endian:
361 * for (i = 0; i < input_bytes; i++) {
362 * remainder ^= next_input_byte();
363 * for (j = 0; j < 8; j++) {
364 * multiple = (remainder & 1) ? CRCPOLY : 0;
365 * remainder = (remainder << 1) ^ multiple;
368 * If the input is a multiple of 32 bits, you can even XOR in a 32-bit
369 * word at a time and increase the inner loop count to 32.
371 * You can also mix and match the two loop styles, for example doing the
372 * bulk of a message byte-at-a-time and adding bit-at-a-time processing
373 * for any fractional bytes at the end.
375 * The only remaining optimization is to the byte-at-a-time table method.
376 * Here, rather than just shifting one bit of the remainder to decide
377 * in the correct multiple to subtract, we can shift a byte at a time.
378 * This produces a 40-bit (rather than a 33-bit) intermediate remainder,
379 * but again the multiple of the polynomial to subtract depends only on
380 * the high bits, the high 8 bits in this case.
382 * The multile we need in that case is the low 32 bits of a 40-bit
383 * value whose high 8 bits are given, and which is a multiple of the
384 * generator polynomial. This is simply the CRC-32 of the given
385 * one-byte message.
387 * Two more details: normally, appending zero bits to a message which
388 * is already a multiple of a polynomial produces a larger multiple of that
389 * polynomial. To enable a CRC to detect this condition, it's common to
390 * invert the CRC before appending it. This makes the remainder of the
391 * message+crc come out not as zero, but some fixed non-zero value.
393 * The same problem applies to zero bits prepended to the message, and
394 * a similar solution is used. Instead of starting with a remainder of
395 * 0, an initial remainder of all ones is used. As long as you start
396 * the same way on decoding, it doesn't make a difference.
399 #ifdef UNITTEST
401 #include <stdlib.h>
402 #include <stdio.h>
404 #if 0 /*Not used at present */
405 static void
406 buf_dump(char const *prefix, unsigned char const *buf, size_t len)
408 fputs(prefix, stdout);
409 while (len--)
410 printf(" %02x", *buf++);
411 putchar('\n');
414 #endif
416 static void bytereverse(unsigned char *buf, size_t len)
418 while (len--) {
419 unsigned char x = *buf;
420 x = (x >> 4) | (x << 4);
421 x = (x >> 2 & 0x33) | (x << 2 & 0xcc);
422 x = (x >> 1 & 0x55) | (x << 1 & 0xaa);
423 *buf++ = x;
427 static void random_garbage(unsigned char *buf, size_t len)
429 while (len--)
430 *buf++ = (unsigned char) random();
433 #if 0 /* Not used at present */
434 static void store_le(u32 x, unsigned char *buf)
436 buf[0] = (unsigned char) x;
437 buf[1] = (unsigned char) (x >> 8);
438 buf[2] = (unsigned char) (x >> 16);
439 buf[3] = (unsigned char) (x >> 24);
441 #endif
443 static void store_be(u32 x, unsigned char *buf)
445 buf[0] = (unsigned char) (x >> 24);
446 buf[1] = (unsigned char) (x >> 16);
447 buf[2] = (unsigned char) (x >> 8);
448 buf[3] = (unsigned char) x;
452 * This checks that CRC(buf + CRC(buf)) = 0, and that
453 * CRC commutes with bit-reversal. This has the side effect
454 * of bytewise bit-reversing the input buffer, and returns
455 * the CRC of the reversed buffer.
457 static u32 test_step(u32 init, unsigned char *buf, size_t len)
459 u32 crc1, crc2;
460 size_t i;
462 crc1 = crc32_be(init, buf, len);
463 store_be(crc1, buf + len);
464 crc2 = crc32_be(init, buf, len + 4);
465 if (crc2)
466 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
467 crc2);
469 for (i = 0; i <= len + 4; i++) {
470 crc2 = crc32_be(init, buf, i);
471 crc2 = crc32_be(crc2, buf + i, len + 4 - i);
472 if (crc2)
473 printf("\nCRC split fail: 0x%08x\n", crc2);
476 /* Now swap it around for the other test */
478 bytereverse(buf, len + 4);
479 init = bitreverse(init);
480 crc2 = bitreverse(crc1);
481 if (crc1 != bitreverse(crc2))
482 printf("\nBit reversal fail: 0x%08x -> %0x08x -> 0x%08x\n",
483 crc1, crc2, bitreverse(crc2));
484 crc1 = crc32_le(init, buf, len);
485 if (crc1 != crc2)
486 printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,
487 crc2);
488 crc2 = crc32_le(init, buf, len + 4);
489 if (crc2)
490 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
491 crc2);
493 for (i = 0; i <= len + 4; i++) {
494 crc2 = crc32_le(init, buf, i);
495 crc2 = crc32_le(crc2, buf + i, len + 4 - i);
496 if (crc2)
497 printf("\nCRC split fail: 0x%08x\n", crc2);
500 return crc1;
503 #define SIZE 64
504 #define INIT1 0
505 #define INIT2 0
507 int main(void)
509 unsigned char buf1[SIZE + 4];
510 unsigned char buf2[SIZE + 4];
511 unsigned char buf3[SIZE + 4];
512 int i, j;
513 u32 crc1, crc2, crc3;
515 for (i = 0; i <= SIZE; i++) {
516 printf("\rTesting length %d...", i);
517 fflush(stdout);
518 random_garbage(buf1, i);
519 random_garbage(buf2, i);
520 for (j = 0; j < i; j++)
521 buf3[j] = buf1[j] ^ buf2[j];
523 crc1 = test_step(INIT1, buf1, i);
524 crc2 = test_step(INIT2, buf2, i);
525 /* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */
526 crc3 = test_step(INIT1 ^ INIT2, buf3, i);
527 if (crc3 != (crc1 ^ crc2))
528 printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",
529 crc3, crc1, crc2);
531 printf("\nAll test complete. No failures expected.\n");
532 return 0;
535 #endif /* UNITTEST */