crc32.c 14 KB

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