crc32.c 14 KB

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