crc32.c 15 KB

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