crc32.c 16 KB

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