crc32.c 15 KB

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