blob: 02e3b31b3a79003514138cf5c6a1cad19e3d3cf9 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
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.
7 *
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.
18 *
19 * This source code is licensed under the GNU General Public License,
20 * Version 2. See the file COPYING for more details.
21 */
22
23#include <linux/crc32.h>
24#include <linux/kernel.h>
25#include <linux/module.h>
26#include <linux/compiler.h>
27#include <linux/types.h>
28#include <linux/slab.h>
29#include <linux/init.h>
30#include <asm/atomic.h>
31#include "crc32defs.h"
32#if CRC_LE_BITS == 8
33#define tole(x) __constant_cpu_to_le32(x)
34#define tobe(x) __constant_cpu_to_be32(x)
35#else
36#define tole(x) (x)
37#define tobe(x) (x)
38#endif
39#include "crc32table.h"
40
41MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
42MODULE_DESCRIPTION("Ethernet CRC32 calculations");
43MODULE_LICENSE("GPL");
44
Joakim Tjernlundddcaccb2009-12-14 18:01:33 -080045#if CRC_LE_BITS == 8 || CRC_BE_BITS == 8
46
47static inline u32
48crc32_body(u32 crc, unsigned char const *buf, size_t len, const u32 *tab)
49{
50# ifdef __LITTLE_ENDIAN
51# define DO_CRC(x) crc = tab[(crc ^ (x)) & 255 ] ^ (crc >> 8)
52# else
53# define DO_CRC(x) crc = tab[((crc >> 24) ^ (x)) & 255] ^ (crc << 8)
54# endif
55 const u32 *b = (const u32 *)buf;
56 size_t rem_len;
57
58 /* Align it */
59 if (unlikely((long)b & 3 && len)) {
60 u8 *p = (u8 *)b;
61 do {
62 DO_CRC(*p++);
63 } while ((--len) && ((long)p)&3);
64 b = (u32 *)p;
65 }
66 rem_len = len & 3;
67 /* load data 32 bits wide, xor data 32 bits wide. */
68 len = len >> 2;
69 for (--b; len; --len) {
70 crc ^= *++b; /* use pre increment for speed */
71 DO_CRC(0);
72 DO_CRC(0);
73 DO_CRC(0);
74 DO_CRC(0);
75 }
76 len = rem_len;
77 /* And the last few bytes */
78 if (len) {
79 u8 *p = (u8 *)(b + 1) - 1;
80 do {
81 DO_CRC(*++p); /* use pre increment for speed */
82 } while (--len);
83 }
84 return crc;
85}
86#endif
Randy Dunlap2f721002006-06-25 05:48:59 -070087/**
88 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
89 * @crc: seed value for computation. ~0 for Ethernet, sometimes 0 for
90 * other uses, or the previous crc32 value if computing incrementally.
91 * @p: pointer to buffer over which CRC is run
92 * @len: length of buffer @p
93 */
Ralf Baechlee8c44312007-10-18 03:07:07 -070094u32 __pure crc32_le(u32 crc, unsigned char const *p, size_t len);
Randy Dunlap2f721002006-06-25 05:48:59 -070095
Linus Torvalds1da177e2005-04-16 15:20:36 -070096#if CRC_LE_BITS == 1
97/*
98 * In fact, the table-based code will work in this case, but it can be
99 * simplified by inlining the table in ?: form.
100 */
101
Ralf Baechlee8c44312007-10-18 03:07:07 -0700102u32 __pure crc32_le(u32 crc, unsigned char const *p, size_t len)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700103{
104 int i;
105 while (len--) {
106 crc ^= *p++;
107 for (i = 0; i < 8; i++)
108 crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
109 }
110 return crc;
111}
112#else /* Table-based approach */
113
Ralf Baechlee8c44312007-10-18 03:07:07 -0700114u32 __pure crc32_le(u32 crc, unsigned char const *p, size_t len)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700115{
116# if CRC_LE_BITS == 8
Linus Torvalds1da177e2005-04-16 15:20:36 -0700117 const u32 *tab = crc32table_le;
118
Linus Torvalds1da177e2005-04-16 15:20:36 -0700119 crc = __cpu_to_le32(crc);
Joakim Tjernlundddcaccb2009-12-14 18:01:33 -0800120 crc = crc32_body(crc, p, len, tab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700121 return __le32_to_cpu(crc);
122#undef ENDIAN_SHIFT
123#undef DO_CRC
124
125# elif CRC_LE_BITS == 4
126 while (len--) {
127 crc ^= *p++;
128 crc = (crc >> 4) ^ crc32table_le[crc & 15];
129 crc = (crc >> 4) ^ crc32table_le[crc & 15];
130 }
131 return crc;
132# elif CRC_LE_BITS == 2
133 while (len--) {
134 crc ^= *p++;
135 crc = (crc >> 2) ^ crc32table_le[crc & 3];
136 crc = (crc >> 2) ^ crc32table_le[crc & 3];
137 crc = (crc >> 2) ^ crc32table_le[crc & 3];
138 crc = (crc >> 2) ^ crc32table_le[crc & 3];
139 }
140 return crc;
141# endif
142}
143#endif
144
Randy Dunlap2f721002006-06-25 05:48:59 -0700145/**
146 * crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32
147 * @crc: seed value for computation. ~0 for Ethernet, sometimes 0 for
148 * other uses, or the previous crc32 value if computing incrementally.
149 * @p: pointer to buffer over which CRC is run
150 * @len: length of buffer @p
151 */
Ralf Baechlee8c44312007-10-18 03:07:07 -0700152u32 __pure crc32_be(u32 crc, unsigned char const *p, size_t len);
Randy Dunlap2f721002006-06-25 05:48:59 -0700153
Linus Torvalds1da177e2005-04-16 15:20:36 -0700154#if CRC_BE_BITS == 1
155/*
156 * In fact, the table-based code will work in this case, but it can be
157 * simplified by inlining the table in ?: form.
158 */
159
Ralf Baechlee8c44312007-10-18 03:07:07 -0700160u32 __pure crc32_be(u32 crc, unsigned char const *p, size_t len)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700161{
162 int i;
163 while (len--) {
164 crc ^= *p++ << 24;
165 for (i = 0; i < 8; i++)
166 crc =
167 (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :
168 0);
169 }
170 return crc;
171}
172
173#else /* Table-based approach */
Ralf Baechlee8c44312007-10-18 03:07:07 -0700174u32 __pure crc32_be(u32 crc, unsigned char const *p, size_t len)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700175{
176# if CRC_BE_BITS == 8
Linus Torvalds1da177e2005-04-16 15:20:36 -0700177 const u32 *tab = crc32table_be;
178
Linus Torvalds1da177e2005-04-16 15:20:36 -0700179 crc = __cpu_to_be32(crc);
Joakim Tjernlundddcaccb2009-12-14 18:01:33 -0800180 crc = crc32_body(crc, p, len, tab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700181 return __be32_to_cpu(crc);
182#undef ENDIAN_SHIFT
183#undef DO_CRC
184
185# elif CRC_BE_BITS == 4
186 while (len--) {
187 crc ^= *p++ << 24;
188 crc = (crc << 4) ^ crc32table_be[crc >> 28];
189 crc = (crc << 4) ^ crc32table_be[crc >> 28];
190 }
191 return crc;
192# elif CRC_BE_BITS == 2
193 while (len--) {
194 crc ^= *p++ << 24;
195 crc = (crc << 2) ^ crc32table_be[crc >> 30];
196 crc = (crc << 2) ^ crc32table_be[crc >> 30];
197 crc = (crc << 2) ^ crc32table_be[crc >> 30];
198 crc = (crc << 2) ^ crc32table_be[crc >> 30];
199 }
200 return crc;
201# endif
202}
203#endif
204
Linus Torvalds1da177e2005-04-16 15:20:36 -0700205EXPORT_SYMBOL(crc32_le);
206EXPORT_SYMBOL(crc32_be);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700207
208/*
209 * A brief CRC tutorial.
210 *
211 * A CRC is a long-division remainder. You add the CRC to the message,
212 * and the whole thing (message+CRC) is a multiple of the given
213 * CRC polynomial. To check the CRC, you can either check that the
214 * CRC matches the recomputed value, *or* you can check that the
215 * remainder computed on the message+CRC is 0. This latter approach
216 * is used by a lot of hardware implementations, and is why so many
217 * protocols put the end-of-frame flag after the CRC.
218 *
219 * It's actually the same long division you learned in school, except that
220 * - We're working in binary, so the digits are only 0 and 1, and
221 * - When dividing polynomials, there are no carries. Rather than add and
222 * subtract, we just xor. Thus, we tend to get a bit sloppy about
223 * the difference between adding and subtracting.
224 *
225 * A 32-bit CRC polynomial is actually 33 bits long. But since it's
226 * 33 bits long, bit 32 is always going to be set, so usually the CRC
227 * is written in hex with the most significant bit omitted. (If you're
228 * familiar with the IEEE 754 floating-point format, it's the same idea.)
229 *
230 * Note that a CRC is computed over a string of *bits*, so you have
231 * to decide on the endianness of the bits within each byte. To get
232 * the best error-detecting properties, this should correspond to the
233 * order they're actually sent. For example, standard RS-232 serial is
234 * little-endian; the most significant bit (sometimes used for parity)
235 * is sent last. And when appending a CRC word to a message, you should
236 * do it in the right order, matching the endianness.
237 *
238 * Just like with ordinary division, the remainder is always smaller than
239 * the divisor (the CRC polynomial) you're dividing by. Each step of the
240 * division, you take one more digit (bit) of the dividend and append it
241 * to the current remainder. Then you figure out the appropriate multiple
242 * of the divisor to subtract to being the remainder back into range.
243 * In binary, it's easy - it has to be either 0 or 1, and to make the
244 * XOR cancel, it's just a copy of bit 32 of the remainder.
245 *
246 * When computing a CRC, we don't care about the quotient, so we can
247 * throw the quotient bit away, but subtract the appropriate multiple of
248 * the polynomial from the remainder and we're back to where we started,
249 * ready to process the next bit.
250 *
251 * A big-endian CRC written this way would be coded like:
252 * for (i = 0; i < input_bits; i++) {
253 * multiple = remainder & 0x80000000 ? CRCPOLY : 0;
254 * remainder = (remainder << 1 | next_input_bit()) ^ multiple;
255 * }
256 * Notice how, to get at bit 32 of the shifted remainder, we look
257 * at bit 31 of the remainder *before* shifting it.
258 *
259 * But also notice how the next_input_bit() bits we're shifting into
260 * the remainder don't actually affect any decision-making until
261 * 32 bits later. Thus, the first 32 cycles of this are pretty boring.
262 * Also, to add the CRC to a message, we need a 32-bit-long hole for it at
263 * the end, so we have to add 32 extra cycles shifting in zeros at the
264 * end of every message,
265 *
266 * So the standard trick is to rearrage merging in the next_input_bit()
267 * until the moment it's needed. Then the first 32 cycles can be precomputed,
268 * and merging in the final 32 zero bits to make room for the CRC can be
269 * skipped entirely.
270 * This changes the code to:
271 * for (i = 0; i < input_bits; i++) {
272 * remainder ^= next_input_bit() << 31;
273 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
274 * remainder = (remainder << 1) ^ multiple;
275 * }
276 * With this optimization, the little-endian code is simpler:
277 * for (i = 0; i < input_bits; i++) {
278 * remainder ^= next_input_bit();
279 * multiple = (remainder & 1) ? CRCPOLY : 0;
280 * remainder = (remainder >> 1) ^ multiple;
281 * }
282 *
283 * Note that the other details of endianness have been hidden in CRCPOLY
284 * (which must be bit-reversed) and next_input_bit().
285 *
286 * However, as long as next_input_bit is returning the bits in a sensible
287 * order, we can actually do the merging 8 or more bits at a time rather
288 * than one bit at a time:
289 * for (i = 0; i < input_bytes; i++) {
290 * remainder ^= next_input_byte() << 24;
291 * for (j = 0; j < 8; j++) {
292 * multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
293 * remainder = (remainder << 1) ^ multiple;
294 * }
295 * }
296 * Or in little-endian:
297 * for (i = 0; i < input_bytes; i++) {
298 * remainder ^= next_input_byte();
299 * for (j = 0; j < 8; j++) {
300 * multiple = (remainder & 1) ? CRCPOLY : 0;
301 * remainder = (remainder << 1) ^ multiple;
302 * }
303 * }
304 * If the input is a multiple of 32 bits, you can even XOR in a 32-bit
305 * word at a time and increase the inner loop count to 32.
306 *
307 * You can also mix and match the two loop styles, for example doing the
308 * bulk of a message byte-at-a-time and adding bit-at-a-time processing
309 * for any fractional bytes at the end.
310 *
311 * The only remaining optimization is to the byte-at-a-time table method.
312 * Here, rather than just shifting one bit of the remainder to decide
313 * in the correct multiple to subtract, we can shift a byte at a time.
314 * This produces a 40-bit (rather than a 33-bit) intermediate remainder,
315 * but again the multiple of the polynomial to subtract depends only on
316 * the high bits, the high 8 bits in this case.
317 *
Joe Perches643d1f72008-02-03 17:48:52 +0200318 * The multiple we need in that case is the low 32 bits of a 40-bit
Linus Torvalds1da177e2005-04-16 15:20:36 -0700319 * value whose high 8 bits are given, and which is a multiple of the
320 * generator polynomial. This is simply the CRC-32 of the given
321 * one-byte message.
322 *
323 * Two more details: normally, appending zero bits to a message which
324 * is already a multiple of a polynomial produces a larger multiple of that
325 * polynomial. To enable a CRC to detect this condition, it's common to
326 * invert the CRC before appending it. This makes the remainder of the
327 * message+crc come out not as zero, but some fixed non-zero value.
328 *
329 * The same problem applies to zero bits prepended to the message, and
330 * a similar solution is used. Instead of starting with a remainder of
331 * 0, an initial remainder of all ones is used. As long as you start
332 * the same way on decoding, it doesn't make a difference.
333 */
334
335#ifdef UNITTEST
336
337#include <stdlib.h>
338#include <stdio.h>
339
340#if 0 /*Not used at present */
341static void
342buf_dump(char const *prefix, unsigned char const *buf, size_t len)
343{
344 fputs(prefix, stdout);
345 while (len--)
346 printf(" %02x", *buf++);
347 putchar('\n');
348
349}
350#endif
351
352static void bytereverse(unsigned char *buf, size_t len)
353{
354 while (len--) {
Akinobu Mita906d66d2006-12-08 02:36:25 -0800355 unsigned char x = bitrev8(*buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700356 *buf++ = x;
357 }
358}
359
360static void random_garbage(unsigned char *buf, size_t len)
361{
362 while (len--)
363 *buf++ = (unsigned char) random();
364}
365
366#if 0 /* Not used at present */
367static void store_le(u32 x, unsigned char *buf)
368{
369 buf[0] = (unsigned char) x;
370 buf[1] = (unsigned char) (x >> 8);
371 buf[2] = (unsigned char) (x >> 16);
372 buf[3] = (unsigned char) (x >> 24);
373}
374#endif
375
376static void store_be(u32 x, unsigned char *buf)
377{
378 buf[0] = (unsigned char) (x >> 24);
379 buf[1] = (unsigned char) (x >> 16);
380 buf[2] = (unsigned char) (x >> 8);
381 buf[3] = (unsigned char) x;
382}
383
384/*
385 * This checks that CRC(buf + CRC(buf)) = 0, and that
386 * CRC commutes with bit-reversal. This has the side effect
387 * of bytewise bit-reversing the input buffer, and returns
388 * the CRC of the reversed buffer.
389 */
390static u32 test_step(u32 init, unsigned char *buf, size_t len)
391{
392 u32 crc1, crc2;
393 size_t i;
394
395 crc1 = crc32_be(init, buf, len);
396 store_be(crc1, buf + len);
397 crc2 = crc32_be(init, buf, len + 4);
398 if (crc2)
399 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
400 crc2);
401
402 for (i = 0; i <= len + 4; i++) {
403 crc2 = crc32_be(init, buf, i);
404 crc2 = crc32_be(crc2, buf + i, len + 4 - i);
405 if (crc2)
406 printf("\nCRC split fail: 0x%08x\n", crc2);
407 }
408
409 /* Now swap it around for the other test */
410
411 bytereverse(buf, len + 4);
Akinobu Mita906d66d2006-12-08 02:36:25 -0800412 init = bitrev32(init);
413 crc2 = bitrev32(crc1);
414 if (crc1 != bitrev32(crc2))
Dominik Hacklcfc646f2005-08-07 09:42:53 -0700415 printf("\nBit reversal fail: 0x%08x -> 0x%08x -> 0x%08x\n",
Akinobu Mita906d66d2006-12-08 02:36:25 -0800416 crc1, crc2, bitrev32(crc2));
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417 crc1 = crc32_le(init, buf, len);
418 if (crc1 != crc2)
419 printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,
420 crc2);
421 crc2 = crc32_le(init, buf, len + 4);
422 if (crc2)
423 printf("\nCRC cancellation fail: 0x%08x should be 0\n",
424 crc2);
425
426 for (i = 0; i <= len + 4; i++) {
427 crc2 = crc32_le(init, buf, i);
428 crc2 = crc32_le(crc2, buf + i, len + 4 - i);
429 if (crc2)
430 printf("\nCRC split fail: 0x%08x\n", crc2);
431 }
432
433 return crc1;
434}
435
436#define SIZE 64
437#define INIT1 0
438#define INIT2 0
439
440int main(void)
441{
442 unsigned char buf1[SIZE + 4];
443 unsigned char buf2[SIZE + 4];
444 unsigned char buf3[SIZE + 4];
445 int i, j;
446 u32 crc1, crc2, crc3;
447
448 for (i = 0; i <= SIZE; i++) {
449 printf("\rTesting length %d...", i);
450 fflush(stdout);
451 random_garbage(buf1, i);
452 random_garbage(buf2, i);
453 for (j = 0; j < i; j++)
454 buf3[j] = buf1[j] ^ buf2[j];
455
456 crc1 = test_step(INIT1, buf1, i);
457 crc2 = test_step(INIT2, buf2, i);
458 /* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */
459 crc3 = test_step(INIT1 ^ INIT2, buf3, i);
460 if (crc3 != (crc1 ^ crc2))
461 printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",
462 crc3, crc1, crc2);
463 }
464 printf("\nAll test complete. No failures expected.\n");
465 return 0;
466}
467
468#endif /* UNITTEST */