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