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