1 /* crc32.c -- compute the CRC-32 of a data stream
2 * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016, 2018 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
5 * This interleaved implementation of a CRC makes use of pipelined multiple
6 * arithmetic-logic units, commonly found in modern CPU cores. It is due to
7 * Kadatch and Jenkins (2010). See doc/crc-doc.1.0.pdf in this distribution.
13 Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
14 protection on the static variables used to control the first-use generation
15 of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
16 first call get_crc_table() to initialize the tables before allowing more than
17 one thread to use crc32().
19 MAKECRCH can be #defined to write out crc32.h. A main() routine is also
20 produced, so that this one source file can be compiled to an executable.
25 # ifndef DYNAMIC_CRC_TABLE
26 # define DYNAMIC_CRC_TABLE
27 # endif /* !DYNAMIC_CRC_TABLE */
30 #include "zutil.h" /* for Z_U4, Z_U8, z_crc_t, and FAR definitions */
33 A CRC of a message is computed on N braids of words in the message, where
34 each word consists of W bytes (4 or 8). If N is 3, for example, then three
35 running sparse CRCs are calculated respectively on each braid, at these
36 indices in the array of words: 0, 3, 6, ..., 1, 4, 7, ..., and 2, 5, 8, ...
37 This is done starting at a word boundary, and continues until as many blocks
38 of N * W bytes as are available have been processed. The results are combined
39 into a single CRC at the end. For this code, N must be in the range 1..6 and
40 W must be 4 or 8. The upper limit on N can be increased if desired by adding
41 more #if blocks, extending the patterns apparent in the code. In addition,
42 crc32.h would need to be regenerated, if the maximum N value is increased.
44 N and W are chosen empirically by benchmarking the execution time on a given
45 processor. The choices for N and W below were based on testing on Intel Kaby
46 Lake i7, AMD Ryzen 7, ARM Cortex-A57, Sparc64-VII, PowerPC POWER9, and MIPS64
47 Octeon II processors. The Intel, AMD, and ARM processors were all fastest
48 with N=5, W=8. The Sparc, PowerPC, and MIPS64 were all fastest at N=5, W=4.
49 They were all tested with either gcc or clang, all using the -O3 optimization
50 level. Your mileage may vary.
60 # error N must be in 1..6
64 z_crc_t must be at least 32 bits. z_word_t must be at least as long as
65 z_crc_t. It is assumed here that z_word_t is either 32 bits or 64 bits, and
66 that bytes are eight bits.
70 Define W and the associated z_word_t type. If W is not defined, then a
71 braided calculation is not used, and the associated tables and code are not
80 # define W 8 /* required for MAKECRCH */
82 # if defined(__x86_64__) || defined(__aarch64__)
90 # if W == 8 && defined(Z_U8)
91 typedef Z_U8 z_word_t;
95 typedef Z_U4 z_word_t;
101 /* Local functions. */
102 local z_crc_t multmodp OF((z_crc_t a, z_crc_t b));
103 local z_crc_t x2nmodp OF((z_off64_t n, unsigned k));
105 local z_word_t byte_swap OF((z_word_t word));
106 local z_crc_t crc_word OF((z_word_t data));
107 local z_word_t crc_word_big OF((z_word_t data));
110 /* CRC polynomial. */
111 #define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */
113 #ifdef DYNAMIC_CRC_TABLE
115 local z_crc_t FAR crc_table[256];
116 local z_crc_t FAR x2n_table[32];
117 local void make_crc_table OF((void));
119 local z_word_t FAR crc_big_table[256];
120 local z_crc_t FAR crc_braid_table[W][256];
121 local z_word_t FAR crc_braid_big_table[W][256];
122 local void braid OF((z_crc_t [][256], z_word_t [][256], int, int));
125 local void write_table OF((FILE *, const z_crc_t FAR *, int));
126 local void write_table32hi OF((FILE *, const z_word_t FAR *, int));
127 local void write_table64 OF((FILE *, const z_word_t FAR *, int));
128 #endif /* MAKECRCH */
131 Define a once() function depending on the availability of atomics. If this is
132 compiled with DYNAMIC_CRC_TABLE defined, and if CRCs will be computed in
133 multiple threads, and if atomics are not available, then get_crc_table() must
134 be called to initialize the tables and must return before any threads are
135 allowed to compute or combine CRCs.
138 /* Definition of once functionality. */
139 typedef struct once_s once_t;
140 local void once OF((once_t *, void (*)(void)));
142 /* Check for the availability of atomics. */
143 #if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \
144 !defined(__STDC_NO_ATOMICS__)
146 #include <stdatomic.h>
148 /* Structure for once(), which must be initialized with ONCE_INIT. */
153 #define ONCE_INIT {ATOMIC_FLAG_INIT, 0}
156 Run the provided init() function exactly once, even if multiple threads
157 invoke once() at the same time. The state must be a once_t initialized with
160 local void once(state, init)
164 if (!atomic_load(&state->done)) {
165 if (atomic_flag_test_and_set(&state->begun))
166 while (!atomic_load(&state->done))
170 atomic_store(&state->done, 1);
175 #else /* no atomics */
177 /* Structure for once(), which must be initialized with ONCE_INIT. */
182 #define ONCE_INIT {0, 0}
184 /* Test and set. Alas, not atomic, but tries to minimize the period of
186 local int test_and_set OF((int volatile *));
187 local int test_and_set(flag)
197 /* Run the provided init() function once. This is not thread-safe. */
198 local void once(state, init)
203 if (test_and_set(&state->begun))
215 /* State for once(). */
216 local once_t made = ONCE_INIT;
219 Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
220 x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
222 Polynomials over GF(2) are represented in binary, one bit per coefficient,
223 with the lowest powers in the most significant bit. Then adding polynomials
224 is just exclusive-or, and multiplying a polynomial by x is a right shift by
225 one. If we call the above polynomial p, and represent a byte as the
226 polynomial q, also with the lowest power in the most significant bit (so the
227 byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
228 where a mod b means the remainder after dividing a by b.
230 This calculation is done using the shift-register method of multiplying and
231 taking the remainder. The register is initialized to zero, and for each
232 incoming bit, x^32 is added mod p to the register if the bit is a one (where
233 x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x
234 (which is shifting right by one and adding x^32 mod p if the bit shifted out
235 is a one). We start with the highest power (least significant bit) of q and
236 repeat for all eight bits of q.
238 The table is simply the CRC of all possible eight bit values. This is all the
239 information needed to generate CRCs on data a byte at a time for all
240 combinations of CRC register values and incoming bytes.
243 local void make_crc_table()
248 /* initialize the CRC of bytes tables */
249 for (i = 0; i < 256; i++) {
251 for (j = 0; j < 8; j++)
252 p = p & 1 ? (p >> 1) ^ POLY : p >> 1;
255 crc_big_table[i] = byte_swap(p);
259 /* initialize the x^2^n mod p(x) table */
260 p = (z_crc_t)1 << 30; /* x^1 */
262 for (n = 1; n < 32; n++)
263 x2n_table[n] = p = multmodp(p, p);
266 /* initialize the braiding tables -- needs x2n_table[] */
267 braid(crc_braid_table, crc_braid_big_table, N, W);
273 The crc32.h header file contains tables for both 32-bit and 64-bit
274 z_word_t's, and so requires a 64-bit type be available. In that case,
275 z_word_t must be defined to be 64-bits. This code then also generates
276 and writes out the tables for the case that z_word_t is 32 bits.
278 #if !defined(W) || W != 8
279 # error Need a 64-bit integer type in order to generate crc32.h.
284 z_word_t big[8][256];
286 out = fopen("crc32.h", "w");
287 if (out == NULL) return;
289 /* write out little-endian CRC table to crc32.h */
291 "/* crc32.h -- tables for rapid CRC calculation\n"
292 " * Generated automatically by crc32.c\n */\n"
294 "local const z_crc_t FAR crc_table[] = {\n"
296 write_table(out, crc_table, 256);
300 /* write out big-endian CRC table for 64-bit z_word_t to crc32.h */
307 "local const z_word_t FAR crc_big_table[] = {\n"
309 write_table64(out, crc_big_table, 256);
313 /* write out big-endian CRC table for 32-bit z_word_t to crc32.h */
316 "#else /* W == 4 */\n"
318 "local const z_word_t FAR crc_big_table[] = {\n"
320 write_table32hi(out, crc_big_table, 256);
326 /* write out braid tables for each value of N */
327 for (n = 1; n <= 6; n++) {
332 /* compute braid tables for this N and 64-bit word_t */
333 braid(ltl, big, n, 8);
335 /* write out braid tables for 64-bit z_word_t to crc32.h */
340 "local const z_crc_t FAR crc_braid_table[][256] = {\n");
341 for (k = 0; k < 8; k++) {
343 write_table(out, ltl[k], 256);
344 fprintf(out, "}%s", k < 7 ? ",\n" : "");
349 "local const z_word_t FAR crc_braid_big_table[][256] = {\n");
350 for (k = 0; k < 8; k++) {
352 write_table64(out, big[k], 256);
353 fprintf(out, "}%s", k < 7 ? ",\n" : "");
358 /* compute braid tables for this N and 32-bit word_t */
359 braid(ltl, big, n, 4);
361 /* write out braid tables for 32-bit z_word_t to crc32.h */
364 "#else /* W == 4 */\n"
366 "local const z_crc_t FAR crc_braid_table[][256] = {\n");
367 for (k = 0; k < 4; k++) {
369 write_table(out, ltl[k], 256);
370 fprintf(out, "}%s", k < 3 ? ",\n" : "");
375 "local const z_word_t FAR crc_braid_big_table[][256] = {\n");
376 for (k = 0; k < 4; k++) {
378 write_table32hi(out, big[k], 256);
379 fprintf(out, "}%s", k < 3 ? ",\n" : "");
392 /* write out zeros operator table to crc32.h */
395 "local const z_crc_t FAR x2n_table[] = {\n"
397 write_table(out, x2n_table, 32);
402 #endif /* MAKECRCH */
408 Write the 32-bit values in table[0..k-1] to out, five per line in
409 hexadecimal separated by commas.
411 local void write_table(out, table, k)
413 const z_crc_t FAR *table;
418 for (n = 0; n < k; n++)
419 fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ",
420 (unsigned long)(table[n]),
421 n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", "));
425 Write the high 32-bits of each value in table[0..k-1] to out, five per line
426 in hexadecimal separated by commas.
428 local void write_table32hi(out, table, k)
430 const z_word_t FAR *table;
435 for (n = 0; n < k; n++)
436 fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ",
437 (unsigned long)(table[n] >> 32),
438 n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", "));
442 Write the 64-bit values in table[0..k-1] to out, three per line in
443 hexadecimal separated by commas. This assumes that if there is a 64-bit
444 type, then there is also a long long integer type, and it is at least 64
445 bits. If not, then the type cast and format string can be adjusted
448 local void write_table64(out, table, k)
450 const z_word_t FAR *table;
455 for (n = 0; n < k; n++)
456 fprintf(out, "%s0x%016llx%s", n == 0 || n % 3 ? "" : " ",
457 (unsigned long long)(table[n]),
458 n == k - 1 ? "" : (n % 3 == 2 ? ",\n" : ", "));
461 /* Actually do the deed. */
468 #endif /* MAKECRCH */
472 Generate the little and big-endian braid tables for the given n and z_word_t
473 size w. Each array must have room for w blocks of 256 elements.
475 local void braid(ltl, big, n, w)
483 for (k = 0; k < w; k++) {
484 p = x2nmodp((n * w + 3 - k) << 3, 0);
486 big[w - 1 - k][0] = 0;
487 for (i = 1; i < 256; i++) {
488 ltl[k][i] = q = multmodp(i << 24, p);
489 big[w - 1 - k][i] = byte_swap(q);
495 #else /* !DYNAMIC_CRC_TABLE */
496 /* ========================================================================
497 * Tables for byte-wise and braided CRC-32 calculations, and a table of powers
498 * of x for combining CRC-32s, all made by make_crc_table().
501 #endif /* DYNAMIC_CRC_TABLE */
503 /* ========================================================================
504 * Routines used for CRC calculation. Some are also required for the table
509 Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial,
510 reflected. For speed, this requires that a not be zero.
512 local z_crc_t multmodp(a, b)
518 m = (z_crc_t)1 << 31;
523 if ((a & (m - 1)) == 0)
527 b = b & 1 ? (b >> 1) ^ POLY : b >> 1;
533 Return x^(n+k) modulo p(x). Requires that x2n_table[] has been initialized.
535 local z_crc_t x2nmodp(n, k)
541 p = (z_crc_t)1 << 31; /* x^0 == 1 */
544 p = multmodp(x2n_table[k & 31], p);
554 Swap the bytes in a z_word_t to convert between little and big endian. Any
555 self-respecting compiler will optimize this to a single machine byte-swap
556 instruction, if one is available. This assumes that word_t is either 32 bits
559 local z_word_t byte_swap(word)
564 (word & 0xff00000000000000) >> 56 |
565 (word & 0xff000000000000) >> 40 |
566 (word & 0xff0000000000) >> 24 |
567 (word & 0xff00000000) >> 8 |
568 (word & 0xff000000) << 8 |
569 (word & 0xff0000) << 24 |
570 (word & 0xff00) << 40 |
574 (word & 0xff000000) >> 24 |
575 (word & 0xff0000) >> 8 |
576 (word & 0xff00) << 8 |
582 Return the CRC of the W bytes in the word_t data, taking the
583 least-significant byte of the word as the first byte of data, without any pre
584 or post conditioning. This is used to combine the CRCs of each braid.
586 local z_crc_t crc_word(data)
590 for (k = 0; k < W; k++)
591 data = (data >> 8) ^ crc_table[data & 0xff];
592 return (z_crc_t)data;
595 local z_word_t crc_word_big(data)
599 for (k = 0; k < W; k++)
601 crc_big_table[(data >> ((W - 1) << 3)) & 0xff];
607 /* =========================================================================
608 * This function can be used by asm versions of crc32(), and to force the
609 * generation of the CRC tables in a threaded application.
611 const z_crc_t FAR * ZEXPORT get_crc_table()
613 #ifdef DYNAMIC_CRC_TABLE
614 once(&made, make_crc_table);
615 #endif /* DYNAMIC_CRC_TABLE */
616 return (const z_crc_t FAR *)crc_table;
619 /* ========================================================================= */
620 unsigned long ZEXPORT crc32_z(crc, buf, len)
622 const unsigned char FAR *buf;
625 /* Return initial CRC, if requested. */
626 if (buf == Z_NULL) return 0;
628 #ifdef DYNAMIC_CRC_TABLE
629 once(&made, make_crc_table);
630 #endif /* DYNAMIC_CRC_TABLE */
632 /* Pre-condition the CRC */
637 /* If provided enough bytes, do a braided CRC calculation. */
638 if (len >= N * W + W - 1) {
640 z_word_t const *words;
644 /* Compute the CRC up to a z_word_t boundary. */
645 while (len && ((z_size_t)buf & (W - 1)) != 0) {
647 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
650 /* Compute the CRC on as many N z_word_t blocks as are available. */
651 blks = len / (N * W);
653 words = (z_word_t const *)buf;
655 /* Do endian check at execution time instead of compile time, since ARM
656 processors can change the endianess at execution time. If the
657 compiler knows what the endianess will be, it can optimize out the
658 check and the unused branch. */
660 if (*(unsigned char *)&endian) {
686 /* Initialize the CRC for each braid. */
705 Process the first blks-1 blocks, computing the CRCs on each braid
709 /* Load the word for each braid into registers. */
710 word0 = crc0 ^ words[0];
712 word1 = crc1 ^ words[1];
714 word2 = crc2 ^ words[2];
716 word3 = crc3 ^ words[3];
718 word4 = crc4 ^ words[4];
720 word5 = crc5 ^ words[5];
728 /* Compute and update the CRC for each word. The loop should
730 crc0 = crc_braid_table[0][word0 & 0xff];
732 crc1 = crc_braid_table[0][word1 & 0xff];
734 crc2 = crc_braid_table[0][word2 & 0xff];
736 crc3 = crc_braid_table[0][word3 & 0xff];
738 crc4 = crc_braid_table[0][word4 & 0xff];
740 crc5 = crc_braid_table[0][word5 & 0xff];
746 for (k = 1; k < W; k++) {
747 crc0 ^= crc_braid_table[k][(word0 >> (k << 3)) & 0xff];
749 crc1 ^= crc_braid_table[k][(word1 >> (k << 3)) & 0xff];
751 crc2 ^= crc_braid_table[k][(word2 >> (k << 3)) & 0xff];
753 crc3 ^= crc_braid_table[k][(word3 >> (k << 3)) & 0xff];
755 crc4 ^= crc_braid_table[k][(word4 >> (k << 3)) & 0xff];
757 crc5 ^= crc_braid_table[k][(word5 >> (k << 3)) & 0xff];
767 Process the last block, combining the CRCs of the N braids at the
770 crc = crc_word(crc0 ^ words[0]);
772 crc = crc_word(crc1 ^ words[1] ^ crc);
774 crc = crc_word(crc2 ^ words[2] ^ crc);
776 crc = crc_word(crc3 ^ words[3] ^ crc);
778 crc = crc_word(crc4 ^ words[4] ^ crc);
780 crc = crc_word(crc5 ^ words[5] ^ crc);
791 z_word_t crc0, word0, comb;
793 z_word_t crc1, word1;
795 z_word_t crc2, word2;
797 z_word_t crc3, word3;
799 z_word_t crc4, word4;
801 z_word_t crc5, word5;
808 /* Initialize the CRC for each braid. */
809 crc0 = byte_swap(crc);
827 Process the first blks-1 blocks, computing the CRCs on each braid
831 /* Load the word for each braid into registers. */
832 word0 = crc0 ^ words[0];
834 word1 = crc1 ^ words[1];
836 word2 = crc2 ^ words[2];
838 word3 = crc3 ^ words[3];
840 word4 = crc4 ^ words[4];
842 word5 = crc5 ^ words[5];
850 /* Compute and update the CRC for each word. The loop should
852 crc0 = crc_braid_big_table[0][word0 & 0xff];
854 crc1 = crc_braid_big_table[0][word1 & 0xff];
856 crc2 = crc_braid_big_table[0][word2 & 0xff];
858 crc3 = crc_braid_big_table[0][word3 & 0xff];
860 crc4 = crc_braid_big_table[0][word4 & 0xff];
862 crc5 = crc_braid_big_table[0][word5 & 0xff];
868 for (k = 1; k < W; k++) {
869 crc0 ^= crc_braid_big_table[k][(word0 >> (k << 3)) & 0xff];
871 crc1 ^= crc_braid_big_table[k][(word1 >> (k << 3)) & 0xff];
873 crc2 ^= crc_braid_big_table[k][(word2 >> (k << 3)) & 0xff];
875 crc3 ^= crc_braid_big_table[k][(word3 >> (k << 3)) & 0xff];
877 crc4 ^= crc_braid_big_table[k][(word4 >> (k << 3)) & 0xff];
879 crc5 ^= crc_braid_big_table[k][(word5 >> (k << 3)) & 0xff];
889 Process the last block, combining the CRCs of the N braids at the
892 comb = crc_word_big(crc0 ^ words[0]);
894 comb = crc_word_big(crc1 ^ words[1] ^ comb);
896 comb = crc_word_big(crc2 ^ words[2] ^ comb);
898 comb = crc_word_big(crc3 ^ words[3] ^ comb);
900 comb = crc_word_big(crc4 ^ words[4] ^ comb);
902 comb = crc_word_big(crc5 ^ words[5] ^ comb);
909 crc = byte_swap(comb);
913 Update the pointer to the remaining bytes to process.
915 buf = (unsigned char const *)words;
920 /* Complete the computation of the CRC on any remaining bytes. */
923 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
924 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
925 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
926 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
927 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
928 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
929 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
930 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
934 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
937 /* Return the CRC, post-conditioned. */
938 return crc ^ 0xffffffff;
941 /* ========================================================================= */
942 unsigned long ZEXPORT crc32(crc, buf, len)
944 const unsigned char FAR *buf;
947 return crc32_z(crc, buf, len);
950 /* ========================================================================= */
951 uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
956 #ifdef DYNAMIC_CRC_TABLE
957 once(&made, make_crc_table);
958 #endif /* DYNAMIC_CRC_TABLE */
959 return multmodp(x2nmodp(len2, 3), crc1) ^ crc2;
962 /* ========================================================================= */
963 uLong ZEXPORT crc32_combine(crc1, crc2, len2)
968 return crc32_combine64(crc1, crc2, len2);
971 /* ========================================================================= */
972 uLong ZEXPORT crc32_combine_gen64(len2)
975 #ifdef DYNAMIC_CRC_TABLE
976 once(&made, make_crc_table);
977 #endif /* DYNAMIC_CRC_TABLE */
978 return x2nmodp(len2, 3);
981 /* ========================================================================= */
982 uLong ZEXPORT crc32_combine_gen(len2)
985 return crc32_combine_gen64(len2);
988 /* ========================================================================= */
989 uLong crc32_combine_op(crc1, crc2, op)
994 return multmodp(op, crc1) ^ crc2;