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>
26 #if __GNUC__ >= 3 /* 2.x has "attribute", but only 3.0 has "pure */
27 #define attribute(x) __attribute__(x)
33 * This code is in the public domain; copyright abandoned.
34 * Liability for non-performance of this code is limited to the amount
35 * you paid for it. Since it is distributed for free, your refund will
36 * be very very small. If it breaks, you get to keep both pieces.
39 MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
40 MODULE_DESCRIPTION("Ethernet CRC32 calculations");
41 MODULE_LICENSE("GPL and additional rights");
45 * There are multiple 16-bit CRC polynomials in common use, but this is
46 * *the* standard CRC-32 polynomial, first popularized by Ethernet.
47 * x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x^1+x^0
49 #define CRCPOLY_LE 0xedb88320
50 #define CRCPOLY_BE 0x04c11db7
52 /* How many bits at a time to use. Requires a table of 4<<CRC_xx_BITS bytes. */
53 /* For less performance-sensitive, use 4 */
58 * Little-endian CRC computation. Used with serial bit streams sent
59 * lsbit-first. Be sure to use cpu_to_le32() to append the computed CRC.
61 #if CRC_LE_BITS > 8 || CRC_LE_BITS < 1 || CRC_LE_BITS & CRC_LE_BITS-1
62 # error CRC_LE_BITS must be a power of 2 between 1 and 8
67 * In fact, the table-based code will work in this case, but it can be
68 * simplified by inlining the table in ?: form.
70 #define crc32init_le()
71 #define crc32cleanup_le()
73 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
74 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
75 * other uses, or the previous crc32 value if computing incrementally.
76 * @p - pointer to buffer over which CRC is run
77 * @len - length of buffer @p
80 u32 attribute((pure)) crc32_le(u32 crc, unsigned char const *p, size_t len)
85 for (i = 0; i < 8; i++)
86 crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
90 #else /* Table-based approach */
92 static u32 *crc32table_le;
94 * crc32init_le() - allocate and initialize LE table data
96 * crc is the crc of the byte i; other entries are filled in based on the
97 * fact that crctable[i^j] = crctable[i] ^ crctable[j].
100 static int __init crc32init_le(void)
106 kmalloc((1 << CRC_LE_BITS) * sizeof(u32), GFP_KERNEL);
109 crc32table_le[0] = 0;
111 for (i = 1 << (CRC_LE_BITS - 1); i; i >>= 1) {
112 crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
113 for (j = 0; j < 1 << CRC_LE_BITS; j += 2 * i)
114 crc32table_le[i + j] = crc ^ crc32table_le[j];
120 * crc32cleanup_le(): free LE table data
122 static void __exit crc32cleanup_le(void)
124 if (crc32table_le) kfree(crc32table_le);
125 crc32table_le = NULL;
129 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
130 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
131 * other uses, or the previous crc32 value if computing incrementally.
132 * @p - pointer to buffer over which CRC is run
133 * @len - length of buffer @p
136 u32 attribute((pure)) crc32_le(u32 crc, unsigned char const *p, size_t len)
139 # if CRC_LE_BITS == 8
140 crc = (crc >> 8) ^ crc32table_le[(crc ^ *p++) & 255];
141 # elif CRC_LE_BITS == 4
143 crc = (crc >> 4) ^ crc32table_le[crc & 15];
144 crc = (crc >> 4) ^ crc32table_le[crc & 15];
145 # elif CRC_LE_BITS == 2
147 crc = (crc >> 2) ^ crc32table_le[crc & 3];
148 crc = (crc >> 2) ^ crc32table_le[crc & 3];
149 crc = (crc >> 2) ^ crc32table_le[crc & 3];
150 crc = (crc >> 2) ^ crc32table_le[crc & 3];
158 * Big-endian CRC computation. Used with serial bit streams sent
159 * msbit-first. Be sure to use cpu_to_be32() to append the computed CRC.
161 #if CRC_BE_BITS > 8 || CRC_BE_BITS < 1 || CRC_BE_BITS & CRC_BE_BITS-1
162 # error CRC_BE_BITS must be a power of 2 between 1 and 8
167 * In fact, the table-based code will work in this case, but it can be
168 * simplified by inlining the table in ?: form.
170 #define crc32init_be()
171 #define crc32cleanup_be()
174 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
175 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
176 * other uses, or the previous crc32 value if computing incrementally.
177 * @p - pointer to buffer over which CRC is run
178 * @len - length of buffer @p
181 u32 attribute((pure)) crc32_be(u32 crc, unsigned char const *p, size_t len)
186 for (i = 0; i < 8; i++)
188 (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :
194 #else /* Table-based approach */
195 static u32 *crc32table_be;
198 * crc32init_be() - allocate and initialize BE table data
200 static int __init crc32init_be(void)
203 u32 crc = 0x80000000;
206 kmalloc((1 << CRC_BE_BITS) * sizeof(u32), GFP_KERNEL);
209 crc32table_be[0] = 0;
211 for (i = 1; i < 1 << CRC_BE_BITS; i <<= 1) {
212 crc = (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE : 0);
213 for (j = 0; j < i; j++)
214 crc32table_be[i + j] = crc ^ crc32table_be[j];
220 * crc32cleanup_be(): free BE table data
222 static void __exit crc32cleanup_be(void)
224 if (crc32table_be) kfree(crc32table_be);
225 crc32table_be = NULL;
230 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
231 * @crc - seed value for computation. ~0 for Ethernet, sometimes 0 for
232 * other uses, or the previous crc32 value if computing incrementally.
233 * @p - pointer to buffer over which CRC is run
234 * @len - length of buffer @p
237 u32 attribute((pure)) crc32_be(u32 crc, unsigned char const *p, size_t len)
240 # if CRC_BE_BITS == 8
241 crc = (crc << 8) ^ crc32table_be[(crc >> 24) ^ *p++];
242 # elif CRC_BE_BITS == 4
244 crc = (crc << 4) ^ crc32table_be[crc >> 28];
245 crc = (crc << 4) ^ crc32table_be[crc >> 28];
246 # elif CRC_BE_BITS == 2
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];
259 * A brief CRC tutorial.
261 * A CRC is a long-division remainder. You add the CRC to the message,
262 * and the whole thing (message+CRC) is a multiple of the given
263 * CRC polynomial. To check the CRC, you can either check that the
264 * CRC matches the recomputed value, *or* you can check that the
265 * remainder computed on the message+CRC is 0. This latter approach
266 * is used by a lot of hardware implementations, and is why so many
267 * protocols put the end-of-frame flag after the CRC.
269 * It's actually the same long division you learned in school, except that
270 * - We're working in binary, so the digits are only 0 and 1, and
271 * - When dividing polynomials, there are no carries. Rather than add and
272 * subtract, we just xor. Thus, we tend to get a bit sloppy about
273 * the difference between adding and subtracting.
275 * A 32-bit CRC polynomial is actually 33 bits long. But since it's
276 * 33 bits long, bit 32 is always going to be set, so usually the CRC
277 * is written in hex with the most significant bit omitted. (If you're
278 * familiar with the IEEE 754 floating-point format, it's the same idea.)
280 * Note that a CRC is computed over a string of *bits*, so you have
281 * to decide on the endianness of the bits within each byte. To get
282 * the best error-detecting properties, this should correspond to the
283 * order they're actually sent. For example, standard RS-232 serial is
284 * little-endian; the most significant bit (sometimes used for parity)
285 * is sent last. And when appending a CRC word to a message, you should
286 * do it in the right order, matching the endianness.
288 * Just like with ordinary division, the remainder is always smaller than
289 * the divisor (the CRC polynomial) you're dividing by. Each step of the
290 * division, you take one more digit (bit) of the dividend and append it
291 * to the current remainder. Then you figure out the appropriate multiple
292 * of the divisor to subtract to being the remainder back into range.
293 * In binary, it's easy - it has to be either 0 or 1, and to make the
294 * XOR cancel, it's just a copy of bit 32 of the remainder.
296 * When computing a CRC, we don't care about the quotient, so we can
297 * throw the quotient bit away, but subtract the appropriate multiple of
298 * the polynomial from the remainder and we're back to where we started,
299 * ready to process the next bit.
301 * A big-endian CRC written this way would be coded like:
302 * for (i = 0; i < input_bits; i++) {
303 * multiple = remainder & 0x80000000 ? CRCPOLY : 0;
304 * remainder = (remainder << 1 | next_input_bit()) ^ multiple;
306 * Notice how, to get at bit 32 of the shifted remainder, we look
307 * at bit 31 of the remainder *before* shifting it.
309 * But also notice how the next_input_bit() bits we're shifting into
310 * the remainder don't actually affect any decision-making until
311 * 32 bits later. Thus, the first 32 cycles of this are pretty boring.
312 * Also, to add the CRC to a message, we need a 32-bit-long hole for it at
313 * the end, so we have to add 32 extra cycles shifting in zeros at the
314 * end of every message,
316 * So the standard trick is to rearrage merging in the next_input_bit()
317 * until the moment it's needed. Then the first 32 cycles can be precomputed,
318 * and merging in the final 32 zero bits to make room for the CRC can be
320 * This changes the code to:
321 * for (i = 0; i < input_bits; i++) {
322 * remainder ^= next_input_bit() << 31;
323 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
324 * remainder = (remainder << 1) ^ multiple;
326 * With this optimization, the little-endian code is simpler:
327 * for (i = 0; i < input_bits; i++) {
328 * remainder ^= next_input_bit();
329 * multiple = (remainder & 1) ? CRCPOLY : 0;
330 * remainder = (remainder >> 1) ^ multiple;
333 * Note that the other details of endianness have been hidden in CRCPOLY
334 * (which must be bit-reversed) and next_input_bit().
336 * However, as long as next_input_bit is returning the bits in a sensible
337 * order, we can actually do the merging 8 or more bits at a time rather
338 * than one bit at a time:
339 * for (i = 0; i < input_bytes; i++) {
340 * remainder ^= next_input_byte() << 24;
341 * for (j = 0; j < 8; j++) {
342 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
343 * remainder = (remainder << 1) ^ multiple;
346 * Or in little-endian:
347 * for (i = 0; i < input_bytes; i++) {
348 * remainder ^= next_input_byte();
349 * for (j = 0; j < 8; j++) {
350 * multiple = (remainder & 1) ? CRCPOLY : 0;
351 * remainder = (remainder << 1) ^ multiple;
354 * If the input is a multiple of 32 bits, you can even XOR in a 32-bit
355 * word at a time and increase the inner loop count to 32.
357 * You can also mix and match the two loop styles, for example doing the
358 * bulk of a message byte-at-a-time and adding bit-at-a-time processing
359 * for any fractional bytes at the end.
361 * The only remaining optimization is to the byte-at-a-time table method.
362 * Here, rather than just shifting one bit of the remainder to decide
363 * in the correct multiple to subtract, we can shift a byte at a time.
364 * This produces a 40-bit (rather than a 33-bit) intermediate remainder,
365 * but again the multiple of the polynomial to subtract depends only on
366 * the high bits, the high 8 bits in this case.
368 * The multile we need in that case is the low 32 bits of a 40-bit
369 * value whose high 8 bits are given, and which is a multiple of the
370 * generator polynomial. This is simply the CRC-32 of the given
373 * Two more details: normally, appending zero bits to a message which
374 * is already a multiple of a polynomial produces a larger multiple of that
375 * polynomial. To enable a CRC to detect this condition, it's common to
376 * invert the CRC before appending it. This makes the remainder of the
377 * message+crc come out not as zero, but some fixed non-zero value.
379 * The same problem applies to zero bits prepended to the message, and
380 * a similar solution is used. Instead of starting with a remainder of
381 * 0, an initial remainder of all ones is used. As long as you start
382 * the same way on decoding, it doesn't make a difference.
390 #if 0 /*Not used at present */
392 buf_dump(char const *prefix, unsigned char const *buf, size_t len)
394 fputs(prefix, stdout);
396 printf(" %02x", *buf++);
402 static u32 attribute((const)) bitreverse(u32 x)
404 x = (x >> 16) | (x << 16);
405 x = (x >> 8 & 0x00ff00ff) | (x << 8 & 0xff00ff00);
406 x = (x >> 4 & 0x0f0f0f0f) | (x << 4 & 0xf0f0f0f0);
407 x = (x >> 2 & 0x33333333) | (x << 2 & 0xcccccccc);
408 x = (x >> 1 & 0x55555555) | (x << 1 & 0xaaaaaaaa);
412 static void bytereverse(unsigned char *buf, size_t len)
415 unsigned char x = *buf;
416 x = (x >> 4) | (x << 4);
417 x = (x >> 2 & 0x33) | (x << 2 & 0xcc);
418 x = (x >> 1 & 0x55) | (x << 1 & 0xaa);
423 static void random_garbage(unsigned char *buf, size_t len)
426 *buf++ = (unsigned char) random();
429 #if 0 /* Not used at present */
430 static void store_le(u32 x, unsigned char *buf)
432 buf[0] = (unsigned char) x;
433 buf[1] = (unsigned char) (x >> 8);
434 buf[2] = (unsigned char) (x >> 16);
435 buf[3] = (unsigned char) (x >> 24);
439 static void store_be(u32 x, unsigned char *buf)
441 buf[0] = (unsigned char) (x >> 24);
442 buf[1] = (unsigned char) (x >> 16);
443 buf[2] = (unsigned char) (x >> 8);
444 buf[3] = (unsigned char) x;
448 * This checks that CRC(buf + CRC(buf)) = 0, and that
449 * CRC commutes with bit-reversal. This has the side effect
450 * of bytewise bit-reversing the input buffer, and returns
451 * the CRC of the reversed buffer.
453 static u32 test_step(u32 init, unsigned char *buf, size_t len)
458 crc1 = crc32_be(init, buf, len);
459 store_be(crc1, buf + len);
460 crc2 = crc32_be(init, buf, len + 4);
462 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
465 for (i = 0; i <= len + 4; i++) {
466 crc2 = crc32_be(init, buf, i);
467 crc2 = crc32_be(crc2, buf + i, len + 4 - i);
469 printf("\nCRC split fail: 0x%08x\n", crc2);
472 /* Now swap it around for the other test */
474 bytereverse(buf, len + 4);
475 init = bitreverse(init);
476 crc2 = bitreverse(crc1);
477 if (crc1 != bitreverse(crc2))
478 printf("\nBit reversal fail: 0x%08x -> %0x08x -> 0x%08x\n",
479 crc1, crc2, bitreverse(crc2));
480 crc1 = crc32_le(init, buf, len);
482 printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,
484 crc2 = crc32_le(init, buf, len + 4);
486 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
489 for (i = 0; i <= len + 4; i++) {
490 crc2 = crc32_le(init, buf, i);
491 crc2 = crc32_le(crc2, buf + i, len + 4 - i);
493 printf("\nCRC split fail: 0x%08x\n", crc2);
505 unsigned char buf1[SIZE + 4];
506 unsigned char buf2[SIZE + 4];
507 unsigned char buf3[SIZE + 4];
509 u32 crc1, crc2, crc3;
514 for (i = 0; i <= SIZE; i++) {
515 printf("\rTesting length %d...", i);
517 random_garbage(buf1, i);
518 random_garbage(buf2, i);
519 for (j = 0; j < i; j++)
520 buf3[j] = buf1[j] ^ buf2[j];
522 crc1 = test_step(INIT1, buf1, i);
523 crc2 = test_step(INIT2, buf2, i);
524 /* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */
525 crc3 = test_step(INIT1 ^ INIT2, buf3, i);
526 if (crc3 != (crc1 ^ crc2))
527 printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",
530 printf("\nAll test complete. No failures expected.\n");
534 #endif /* UNITTEST */
537 * init_crc32(): generates CRC32 tables
539 * On successful initialization, use count is increased.
540 * This guarantees that the library functions will stay resident
541 * in memory, and prevents someone from 'rmmod crc32' while
542 * a driver that needs it is still loaded.
543 * This also greatly simplifies drivers, as there's no need
544 * to call an initialization/cleanup function from each driver.
545 * Since crc32.o is a library module, there's no requirement
546 * that the user can unload it.
548 static int __init init_crc32(void)
551 rc1 = crc32init_le();
552 rc2 = crc32init_be();
554 if (!rc) MOD_INC_USE_COUNT;
559 * cleanup_crc32(): frees crc32 data when no longer needed
561 static void __exit cleanup_crc32(void)
567 module_init(init_crc32);
568 module_exit(cleanup_crc32);
570 EXPORT_SYMBOL(crc32_le);
571 EXPORT_SYMBOL(crc32_be);