/*1* Oct 15, 2000 Matt Domsch <[email protected]>2* Nicer crc32 functions/docs submitted by [email protected]. Thanks!3* Code was from the public domain, copyright abandoned. Code was4* subsequently included in the kernel, thus was re-licensed under the5* GNU GPL v2.6*7* Oct 12, 2000 Matt Domsch <[email protected]>8* Same crc32 function was used in 5 other places in the kernel.9* I made one version, and deleted the others.10* There are various incantations of crc32(). Some use a seed of 0 or ~0.11* Some xor at the end with ~0. The generic crc32() function takes12* seed as an argument, and doesn't xor at the end. Then individual13* users can do whatever they need.14* drivers/net/smc9194.c uses seed ~0, doesn't xor with ~0.15* fs/jffs2 uses seed 0, doesn't xor with ~0.16* fs/partitions/efi.c uses seed ~0, xor's with ~0.17*18* This source code is licensed under the GNU General Public License,19* Version 2. See the file COPYING for more details.20*/2122#include <linux/crc32.h>23#include <linux/kernel.h>24#include <linux/module.h>25#include <linux/compiler.h>26#include <linux/types.h>27#include <linux/init.h>28#include <asm/atomic.h>29#include "crc32defs.h"30#if CRC_LE_BITS == 831# define tole(x) __constant_cpu_to_le32(x)32#else33# define tole(x) (x)34#endif3536#if CRC_BE_BITS == 837# define tobe(x) __constant_cpu_to_be32(x)38#else39# define tobe(x) (x)40#endif41#include "crc32table.h"4243MODULE_AUTHOR("Matt Domsch <[email protected]>");44MODULE_DESCRIPTION("Ethernet CRC32 calculations");45MODULE_LICENSE("GPL");4647#if CRC_LE_BITS == 8 || CRC_BE_BITS == 84849static inline u3250crc32_body(u32 crc, unsigned char const *buf, size_t len, const u32 (*tab)[256])51{52# ifdef __LITTLE_ENDIAN53# define DO_CRC(x) crc = tab[0][(crc ^ (x)) & 255] ^ (crc >> 8)54# define DO_CRC4 crc = tab[3][(crc) & 255] ^ \55tab[2][(crc >> 8) & 255] ^ \56tab[1][(crc >> 16) & 255] ^ \57tab[0][(crc >> 24) & 255]58# else59# define DO_CRC(x) crc = tab[0][((crc >> 24) ^ (x)) & 255] ^ (crc << 8)60# define DO_CRC4 crc = tab[0][(crc) & 255] ^ \61tab[1][(crc >> 8) & 255] ^ \62tab[2][(crc >> 16) & 255] ^ \63tab[3][(crc >> 24) & 255]64# endif65const u32 *b;66size_t rem_len;6768/* Align it */69if (unlikely((long)buf & 3 && len)) {70do {71DO_CRC(*buf++);72} while ((--len) && ((long)buf)&3);73}74rem_len = len & 3;75/* load data 32 bits wide, xor data 32 bits wide. */76len = len >> 2;77b = (const u32 *)buf;78for (--b; len; --len) {79crc ^= *++b; /* use pre increment for speed */80DO_CRC4;81}82len = rem_len;83/* And the last few bytes */84if (len) {85u8 *p = (u8 *)(b + 1) - 1;86do {87DO_CRC(*++p); /* use pre increment for speed */88} while (--len);89}90return crc;91#undef DO_CRC92#undef DO_CRC493}94#endif95/**96* crc32_le() - Calculate bitwise little-endian Ethernet AUTODIN II CRC3297* @crc: seed value for computation. ~0 for Ethernet, sometimes 0 for98* other uses, or the previous crc32 value if computing incrementally.99* @p: pointer to buffer over which CRC is run100* @len: length of buffer @p101*/102u32 __pure crc32_le(u32 crc, unsigned char const *p, size_t len);103104#if CRC_LE_BITS == 1105/*106* In fact, the table-based code will work in this case, but it can be107* simplified by inlining the table in ?: form.108*/109110u32 __pure crc32_le(u32 crc, unsigned char const *p, size_t len)111{112int i;113while (len--) {114crc ^= *p++;115for (i = 0; i < 8; i++)116crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);117}118return crc;119}120#else /* Table-based approach */121122u32 __pure crc32_le(u32 crc, unsigned char const *p, size_t len)123{124# if CRC_LE_BITS == 8125const u32 (*tab)[] = crc32table_le;126127crc = __cpu_to_le32(crc);128crc = crc32_body(crc, p, len, tab);129return __le32_to_cpu(crc);130# elif CRC_LE_BITS == 4131while (len--) {132crc ^= *p++;133crc = (crc >> 4) ^ crc32table_le[crc & 15];134crc = (crc >> 4) ^ crc32table_le[crc & 15];135}136return crc;137# elif CRC_LE_BITS == 2138while (len--) {139crc ^= *p++;140crc = (crc >> 2) ^ crc32table_le[crc & 3];141crc = (crc >> 2) ^ crc32table_le[crc & 3];142crc = (crc >> 2) ^ crc32table_le[crc & 3];143crc = (crc >> 2) ^ crc32table_le[crc & 3];144}145return crc;146# endif147}148#endif149150/**151* crc32_be() - Calculate bitwise big-endian Ethernet AUTODIN II CRC32152* @crc: seed value for computation. ~0 for Ethernet, sometimes 0 for153* other uses, or the previous crc32 value if computing incrementally.154* @p: pointer to buffer over which CRC is run155* @len: length of buffer @p156*/157u32 __pure crc32_be(u32 crc, unsigned char const *p, size_t len);158159#if CRC_BE_BITS == 1160/*161* In fact, the table-based code will work in this case, but it can be162* simplified by inlining the table in ?: form.163*/164165u32 __pure crc32_be(u32 crc, unsigned char const *p, size_t len)166{167int i;168while (len--) {169crc ^= *p++ << 24;170for (i = 0; i < 8; i++)171crc =172(crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE :1730);174}175return crc;176}177178#else /* Table-based approach */179u32 __pure crc32_be(u32 crc, unsigned char const *p, size_t len)180{181# if CRC_BE_BITS == 8182const u32 (*tab)[] = crc32table_be;183184crc = __cpu_to_be32(crc);185crc = crc32_body(crc, p, len, tab);186return __be32_to_cpu(crc);187# elif CRC_BE_BITS == 4188while (len--) {189crc ^= *p++ << 24;190crc = (crc << 4) ^ crc32table_be[crc >> 28];191crc = (crc << 4) ^ crc32table_be[crc >> 28];192}193return crc;194# elif CRC_BE_BITS == 2195while (len--) {196crc ^= *p++ << 24;197crc = (crc << 2) ^ crc32table_be[crc >> 30];198crc = (crc << 2) ^ crc32table_be[crc >> 30];199crc = (crc << 2) ^ crc32table_be[crc >> 30];200crc = (crc << 2) ^ crc32table_be[crc >> 30];201}202return crc;203# endif204}205#endif206207EXPORT_SYMBOL(crc32_le);208EXPORT_SYMBOL(crc32_be);209210/*211* A brief CRC tutorial.212*213* A CRC is a long-division remainder. You add the CRC to the message,214* and the whole thing (message+CRC) is a multiple of the given215* CRC polynomial. To check the CRC, you can either check that the216* CRC matches the recomputed value, *or* you can check that the217* remainder computed on the message+CRC is 0. This latter approach218* is used by a lot of hardware implementations, and is why so many219* protocols put the end-of-frame flag after the CRC.220*221* It's actually the same long division you learned in school, except that222* - We're working in binary, so the digits are only 0 and 1, and223* - When dividing polynomials, there are no carries. Rather than add and224* subtract, we just xor. Thus, we tend to get a bit sloppy about225* the difference between adding and subtracting.226*227* A 32-bit CRC polynomial is actually 33 bits long. But since it's228* 33 bits long, bit 32 is always going to be set, so usually the CRC229* is written in hex with the most significant bit omitted. (If you're230* familiar with the IEEE 754 floating-point format, it's the same idea.)231*232* Note that a CRC is computed over a string of *bits*, so you have233* to decide on the endianness of the bits within each byte. To get234* the best error-detecting properties, this should correspond to the235* order they're actually sent. For example, standard RS-232 serial is236* little-endian; the most significant bit (sometimes used for parity)237* is sent last. And when appending a CRC word to a message, you should238* do it in the right order, matching the endianness.239*240* Just like with ordinary division, the remainder is always smaller than241* the divisor (the CRC polynomial) you're dividing by. Each step of the242* division, you take one more digit (bit) of the dividend and append it243* to the current remainder. Then you figure out the appropriate multiple244* of the divisor to subtract to being the remainder back into range.245* In binary, it's easy - it has to be either 0 or 1, and to make the246* XOR cancel, it's just a copy of bit 32 of the remainder.247*248* When computing a CRC, we don't care about the quotient, so we can249* throw the quotient bit away, but subtract the appropriate multiple of250* the polynomial from the remainder and we're back to where we started,251* ready to process the next bit.252*253* A big-endian CRC written this way would be coded like:254* for (i = 0; i < input_bits; i++) {255* multiple = remainder & 0x80000000 ? CRCPOLY : 0;256* remainder = (remainder << 1 | next_input_bit()) ^ multiple;257* }258* Notice how, to get at bit 32 of the shifted remainder, we look259* at bit 31 of the remainder *before* shifting it.260*261* But also notice how the next_input_bit() bits we're shifting into262* the remainder don't actually affect any decision-making until263* 32 bits later. Thus, the first 32 cycles of this are pretty boring.264* Also, to add the CRC to a message, we need a 32-bit-long hole for it at265* the end, so we have to add 32 extra cycles shifting in zeros at the266* end of every message,267*268* So the standard trick is to rearrage merging in the next_input_bit()269* until the moment it's needed. Then the first 32 cycles can be precomputed,270* and merging in the final 32 zero bits to make room for the CRC can be271* skipped entirely.272* This changes the code to:273* for (i = 0; i < input_bits; i++) {274* remainder ^= next_input_bit() << 31;275* multiple = (remainder & 0x80000000) ? CRCPOLY : 0;276* remainder = (remainder << 1) ^ multiple;277* }278* With this optimization, the little-endian code is simpler:279* for (i = 0; i < input_bits; i++) {280* remainder ^= next_input_bit();281* multiple = (remainder & 1) ? CRCPOLY : 0;282* remainder = (remainder >> 1) ^ multiple;283* }284*285* Note that the other details of endianness have been hidden in CRCPOLY286* (which must be bit-reversed) and next_input_bit().287*288* However, as long as next_input_bit is returning the bits in a sensible289* order, we can actually do the merging 8 or more bits at a time rather290* than one bit at a time:291* for (i = 0; i < input_bytes; i++) {292* remainder ^= next_input_byte() << 24;293* for (j = 0; j < 8; j++) {294* multiple = (remainder & 0x80000000) ? CRCPOLY : 0;295* remainder = (remainder << 1) ^ multiple;296* }297* }298* Or in little-endian:299* for (i = 0; i < input_bytes; i++) {300* remainder ^= next_input_byte();301* for (j = 0; j < 8; j++) {302* multiple = (remainder & 1) ? CRCPOLY : 0;303* remainder = (remainder << 1) ^ multiple;304* }305* }306* If the input is a multiple of 32 bits, you can even XOR in a 32-bit307* word at a time and increase the inner loop count to 32.308*309* You can also mix and match the two loop styles, for example doing the310* bulk of a message byte-at-a-time and adding bit-at-a-time processing311* for any fractional bytes at the end.312*313* The only remaining optimization is to the byte-at-a-time table method.314* Here, rather than just shifting one bit of the remainder to decide315* in the correct multiple to subtract, we can shift a byte at a time.316* This produces a 40-bit (rather than a 33-bit) intermediate remainder,317* but again the multiple of the polynomial to subtract depends only on318* the high bits, the high 8 bits in this case.319*320* The multiple we need in that case is the low 32 bits of a 40-bit321* value whose high 8 bits are given, and which is a multiple of the322* generator polynomial. This is simply the CRC-32 of the given323* one-byte message.324*325* Two more details: normally, appending zero bits to a message which326* is already a multiple of a polynomial produces a larger multiple of that327* polynomial. To enable a CRC to detect this condition, it's common to328* invert the CRC before appending it. This makes the remainder of the329* message+crc come out not as zero, but some fixed non-zero value.330*331* The same problem applies to zero bits prepended to the message, and332* a similar solution is used. Instead of starting with a remainder of333* 0, an initial remainder of all ones is used. As long as you start334* the same way on decoding, it doesn't make a difference.335*/336337#ifdef UNITTEST338339#include <stdlib.h>340#include <stdio.h>341342#if 0 /*Not used at present */343static void344buf_dump(char const *prefix, unsigned char const *buf, size_t len)345{346fputs(prefix, stdout);347while (len--)348printf(" %02x", *buf++);349putchar('\n');350351}352#endif353354static void bytereverse(unsigned char *buf, size_t len)355{356while (len--) {357unsigned char x = bitrev8(*buf);358*buf++ = x;359}360}361362static void random_garbage(unsigned char *buf, size_t len)363{364while (len--)365*buf++ = (unsigned char) random();366}367368#if 0 /* Not used at present */369static void store_le(u32 x, unsigned char *buf)370{371buf[0] = (unsigned char) x;372buf[1] = (unsigned char) (x >> 8);373buf[2] = (unsigned char) (x >> 16);374buf[3] = (unsigned char) (x >> 24);375}376#endif377378static void store_be(u32 x, unsigned char *buf)379{380buf[0] = (unsigned char) (x >> 24);381buf[1] = (unsigned char) (x >> 16);382buf[2] = (unsigned char) (x >> 8);383buf[3] = (unsigned char) x;384}385386/*387* This checks that CRC(buf + CRC(buf)) = 0, and that388* CRC commutes with bit-reversal. This has the side effect389* of bytewise bit-reversing the input buffer, and returns390* the CRC of the reversed buffer.391*/392static u32 test_step(u32 init, unsigned char *buf, size_t len)393{394u32 crc1, crc2;395size_t i;396397crc1 = crc32_be(init, buf, len);398store_be(crc1, buf + len);399crc2 = crc32_be(init, buf, len + 4);400if (crc2)401printf("\nCRC cancellation fail: 0x%08x should be 0\n",402crc2);403404for (i = 0; i <= len + 4; i++) {405crc2 = crc32_be(init, buf, i);406crc2 = crc32_be(crc2, buf + i, len + 4 - i);407if (crc2)408printf("\nCRC split fail: 0x%08x\n", crc2);409}410411/* Now swap it around for the other test */412413bytereverse(buf, len + 4);414init = bitrev32(init);415crc2 = bitrev32(crc1);416if (crc1 != bitrev32(crc2))417printf("\nBit reversal fail: 0x%08x -> 0x%08x -> 0x%08x\n",418crc1, crc2, bitrev32(crc2));419crc1 = crc32_le(init, buf, len);420if (crc1 != crc2)421printf("\nCRC endianness fail: 0x%08x != 0x%08x\n", crc1,422crc2);423crc2 = crc32_le(init, buf, len + 4);424if (crc2)425printf("\nCRC cancellation fail: 0x%08x should be 0\n",426crc2);427428for (i = 0; i <= len + 4; i++) {429crc2 = crc32_le(init, buf, i);430crc2 = crc32_le(crc2, buf + i, len + 4 - i);431if (crc2)432printf("\nCRC split fail: 0x%08x\n", crc2);433}434435return crc1;436}437438#define SIZE 64439#define INIT1 0440#define INIT2 0441442int main(void)443{444unsigned char buf1[SIZE + 4];445unsigned char buf2[SIZE + 4];446unsigned char buf3[SIZE + 4];447int i, j;448u32 crc1, crc2, crc3;449450for (i = 0; i <= SIZE; i++) {451printf("\rTesting length %d...", i);452fflush(stdout);453random_garbage(buf1, i);454random_garbage(buf2, i);455for (j = 0; j < i; j++)456buf3[j] = buf1[j] ^ buf2[j];457458crc1 = test_step(INIT1, buf1, i);459crc2 = test_step(INIT2, buf2, i);460/* Now check that CRC(buf1 ^ buf2) = CRC(buf1) ^ CRC(buf2) */461crc3 = test_step(INIT1 ^ INIT2, buf3, i);462if (crc3 != (crc1 ^ crc2))463printf("CRC XOR fail: 0x%08x != 0x%08x ^ 0x%08x\n",464crc3, crc1, crc2);465}466printf("\nAll test complete. No failures expected.\n");467return 0;468}469470#endif /* UNITTEST */471472473