v2.5.2 -> v2.5.2.1
[linux-flexiantxendom0-3.2.10.git] / 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/types.h>
22 #include <linux/slab.h>
23 #include <linux/init.h>
24 #include <asm/atomic.h>
25
26 #if __GNUC__ >= 3       /* 2.x has "attribute", but only 3.0 has "pure */
27 #define attribute(x) __attribute__(x)
28 #else
29 #define attribute(x)
30 #endif
31
32 /*
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.
37  */
38
39 MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
40 MODULE_DESCRIPTION("Ethernet CRC32 calculations");
41 MODULE_LICENSE("GPL and additional rights");
42
43
44 /*
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
48  */
49 #define CRCPOLY_LE 0xedb88320
50 #define CRCPOLY_BE 0x04c11db7
51
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 */
54 #define CRC_LE_BITS 8
55 #define CRC_BE_BITS 8
56
57 /*
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.
60  */
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
63 #endif
64
65 #if CRC_LE_BITS == 1
66 /*
67  * In fact, the table-based code will work in this case, but it can be
68  * simplified by inlining the table in ?: form.
69  */
70 #define crc32init_le()
71 #define crc32cleanup_le()
72 /**
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
78  * 
79  */
80 u32 attribute((pure)) crc32_le(u32 crc, unsigned char const *p, size_t len)
81 {
82         int i;
83         while (len--) {
84                 crc ^= *p++;
85                 for (i = 0; i < 8; i++)
86                         crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
87         }
88         return crc;
89 }
90 #else                           /* Table-based approach */
91
92 static u32 *crc32table_le;
93 /**
94  * crc32init_le() - allocate and initialize LE table data
95  *
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].
98  *
99  */
100 static int __init crc32init_le(void)
101 {
102         unsigned i, j;
103         u32 crc = 1;
104
105         crc32table_le =
106             kmalloc((1 << CRC_LE_BITS) * sizeof(u32), GFP_KERNEL);
107         if (!crc32table_le)
108                 return 1;
109         crc32table_le[0] = 0;
110
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];
115         }
116         return 0;
117 }
118
119 /**
120  * crc32cleanup_le(): free LE table data
121  */
122 static void __exit crc32cleanup_le(void)
123 {
124         if (crc32table_le) kfree(crc32table_le);
125         crc32table_le = NULL;
126 }
127
128 /**
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
134  * 
135  */
136 u32 attribute((pure)) crc32_le(u32 crc, unsigned char const *p, size_t len)
137 {
138         while (len--) {
139 # if CRC_LE_BITS == 8
140                 crc = (crc >> 8) ^ crc32table_le[(crc ^ *p++) & 255];
141 # elif CRC_LE_BITS == 4
142                 crc ^= *p++;
143                 crc = (crc >> 4) ^ crc32table_le[crc & 15];
144                 crc = (crc >> 4) ^ crc32table_le[crc & 15];
145 # elif CRC_LE_BITS == 2
146                 crc ^= *p++;
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];
151 # endif
152         }
153         return crc;
154 }
155 #endif
156
157 /*
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.
160  */
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
163 #endif
164
165 #if CRC_BE_BITS == 1
166 /*
167  * In fact, the table-based code will work in this case, but it can be
168  * simplified by inlining the table in ?: form.
169  */
170 #define crc32init_be()
171 #define crc32cleanup_be()
172
173 /**
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
179  * 
180  */
181 u32 attribute((pure)) crc32_be(u32 crc, unsigned char const *p, size_t len)
182 {
183         int i;
184         while (len--) {
185                 crc ^= *p++ << 24;
186                 for (i = 0; i < 8; i++)
187                         crc =
188                             (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :
189                                           0);
190         }
191         return crc;
192 }
193
194 #else                           /* Table-based approach */
195 static u32 *crc32table_be;
196
197 /**
198  * crc32init_be() - allocate and initialize BE table data
199  */
200 static int __init crc32init_be(void)
201 {
202         unsigned i, j;
203         u32 crc = 0x80000000;
204
205         crc32table_be =
206             kmalloc((1 << CRC_BE_BITS) * sizeof(u32), GFP_KERNEL);
207         if (!crc32table_be)
208                 return 1;
209         crc32table_be[0] = 0;
210
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];
215         }
216         return 0;
217 }
218
219 /**
220  * crc32cleanup_be(): free BE table data
221  */
222 static void __exit crc32cleanup_be(void)
223 {
224         if (crc32table_be) kfree(crc32table_be);
225         crc32table_be = NULL;
226 }
227
228
229 /**
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
235  * 
236  */
237 u32 attribute((pure)) crc32_be(u32 crc, unsigned char const *p, size_t len)
238 {
239         while (len--) {
240 # if CRC_BE_BITS == 8
241                 crc = (crc << 8) ^ crc32table_be[(crc >> 24) ^ *p++];
242 # elif CRC_BE_BITS == 4
243                 crc ^= *p++ << 24;
244                 crc = (crc << 4) ^ crc32table_be[crc >> 28];
245                 crc = (crc << 4) ^ crc32table_be[crc >> 28];
246 # elif CRC_BE_BITS == 2
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];
252 # endif
253         }
254         return crc;
255 }
256 #endif
257
258 /*
259  * A brief CRC tutorial.
260  *
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.
268  *
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.
274  *
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.)
279  *
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.
287  *
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.
295  *
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.
300  *
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;
305  * }
306  * Notice how, to get at bit 32 of the shifted remainder, we look
307  * at bit 31 of the remainder *before* shifting it.
308  *
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,
315  *
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
319  * skipped entirely.
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;
325  * }
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;
331  * }
332  *
333  * Note that the other details of endianness have been hidden in CRCPOLY
334  * (which must be bit-reversed) and next_input_bit().
335  *
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;
344  *      }
345  * }
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;
352  *      }
353  * }
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.
356  *
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.
360  *
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.  
367  *
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
371  * one-byte message.
372  *
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.
378  *
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.
383  */
384
385 #if UNITTEST
386
387 #include <stdlib.h>
388 #include <stdio.h>
389
390 #if 0                           /*Not used at present */
391 static void
392 buf_dump(char const *prefix, unsigned char const *buf, size_t len)
393 {
394         fputs(prefix, stdout);
395         while (len--)
396                 printf(" %02x", *buf++);
397         putchar('\n');
398
399 }
400 #endif
401
402 static u32 attribute((const)) bitreverse(u32 x)
403 {
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);
409         return x;
410 }
411
412 static void bytereverse(unsigned char *buf, size_t len)
413 {
414         while (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);
419                 *buf++ = x;
420         }
421 }
422
423 static void random_garbage(unsigned char *buf, size_t len)
424 {
425         while (len--)
426                 *buf++ = (unsigned char) random();
427 }
428
429 #if 0                           /* Not used at present */
430 static void store_le(u32 x, unsigned char *buf)
431 {
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);
436 }
437 #endif
438
439 static void store_be(u32 x, unsigned char *buf)
440 {
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;
445 }
446
447 /*
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.
452  */
453 static u32 test_step(u32 init, unsigned char *buf, size_t len)
454 {
455         u32 crc1, crc2;
456         size_t i;
457
458         crc1 = crc32_be(init, buf, len);
459         store_be(crc1, buf + len);
460         crc2 = crc32_be(init, buf, len + 4);
461         if (crc2)
462                 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
463                        crc2);
464
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);
468                 if (crc2)
469                         printf("\nCRC split fail: 0x%08x\n", crc2);
470         }
471
472         /* Now swap it around for the other test */
473
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);
481         if (crc1 != crc2)
482                 printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,
483                        crc2);
484         crc2 = crc32_le(init, buf, len + 4);
485         if (crc2)
486                 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
487                        crc2);
488
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);
492                 if (crc2)
493                         printf("\nCRC split fail: 0x%08x\n", crc2);
494         }
495
496         return crc1;
497 }
498
499 #define SIZE 64
500 #define INIT1 0
501 #define INIT2 0
502
503 int main(void)
504 {
505         unsigned char buf1[SIZE + 4];
506         unsigned char buf2[SIZE + 4];
507         unsigned char buf3[SIZE + 4];
508         int i, j;
509         u32 crc1, crc2, crc3;
510
511         crc32init_le();
512         crc32init_be();
513
514         for (i = 0; i <= SIZE; i++) {
515                 printf("\rTesting length %d...", i);
516                 fflush(stdout);
517                 random_garbage(buf1, i);
518                 random_garbage(buf2, i);
519                 for (j = 0; j < i; j++)
520                         buf3[j] = buf1[j] ^ buf2[j];
521
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",
528                                crc3, crc1, crc2);
529         }
530         printf("\nAll test complete.  No failures expected.\n");
531         return 0;
532 }
533
534 #endif                          /* UNITTEST */
535
536 /**
537  * init_crc32(): generates CRC32 tables
538  * 
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.
547  */
548 static int __init init_crc32(void)
549 {
550         int rc1, rc2, rc;
551         rc1 = crc32init_le();
552         rc2 = crc32init_be();
553         rc = rc1 || rc2;
554         if (!rc) MOD_INC_USE_COUNT;
555         return rc;
556 }
557
558 /**
559  * cleanup_crc32(): frees crc32 data when no longer needed
560  */
561 static void __exit cleanup_crc32(void)
562 {
563         crc32cleanup_le();
564         crc32cleanup_be();
565 }
566
567 module_init(init_crc32);
568 module_exit(cleanup_crc32);
569
570 EXPORT_SYMBOL(crc32_le);
571 EXPORT_SYMBOL(crc32_be);