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