2 * Oct 15, 2000 Matt Domsch <Matt_Domsch@dell.com>
3 * Nicer crc32 functions/docs submitted by linux@horizon.com. Thanks!
5 * Oct 12, 2000 Matt Domsch <Matt_Domsch@dell.com>
6 * Same crc32 function was used in 5 other places in the kernel.
7 * I made one version, and deleted the others.
8 * There are various incantations of crc32(). Some use a seed of 0 or ~0.
9 * Some xor at the end with ~0. The generic crc32() function takes
10 * seed as an argument, and doesn't xor at the end. Then individual
11 * users can do whatever they need.
12 * drivers/net/smc9194.c uses seed ~0, doesn't xor with ~0.
13 * fs/jffs2 uses seed 0, doesn't xor with ~0.
14 * fs/partitions/efi.c uses seed ~0, xor's with ~0.
18 #include <linux/crc32.h>
19 #include <linux/kernel.h>
20 #include <linux/module.h>
21 #include <linux/types.h>
22 #include <linux/slab.h>
23 #include <linux/init.h>
24 #include <asm/atomic.h>
25 #include "crc32defs.h"
27 #define tole(x) __constant_cpu_to_le32(x)
28 #define tobe(x) __constant_cpu_to_be32(x)
33 #include "crc32table.h"
35 #if __GNUC__ >= 3 /* 2.x has "attribute", but only 3.0 has "pure */
36 #define attribute(x) __attribute__(x)
42 * This code is in the public domain; copyright abandoned.
43 * Liability for non-performance of this code is limited to the amount
44 * you paid for it. Since it is distributed for free, your refund will
45 * be very very small. If it breaks, you get to keep both pieces.
48 MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
49 MODULE_DESCRIPTION("Ethernet CRC32 calculations");
50 MODULE_LICENSE("GPL and additional rights");
54 * In fact, the table-based code will work in this case, but it can be
55 * simplified by inlining the table in ?: form.
59 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
60 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
61 * other uses, or the previous crc32 value if computing incrementally.
62 * @p - pointer to buffer over which CRC is run
63 * @len - length of buffer @p
66 u32
attribute((pure
)) crc32_le(u32 crc
, unsigned char const *p
, size_t len
)
71 for (i
= 0; i
< 8; i
++)
72 crc
= (crc
>> 1) ^ ((crc
& 1) ? CRCPOLY_LE
: 0);
76 #else /* Table-based approach */
79 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
80 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
81 * other uses, or the previous crc32 value if computing incrementally.
82 * @p - pointer to buffer over which CRC is run
83 * @len - length of buffer @p
86 u32
attribute((pure
)) crc32_le(u32 crc
, unsigned char const *p
, size_t len
)
89 const u32
*b
=(u32
*)p
;
90 const u32
*tab
= crc32table_le
;
92 # ifdef __LITTLE_ENDIAN
93 # define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
95 # define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
98 crc
= __cpu_to_le32(crc
);
100 if(unlikely(((long)b
)&3 && len
)){
102 DO_CRC(*((u8
*)b
)++);
103 } while ((--len
) && ((long)b
)&3 );
105 if(likely(len
>= 4)){
106 /* load data 32 bits wide, xor data 32 bits wide. */
107 size_t save_len
= len
& 3;
109 --b
; /* use pre increment below(*++b) for speed */
117 b
++; /* point to next byte(s) */
120 /* And the last few bytes */
123 DO_CRC(*((u8
*)b
)++);
127 return __le32_to_cpu(crc
);
131 # elif CRC_LE_BITS == 4
134 crc
= (crc
>> 4) ^ crc32table_le
[crc
& 15];
135 crc
= (crc
>> 4) ^ crc32table_le
[crc
& 15];
138 # elif CRC_LE_BITS == 2
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 crc
= (crc
>> 2) ^ crc32table_le
[crc
& 3];
153 * In fact, the table-based code will work in this case, but it can be
154 * simplified by inlining the table in ?: form.
158 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
159 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
160 * other uses, or the previous crc32 value if computing incrementally.
161 * @p - pointer to buffer over which CRC is run
162 * @len - length of buffer @p
165 u32
attribute((pure
)) crc32_be(u32 crc
, unsigned char const *p
, size_t len
)
170 for (i
= 0; i
< 8; i
++)
172 (crc
<< 1) ^ ((crc
& 0x80000000) ? CRCPOLY_BE
:
178 #else /* Table-based approach */
180 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
181 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
182 * other uses, or the previous crc32 value if computing incrementally.
183 * @p - pointer to buffer over which CRC is run
184 * @len - length of buffer @p
187 u32
attribute((pure
)) crc32_be(u32 crc
, unsigned char const *p
, size_t len
)
189 # if CRC_BE_BITS == 8
190 const u32
*b
=(u32
*)p
;
191 const u32
*tab
= crc32table_be
;
193 # ifdef __LITTLE_ENDIAN
194 # define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
196 # define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
199 crc
= __cpu_to_be32(crc
);
201 if(unlikely(((long)b
)&3 && len
)){
203 DO_CRC(*((u8
*)b
)++);
204 } while ((--len
) && ((long)b
)&3 );
206 if(likely(len
>= 4)){
207 /* load data 32 bits wide, xor data 32 bits wide. */
208 size_t save_len
= len
& 3;
210 --b
; /* use pre increment below(*++b) for speed */
218 b
++; /* point to next byte(s) */
221 /* And the last few bytes */
224 DO_CRC(*((u8
*)b
)++);
227 return __be32_to_cpu(crc
);
231 # elif CRC_BE_BITS == 4
234 crc
= (crc
<< 4) ^ crc32table_be
[crc
>> 28];
235 crc
= (crc
<< 4) ^ crc32table_be
[crc
>> 28];
238 # elif CRC_BE_BITS == 2
241 crc
= (crc
<< 2) ^ crc32table_be
[crc
>> 30];
242 crc
= (crc
<< 2) ^ crc32table_be
[crc
>> 30];
243 crc
= (crc
<< 2) ^ crc32table_be
[crc
>> 30];
244 crc
= (crc
<< 2) ^ crc32table_be
[crc
>> 30];
251 u32
bitreverse(u32 x
)
253 x
= (x
>> 16) | (x
<< 16);
254 x
= (x
>> 8 & 0x00ff00ff) | (x
<< 8 & 0xff00ff00);
255 x
= (x
>> 4 & 0x0f0f0f0f) | (x
<< 4 & 0xf0f0f0f0);
256 x
= (x
>> 2 & 0x33333333) | (x
<< 2 & 0xcccccccc);
257 x
= (x
>> 1 & 0x55555555) | (x
<< 1 & 0xaaaaaaaa);
261 EXPORT_SYMBOL(crc32_le
);
262 EXPORT_SYMBOL(crc32_be
);
263 EXPORT_SYMBOL(bitreverse
);
266 * A brief CRC tutorial.
268 * A CRC is a long-division remainder. You add the CRC to the message,
269 * and the whole thing (message+CRC) is a multiple of the given
270 * CRC polynomial. To check the CRC, you can either check that the
271 * CRC matches the recomputed value, *or* you can check that the
272 * remainder computed on the message+CRC is 0. This latter approach
273 * is used by a lot of hardware implementations, and is why so many
274 * protocols put the end-of-frame flag after the CRC.
276 * It's actually the same long division you learned in school, except that
277 * - We're working in binary, so the digits are only 0 and 1, and
278 * - When dividing polynomials, there are no carries. Rather than add and
279 * subtract, we just xor. Thus, we tend to get a bit sloppy about
280 * the difference between adding and subtracting.
282 * A 32-bit CRC polynomial is actually 33 bits long. But since it's
283 * 33 bits long, bit 32 is always going to be set, so usually the CRC
284 * is written in hex with the most significant bit omitted. (If you're
285 * familiar with the IEEE 754 floating-point format, it's the same idea.)
287 * Note that a CRC is computed over a string of *bits*, so you have
288 * to decide on the endianness of the bits within each byte. To get
289 * the best error-detecting properties, this should correspond to the
290 * order they're actually sent. For example, standard RS-232 serial is
291 * little-endian; the most significant bit (sometimes used for parity)
292 * is sent last. And when appending a CRC word to a message, you should
293 * do it in the right order, matching the endianness.
295 * Just like with ordinary division, the remainder is always smaller than
296 * the divisor (the CRC polynomial) you're dividing by. Each step of the
297 * division, you take one more digit (bit) of the dividend and append it
298 * to the current remainder. Then you figure out the appropriate multiple
299 * of the divisor to subtract to being the remainder back into range.
300 * In binary, it's easy - it has to be either 0 or 1, and to make the
301 * XOR cancel, it's just a copy of bit 32 of the remainder.
303 * When computing a CRC, we don't care about the quotient, so we can
304 * throw the quotient bit away, but subtract the appropriate multiple of
305 * the polynomial from the remainder and we're back to where we started,
306 * ready to process the next bit.
308 * A big-endian CRC written this way would be coded like:
309 * for (i = 0; i < input_bits; i++) {
310 * multiple = remainder & 0x80000000 ? CRCPOLY : 0;
311 * remainder = (remainder << 1 | next_input_bit()) ^ multiple;
313 * Notice how, to get at bit 32 of the shifted remainder, we look
314 * at bit 31 of the remainder *before* shifting it.
316 * But also notice how the next_input_bit() bits we're shifting into
317 * the remainder don't actually affect any decision-making until
318 * 32 bits later. Thus, the first 32 cycles of this are pretty boring.
319 * Also, to add the CRC to a message, we need a 32-bit-long hole for it at
320 * the end, so we have to add 32 extra cycles shifting in zeros at the
321 * end of every message,
323 * So the standard trick is to rearrage merging in the next_input_bit()
324 * until the moment it's needed. Then the first 32 cycles can be precomputed,
325 * and merging in the final 32 zero bits to make room for the CRC can be
327 * This changes the code to:
328 * for (i = 0; i < input_bits; i++) {
329 * remainder ^= next_input_bit() << 31;
330 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
331 * remainder = (remainder << 1) ^ multiple;
333 * With this optimization, the little-endian code is simpler:
334 * for (i = 0; i < input_bits; i++) {
335 * remainder ^= next_input_bit();
336 * multiple = (remainder & 1) ? CRCPOLY : 0;
337 * remainder = (remainder >> 1) ^ multiple;
340 * Note that the other details of endianness have been hidden in CRCPOLY
341 * (which must be bit-reversed) and next_input_bit().
343 * However, as long as next_input_bit is returning the bits in a sensible
344 * order, we can actually do the merging 8 or more bits at a time rather
345 * than one bit at a time:
346 * for (i = 0; i < input_bytes; i++) {
347 * remainder ^= next_input_byte() << 24;
348 * for (j = 0; j < 8; j++) {
349 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
350 * remainder = (remainder << 1) ^ multiple;
353 * Or in little-endian:
354 * for (i = 0; i < input_bytes; i++) {
355 * remainder ^= next_input_byte();
356 * for (j = 0; j < 8; j++) {
357 * multiple = (remainder & 1) ? CRCPOLY : 0;
358 * remainder = (remainder << 1) ^ multiple;
361 * If the input is a multiple of 32 bits, you can even XOR in a 32-bit
362 * word at a time and increase the inner loop count to 32.
364 * You can also mix and match the two loop styles, for example doing the
365 * bulk of a message byte-at-a-time and adding bit-at-a-time processing
366 * for any fractional bytes at the end.
368 * The only remaining optimization is to the byte-at-a-time table method.
369 * Here, rather than just shifting one bit of the remainder to decide
370 * in the correct multiple to subtract, we can shift a byte at a time.
371 * This produces a 40-bit (rather than a 33-bit) intermediate remainder,
372 * but again the multiple of the polynomial to subtract depends only on
373 * the high bits, the high 8 bits in this case.
375 * The multile we need in that case is the low 32 bits of a 40-bit
376 * value whose high 8 bits are given, and which is a multiple of the
377 * generator polynomial. This is simply the CRC-32 of the given
380 * Two more details: normally, appending zero bits to a message which
381 * is already a multiple of a polynomial produces a larger multiple of that
382 * polynomial. To enable a CRC to detect this condition, it's common to
383 * invert the CRC before appending it. This makes the remainder of the
384 * message+crc come out not as zero, but some fixed non-zero value.
386 * The same problem applies to zero bits prepended to the message, and
387 * a similar solution is used. Instead of starting with a remainder of
388 * 0, an initial remainder of all ones is used. As long as you start
389 * the same way on decoding, it doesn't make a difference.
397 #if 0 /*Not used at present */
399 buf_dump(char const *prefix
, unsigned char const *buf
, size_t len
)
401 fputs(prefix
, stdout
);
403 printf(" %02x", *buf
++);
409 static void bytereverse(unsigned char *buf
, size_t len
)
412 unsigned char x
= *buf
;
413 x
= (x
>> 4) | (x
<< 4);
414 x
= (x
>> 2 & 0x33) | (x
<< 2 & 0xcc);
415 x
= (x
>> 1 & 0x55) | (x
<< 1 & 0xaa);
420 static void random_garbage(unsigned char *buf
, size_t len
)
423 *buf
++ = (unsigned char) random();
426 #if 0 /* Not used at present */
427 static void store_le(u32 x
, unsigned char *buf
)
429 buf
[0] = (unsigned char) x
;
430 buf
[1] = (unsigned char) (x
>> 8);
431 buf
[2] = (unsigned char) (x
>> 16);
432 buf
[3] = (unsigned char) (x
>> 24);
436 static void store_be(u32 x
, unsigned char *buf
)
438 buf
[0] = (unsigned char) (x
>> 24);
439 buf
[1] = (unsigned char) (x
>> 16);
440 buf
[2] = (unsigned char) (x
>> 8);
441 buf
[3] = (unsigned char) x
;
445 * This checks that CRC(buf + CRC(buf)) = 0, and that
446 * CRC commutes with bit-reversal. This has the side effect
447 * of bytewise bit-reversing the input buffer, and returns
448 * the CRC of the reversed buffer.
450 static u32
test_step(u32 init
, unsigned char *buf
, size_t len
)
455 crc1
= crc32_be(init
, buf
, len
);
456 store_be(crc1
, buf
+ len
);
457 crc2
= crc32_be(init
, buf
, len
+ 4);
459 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
462 for (i
= 0; i
<= len
+ 4; i
++) {
463 crc2
= crc32_be(init
, buf
, i
);
464 crc2
= crc32_be(crc2
, buf
+ i
, len
+ 4 - i
);
466 printf("\nCRC split fail: 0x%08x\n", crc2
);
469 /* Now swap it around for the other test */
471 bytereverse(buf
, len
+ 4);
472 init
= bitreverse(init
);
473 crc2
= bitreverse(crc1
);
474 if (crc1
!= bitreverse(crc2
))
475 printf("\nBit reversal fail: 0x%08x -> %0x08x -> 0x%08x\n",
476 crc1
, crc2
, bitreverse(crc2
));
477 crc1
= crc32_le(init
, buf
, len
);
479 printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1
,
481 crc2
= crc32_le(init
, buf
, len
+ 4);
483 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
486 for (i
= 0; i
<= len
+ 4; i
++) {
487 crc2
= crc32_le(init
, buf
, i
);
488 crc2
= crc32_le(crc2
, buf
+ i
, len
+ 4 - i
);
490 printf("\nCRC split fail: 0x%08x\n", crc2
);
502 unsigned char buf1
[SIZE
+ 4];
503 unsigned char buf2
[SIZE
+ 4];
504 unsigned char buf3
[SIZE
+ 4];
506 u32 crc1
, crc2
, crc3
;
508 for (i
= 0; i
<= SIZE
; i
++) {
509 printf("\rTesting length %d...", i
);
511 random_garbage(buf1
, i
);
512 random_garbage(buf2
, i
);
513 for (j
= 0; j
< i
; j
++)
514 buf3
[j
] = buf1
[j
] ^ buf2
[j
];
516 crc1
= test_step(INIT1
, buf1
, i
);
517 crc2
= test_step(INIT2
, buf2
, i
);
518 /* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */
519 crc3
= test_step(INIT1
^ INIT2
, buf3
, i
);
520 if (crc3
!= (crc1
^ crc2
))
521 printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",
524 printf("\nAll test complete. No failures expected.\n");
528 #endif /* UNITTEST */