crc32.c 15 KB

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