uboot/drivers/mtd/ubi/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#ifdef UBI_LINUX
  24#include <linux/crc32.h>
  25#include <linux/kernel.h>
  26#include <linux/module.h>
  27#include <linux/compiler.h>
  28#endif
  29#include <linux/types.h>
  30
  31#include <asm/byteorder.h>
  32
  33#ifdef UBI_LINUX
  34#include <linux/slab.h>
  35#include <linux/init.h>
  36#include <asm/atomic.h>
  37#endif
  38#include "crc32defs.h"
  39#define CRC_LE_BITS 8
  40
  41# define __force
  42#ifndef __constant_cpu_to_le32
  43#define __constant_cpu_to_le32(x) ((__force __le32)(__u32)(x))
  44#endif
  45#ifndef __constant_le32_to_cpu
  46#define __constant_le32_to_cpu(x) ((__force __u32)(__le32)(x))
  47#endif
  48
  49#if CRC_LE_BITS == 8
  50#define tole(x) __constant_cpu_to_le32(x)
  51#define tobe(x) __constant_cpu_to_be32(x)
  52#else
  53#define tole(x) (x)
  54#define tobe(x) (x)
  55#endif
  56#include "crc32table.h"
  57#ifdef UBI_LINUX
  58MODULE_AUTHOR("Matt Domsch <Matt_Domsch@dell.com>");
  59MODULE_DESCRIPTION("Ethernet CRC32 calculations");
  60MODULE_LICENSE("GPL");
  61#endif
  62/**
  63 * crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC32
  64 * @crc: seed value for computation.  ~0 for Ethernet, sometimes 0 for
  65 *      other uses, or the previous crc32 value if computing incrementally.
  66 * @p: pointer to buffer over which CRC is run
  67 * @len: length of buffer @p
  68 */
  69u32  crc32_le(u32 crc, unsigned char const *p, size_t len);
  70
  71#if CRC_LE_BITS == 1
  72/*
  73 * In fact, the table-based code will work in this case, but it can be
  74 * simplified by inlining the table in ?: form.
  75 */
  76
  77u32 crc32_le(u32 crc, unsigned char const *p, size_t len)
  78{
  79        int i;
  80        while (len--) {
  81                crc ^= *p++;
  82                for (i = 0; i < 8; i++)
  83                        crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
  84        }
  85        return crc;
  86}
  87#else                           /* Table-based approach */
  88
  89u32 crc32_le(u32 crc, unsigned char const *p, size_t len)
  90{
  91# if CRC_LE_BITS == 8
  92        const u32      *b =(u32 *)p;
  93        const u32      *tab = crc32table_le;
  94
  95# ifdef __LITTLE_ENDIAN
  96#  define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
  97# else
  98#  define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
  99# endif
 100        /* printf("Crc32_le crc=%x\n",crc); */
 101        crc = __cpu_to_le32(crc);
 102        /* Align it */
 103        if((((long)b)&3 && len)){
 104                do {
 105                        u8 *p = (u8 *)b;
 106                        DO_CRC(*p++);
 107                        b = (void *)p;
 108                } while ((--len) && ((long)b)&3 );
 109        }
 110        if((len >= 4)){
 111                /* load data 32 bits wide, xor data 32 bits wide. */
 112                size_t save_len = len & 3;
 113                len = len >> 2;
 114                --b; /* use pre increment below(*++b) for speed */
 115                do {
 116                        crc ^= *++b;
 117                        DO_CRC(0);
 118                        DO_CRC(0);
 119                        DO_CRC(0);
 120                        DO_CRC(0);
 121                } while (--len);
 122                b++; /* point to next byte(s) */
 123                len = save_len;
 124        }
 125        /* And the last few bytes */
 126        if(len){
 127                do {
 128                        u8 *p = (u8 *)b;
 129                        DO_CRC(*p++);
 130                        b = (void *)p;
 131                } while (--len);
 132        }
 133
 134        return __le32_to_cpu(crc);
 135#undef ENDIAN_SHIFT
 136#undef DO_CRC
 137
 138# elif CRC_LE_BITS == 4
 139        while (len--) {
 140                crc ^= *p++;
 141                crc = (crc >> 4) ^ crc32table_le[crc & 15];
 142                crc = (crc >> 4) ^ crc32table_le[crc & 15];
 143        }
 144        return crc;
 145# elif CRC_LE_BITS == 2
 146        while (len--) {
 147                crc ^= *p++;
 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                crc = (crc >> 2) ^ crc32table_le[crc & 3];
 152        }
 153        return crc;
 154# endif
 155}
 156#endif
 157#ifdef UBI_LINUX
 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 */
 165u32 __attribute_pure__ crc32_be(u32 crc, unsigned char const *p, size_t len);
 166
 167#if CRC_BE_BITS == 1
 168/*
 169 * In fact, the table-based code will work in this case, but it can be
 170 * simplified by inlining the table in ?: form.
 171 */
 172
 173u32 __attribute_pure__ crc32_be(u32 crc, unsigned char const *p, size_t len)
 174{
 175        int i;
 176        while (len--) {
 177                crc ^= *p++ << 24;
 178                for (i = 0; i < 8; i++)
 179                        crc =
 180                            (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :
 181                                          0);
 182        }
 183        return crc;
 184}
 185
 186#else                           /* Table-based approach */
 187u32 __attribute_pure__ crc32_be(u32 crc, unsigned char const *p, size_t len)
 188{
 189# if CRC_BE_BITS == 8
 190        const u32      *b =(u32 *)p;
 191        const u32      *tab = crc32table_be;
 192
 193# ifdef __LITTLE_ENDIAN
 194#  define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
 195# else
 196#  define DO_CRC(x) crc = tab[ ((crc >> 24) ^ (x)) & 255] ^ (crc<<8)
 197# endif
 198
 199        crc = __cpu_to_be32(crc);
 200        /* Align it */
 201        if(unlikely(((long)b)&3 && len)){
 202                do {
 203                        u8 *p = (u8 *)b;
 204                        DO_CRC(*p++);
 205                        b = (u32 *)p;
 206                } while ((--len) && ((long)b)&3 );
 207        }
 208        if(likely(len >= 4)){
 209                /* load data 32 bits wide, xor data 32 bits wide. */
 210                size_t save_len = len & 3;
 211                len = len >> 2;
 212                --b; /* use pre increment below(*++b) for speed */
 213                do {
 214                        crc ^= *++b;
 215                        DO_CRC(0);
 216                        DO_CRC(0);
 217                        DO_CRC(0);
 218                        DO_CRC(0);
 219                } while (--len);
 220                b++; /* point to next byte(s) */
 221                len = save_len;
 222        }
 223        /* And the last few bytes */
 224        if(len){
 225                do {
 226                        u8 *p = (u8 *)b;
 227                        DO_CRC(*p++);
 228                        b = (void *)p;
 229                } while (--len);
 230        }
 231        return __be32_to_cpu(crc);
 232#undef ENDIAN_SHIFT
 233#undef DO_CRC
 234
 235# elif CRC_BE_BITS == 4
 236        while (len--) {
 237                crc ^= *p++ << 24;
 238                crc = (crc << 4) ^ crc32table_be[crc >> 28];
 239                crc = (crc << 4) ^ crc32table_be[crc >> 28];
 240        }
 241        return crc;
 242# elif CRC_BE_BITS == 2
 243        while (len--) {
 244                crc ^= *p++ << 24;
 245                crc = (crc << 2) ^ crc32table_be[crc >> 30];
 246                crc = (crc << 2) ^ crc32table_be[crc >> 30];
 247                crc = (crc << 2) ^ crc32table_be[crc >> 30];
 248                crc = (crc << 2) ^ crc32table_be[crc >> 30];
 249        }
 250        return crc;
 251# endif
 252}
 253#endif
 254
 255EXPORT_SYMBOL(crc32_le);
 256EXPORT_SYMBOL(crc32_be);
 257#endif
 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#ifdef UNITTEST
 386
 387#include <stdlib.h>
 388#include <stdio.h>
 389
 390#ifdef UBI_LINUX                                /*Not used at present */
 391static void
 392buf_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
 402static void bytereverse(unsigned char *buf, size_t len)
 403{
 404        while (len--) {
 405                unsigned char x = bitrev8(*buf);
 406                *buf++ = x;
 407        }
 408}
 409
 410static void random_garbage(unsigned char *buf, size_t len)
 411{
 412        while (len--)
 413                *buf++ = (unsigned char) random();
 414}
 415
 416#ifdef UBI_LINUX                                /* Not used at present */
 417static void store_le(u32 x, unsigned char *buf)
 418{
 419        buf[0] = (unsigned char) x;
 420        buf[1] = (unsigned char) (x >> 8);
 421        buf[2] = (unsigned char) (x >> 16);
 422        buf[3] = (unsigned char) (x >> 24);
 423}
 424#endif
 425
 426static void store_be(u32 x, unsigned char *buf)
 427{
 428        buf[0] = (unsigned char) (x >> 24);
 429        buf[1] = (unsigned char) (x >> 16);
 430        buf[2] = (unsigned char) (x >> 8);
 431        buf[3] = (unsigned char) x;
 432}
 433
 434/*
 435 * This checks that CRC(buf + CRC(buf)) = 0, and that
 436 * CRC commutes with bit-reversal.  This has the side effect
 437 * of bytewise bit-reversing the input buffer, and returns
 438 * the CRC of the reversed buffer.
 439 */
 440static u32 test_step(u32 init, unsigned char *buf, size_t len)
 441{
 442        u32 crc1, crc2;
 443        size_t i;
 444
 445        crc1 = crc32_be(init, buf, len);
 446        store_be(crc1, buf + len);
 447        crc2 = crc32_be(init, buf, len + 4);
 448        if (crc2)
 449                printf("\nCRC cancellation fail: 0x%08x should be 0\n",
 450                       crc2);
 451
 452        for (i = 0; i <= len + 4; i++) {
 453                crc2 = crc32_be(init, buf, i);
 454                crc2 = crc32_be(crc2, buf + i, len + 4 - i);
 455                if (crc2)
 456                        printf("\nCRC split fail: 0x%08x\n", crc2);
 457        }
 458
 459        /* Now swap it around for the other test */
 460
 461        bytereverse(buf, len + 4);
 462        init = bitrev32(init);
 463        crc2 = bitrev32(crc1);
 464        if (crc1 != bitrev32(crc2))
 465                printf("\nBit reversal fail: 0x%08x -> 0x%08x -> 0x%08x\n",
 466                       crc1, crc2, bitrev32(crc2));
 467        crc1 = crc32_le(init, buf, len);
 468        if (crc1 != crc2)
 469                printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,
 470                       crc2);
 471        crc2 = crc32_le(init, buf, len + 4);
 472        if (crc2)
 473                printf("\nCRC cancellation fail: 0x%08x should be 0\n",
 474                       crc2);
 475
 476        for (i = 0; i <= len + 4; i++) {
 477                crc2 = crc32_le(init, buf, i);
 478                crc2 = crc32_le(crc2, buf + i, len + 4 - i);
 479                if (crc2)
 480                        printf("\nCRC split fail: 0x%08x\n", crc2);
 481        }
 482
 483        return crc1;
 484}
 485
 486#define SIZE 64
 487#define INIT1 0
 488#define INIT2 0
 489
 490int main(void)
 491{
 492        unsigned char buf1[SIZE + 4];
 493        unsigned char buf2[SIZE + 4];
 494        unsigned char buf3[SIZE + 4];
 495        int i, j;
 496        u32 crc1, crc2, crc3;
 497
 498        for (i = 0; i <= SIZE; i++) {
 499                printf("\rTesting length %d...", i);
 500                fflush(stdout);
 501                random_garbage(buf1, i);
 502                random_garbage(buf2, i);
 503                for (j = 0; j < i; j++)
 504                        buf3[j] = buf1[j] ^ buf2[j];
 505
 506                crc1 = test_step(INIT1, buf1, i);
 507                crc2 = test_step(INIT2, buf2, i);
 508                /* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */
 509                crc3 = test_step(INIT1 ^ INIT2, buf3, i);
 510                if (crc3 != (crc1 ^ crc2))
 511                        printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",
 512                               crc3, crc1, crc2);
 513        }
 514        printf("\nAll test complete.  No failures expected.\n");
 515        return 0;
 516}
 517
 518#endif                          /* UNITTEST */
 519