crc32.c 14 KB

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