Debian Codegraph @

storage/innobase/ut/crc32.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2009, 2010 Facebook, Inc.
4 Copyright (c) 2011, 2026, Oracle and/or its affiliates.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License, version 2.0,
8 as published by the Free Software Foundation.
9
10 This program is designed to work with certain software (including
11 but not limited to OpenSSL) that is licensed under separate terms,
12 as designated in a particular file or component or in included license
13 documentation. The authors of MySQL hereby grant you an additional
14 permission to link the program and your derivative works with the
15 separately licensed software that they have either included with
16 the program or referenced in the documentation.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License, version 2.0, for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26
27 *****************************************************************************/
28
29 /** @file ut/crc32.cc
30 CRC32 implementation from Facebook, based on the zlib implementation.
31
32 Created Aug 8, 2011, Vasil Dimov, based on mysys/my_crc32.c and
33 mysys/my_perf.c, contributed by Facebook under the following license.
34 ********************************************************************/
35
36 /* Copyright (C) 2009-2010 Facebook, Inc. All Rights Reserved.
37
38 Dual licensed under BSD license and GPLv2.
39
40 Redistribution and use in source and binary forms, with or without
41 modification, are permitted provided that the following conditions are met:
42 1. Redistributions of source code must retain the above copyright notice,
43 this list of conditions and the following disclaimer.
44 2. Redistributions in binary form must reproduce the above copyright notice,
45 this list of conditions and the following disclaimer in the documentation
46 and/or other materials provided with the distribution.
47
48 THIS SOFTWARE IS PROVIDED BY FACEBOOK, INC. ``AS IS'' AND ANY EXPRESS OR
49 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
50 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
51 EVENT SHALL FACEBOOK, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
52 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
53 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
54 OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
55 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
56 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
57 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58
59 This program is free software; you can redistribute it and/or modify it
60 under the terms of the GNU General Public License as published by the Free
61 Software Foundation; version 2 of the License.
62
63 This program is distributed in the hope that it will be useful, but WITHOUT
64 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
65 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
66 more details.
67
68 You should have received a copy of the GNU General Public License along with
69 this program; if not, write to the Free Software Foundation, Inc.,
70 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
71
72 /* The below CRC32 implementation is based on the implementation included with
73 zlib with modifications to process 8 bytes at a time and using SSE 4.2
74 extensions when available. The polynomial constant has been changed to
75 match the one used by SSE 4.2 and does not return the same value as the
76 version used by zlib. The original zlib copyright notice follows. */
77
78 /* crc32.c -- compute the CRC-32 of a buf stream
79 Copyright (C) 1995-2005 Mark Adler
80 For conditions of distribution and use, see copyright notice in zlib.h
81
82 Thanks to Rodney Brown <[email protected]> for his contribution of faster
83 CRC methods: exclusive-oring 32 bits of buf at a time, and pre-computing
84 tables for updating the shift register in one step with three exclusive-ors
85 instead of four steps with four exclusive-ors. This results in about a
86 factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
87 */
88
89 /** NOTE: The functions in this file should only use functions from
90 other files in library. The code in this file is used to make a library for
91 external tools. */
92
93 #include <string.h>
94 #include "my_compiler.h"
95 #include "my_config.h"
96 #include "my_inttypes.h"
97 #include "univ.i"
98 #include "ut0crc32.h"
99
100 /** Pointer to CRC32 calculation function. */
101 ut_crc32_func_t ut_crc32;
102
103 bool ut_crc32_cpu_enabled = false;
104 bool ut_poly_mul_cpu_enabled = false;
105
106 /* CRC32 software implementation. */
107 namespace software {
108
109 /** Swap the byte order of an 8 byte integer.
110 @param[in] i 8-byte integer
111 @return 8-byte integer */
112 inline uint64_t swap_byteorder(uint64_t i) {
113 return (i << 56 | (i & 0x000000000000FF00ULL) << 40 |
114 (i & 0x0000000000FF0000ULL) << 24 | (i & 0x00000000FF000000ULL) << 8 |
115 (i & 0x000000FF00000000ULL) >> 8 | (i & 0x0000FF0000000000ULL) >> 24 |
116 (i & 0x00FF000000000000ULL) >> 40 | i >> 56);
117 }
118
119 /* Precalculated table used to generate the CRC32 if the CPU does not
120 have support for it */
121 static uint32_t crc32_slice8_table[8][256];
122
123 #ifdef UNIV_DEBUG
124 static bool crc32_slice8_table_initialized = false;
125 #endif /* UNIV_DEBUG */
126
127 /** Initializes the table that is used to generate the CRC32 if the CPU does
128 not have support for it. */
129 static void crc32_slice8_table_init() {
130 /* bit-reversed poly 0x1EDC6F41 (from SSE42 crc32 instruction) */
131 static const uint32_t poly = 0x82f63b78;
132 uint32_t n;
133 uint32_t k;
134 uint32_t c;
135
136 for (n = 0; n < 256; n++) {
137 c = n;
138 for (k = 0; k < 8; k++) {
139 c = (c & 1) ? (poly ^ (c >> 1)) : (c >> 1);
140 }
141 crc32_slice8_table[0][n] = c;
142 }
143
144 for (n = 0; n < 256; n++) {
145 c = crc32_slice8_table[0][n];
146 for (k = 1; k < 8; k++) {
147 c = crc32_slice8_table[0][c & 0xFF] ^ (c >> 8);
148 crc32_slice8_table[k][n] = c;
149 }
150 }
151
152 #ifdef UNIV_DEBUG
153 crc32_slice8_table_initialized = true;
154 #endif /* UNIV_DEBUG */
155 }
156
157 /** Calculate CRC32 over 8-bit data using a software implementation.
158 @param[in,out] crc crc32 checksum so far when this function is called,
159 when the function ends it will contain the new checksum
160 @param[in,out] data data to be checksummed, the pointer will be advanced
161 with 1 byte
162 @param[in,out] len remaining bytes, it will be decremented with 1 */
163 inline void crc32_8(uint32_t *crc, const byte **data, size_t *len) {
164 const uint8_t i = (*crc ^ (*data)[0]) & 0xFF;
165
166 *crc = (*crc >> 8) ^ crc32_slice8_table[0][i];
167
168 (*data)++;
169 (*len)--;
170 }
171
172 /** Calculate CRC32 over a 64-bit integer using a software implementation.
173 @param[in] crc crc32 checksum so far
174 @param[in] data data to be checksummed
175 @return resulting checksum of crc + crc(data) */
176 inline uint32_t crc32_64_low(uint32_t crc, uint64_t data) {
177 const uint64_t i = crc ^ data;
178
179 return (crc32_slice8_table[7][(i)&0xFF] ^
180 crc32_slice8_table[6][(i >> 8) & 0xFF] ^
181 crc32_slice8_table[5][(i >> 16) & 0xFF] ^
182 crc32_slice8_table[4][(i >> 24) & 0xFF] ^
183 crc32_slice8_table[3][(i >> 32) & 0xFF] ^
184 crc32_slice8_table[2][(i >> 40) & 0xFF] ^
185 crc32_slice8_table[1][(i >> 48) & 0xFF] ^
186 crc32_slice8_table[0][(i >> 56)]);
187 }
188
189 /** Calculate CRC32 over 64-bit byte string using a software implementation.
190 @param[in,out] crc crc32 checksum so far when this function is called,
191 when the function ends it will contain the new checksum
192 @param[in,out] data data to be checksummed, the pointer will be advanced
193 with 8 bytes
194 @param[in,out] len remaining bytes, it will be decremented with 8 */
195 static inline void crc32_64(uint32_t *crc, const byte **data, size_t *len) {
196 uint64_t data_int = *reinterpret_cast<const uint64_t *>(*data);
197
198 #ifdef WORDS_BIGENDIAN
199 data_int = swap_byteorder(data_int);
200 #endif /* WORDS_BIGENDIAN */
201
202 *crc = crc32_64_low(*crc, data_int);
203
204 *data += 8;
205 *len -= 8;
206 }
207
208 /** Calculate CRC32 over 64-bit byte string using a software implementation.
209 The byte string is converted to a 64-bit integer using big endian byte order.
210 @param[in,out] crc crc32 checksum so far when this function is called,
211 when the function ends it will contain the new checksum
212 @param[in,out] data data to be checksummed, the pointer will be advanced
213 with 8 bytes
214 @param[in,out] len remaining bytes, it will be decremented with 8 */
215 static inline void crc32_64_legacy_big_endian(uint32_t *crc, const byte **data,
216 size_t *len) {
217 uint64_t data_int = *reinterpret_cast<const uint64_t *>(*data);
218
219 #ifndef WORDS_BIGENDIAN
220 data_int = swap_byteorder(data_int);
221 #endif /* !WORDS_BIGENDIAN */
222
223 *crc = crc32_64_low(*crc, data_int);
224
225 *data += 8;
226 *len -= 8;
227 }
228
229 /** Calculates CRC32 in software, without using CPU instructions.
230 @param[in] buf data over which to calculate CRC32
231 @param[in] len data length
232 @return CRC-32C (polynomial 0x11EDC6F41) */
233 template <void crc32_64(uint32_t *crc, const byte **data, size_t *len)>
234 uint32_t crc32_processing_64bit_chunks(const byte *buf, size_t len) {
235 uint32_t crc = 0xFFFFFFFFU;
236
237 ut_ad(crc32_slice8_table_initialized);
238
239 /* Calculate byte-by-byte up to an 8-byte aligned address. After
240 this consume the input 8-bytes at a time. */
241 while (len > 0 && (reinterpret_cast<uintptr_t>(buf) & 7) != 0) {
242 crc32_8(&crc, &buf, &len);
243 }
244
245 while (len >= 128) {
246 /* This call is repeated 16 times. 16 * 8 = 128. */
247 crc32_64(&crc, &buf, &len);
248 crc32_64(&crc, &buf, &len);
249 crc32_64(&crc, &buf, &len);
250 crc32_64(&crc, &buf, &len);
251 crc32_64(&crc, &buf, &len);
252 crc32_64(&crc, &buf, &len);
253 crc32_64(&crc, &buf, &len);
254 crc32_64(&crc, &buf, &len);
255 crc32_64(&crc, &buf, &len);
256 crc32_64(&crc, &buf, &len);
257 crc32_64(&crc, &buf, &len);
258 crc32_64(&crc, &buf, &len);
259 crc32_64(&crc, &buf, &len);
260 crc32_64(&crc, &buf, &len);
261 crc32_64(&crc, &buf, &len);
262 crc32_64(&crc, &buf, &len);
263 }
264
265 while (len >= 8) {
266 crc32_64(&crc, &buf, &len);
267 }
268
269 while (len > 0) {
270 crc32_8(&crc, &buf, &len);
271 }
272
273 return (~crc);
274 }
275 /** Computes CRC32-C hash not using any hardware acceleration.
276 It's non-static so it can be unit-tested, but otherwise should not be used
277 directly, and thus is not exposed in the header file - use ut_crc32 to benefit
278 from hardware acceleration available.
279 @param[in] buf data over which to calculate CRC32
280 @param[in] len data length
281 @return CRC-32C (polynomial 0x11EDC6F41) */
282 uint32_t crc32(const byte *buf, size_t len) {
283 return crc32_processing_64bit_chunks<crc32_64>(buf, len);
284 }
285 } /* namespace software */
286
287 uint32_t ut_crc32_legacy_big_endian(const byte *buf, size_t len) {
288 return software::crc32_processing_64bit_chunks<
289 software::crc32_64_legacy_big_endian>(buf, len);
290 }
291
292 #ifndef CRC32_DEFAULT
293
294 namespace hardware {
295
296 #ifdef CRC32_x86_64
297 /** Executes cpuid assembly instruction and returns the ecx register's value.
298 @return ecx value produced by cpuid */
299 static inline uint32_t get_cpuid_ecx();
300 #endif /* CRC32_x86_64 */
301
302 #ifdef CRC32_x86_64_WIN
303 static inline uint32_t get_cpuid_ecx() {
304 int cpu_info[4] = {-1, -1, -1, -1};
305 __cpuid(cpu_info, 1 /* function 1 */);
306 return static_cast<uint32_t>(cpu_info[2]);
307 }
308 #endif /* CRC32_x86_64_WIN */
309
310 #ifdef CRC32_x86_64_DEFAULT
311 static inline uint32_t get_cpuid_ecx() {
312 uint32_t features_ecx;
313 asm("cpuid" : "=c"(features_ecx) : "a"(1) : "ebx", "edx");
314 return features_ecx;
315 }
316 #endif /* CRC32_x86_64_DEFAULT */
317
318 /** Checks if hardware accelerated crc32 instructions are available to this
319 process right now. */
320 bool can_use_crc32();
321 /** Checks if hardware accelerated polynomial multiplication instructions are
322 available to this process right now. */
323 bool can_use_poly_mul();
324
325 #ifdef CRC32_x86_64
326 bool can_use_crc32() { return get_cpuid_ecx() & (1U << 20); }
327 bool can_use_poly_mul() { return get_cpuid_ecx() & (1U << 1); }
328 #endif /* CRC32_x86_64 */
329
330 #ifdef CRC32_ARM64_APPLE
331 bool can_use_crc32() { return true; }
332 bool can_use_poly_mul() { return true; }
333 #endif /* CRC32_ARM64_APPLE */
334
335 #ifdef CRC32_ARM64_DEFAULT
336 bool can_use_crc32() { return getauxval(AT_HWCAP) & HWCAP_CRC32; }
337 bool can_use_poly_mul() { return getauxval(AT_HWCAP) & HWCAP_PMULL; }
338 #endif /* CRC32_ARM64_DEFAULT */
339
340 /** A helper template to statically unroll a loop with a fixed number of
341 iterations, where the iteration number itself is constexpr. So, instead of:
342
343 Something::template run<0>(a,b);
344 Something::template run<1>(a,b);
345 Something::template run<2>(a,b);
346
347 you can write:
348
349 Loop<3>::template run<Something>(a, b);
350 */
351 template <size_t iterations>
352 struct Loop {
353 template <typename Step_executor, typename... Args>
354 static void run(Args &&...args) {
355 Loop<iterations - 1>::template run<Step_executor, Args...>(
356 std::forward<Args>(args)...);
357 Step_executor::template run<iterations - 1>(std::forward<Args>(args)...);
358 }
359 };
360 template <>
361 struct Loop<0> {
362 template <typename Step_executor, typename... Args>
363 static void run(Args &&...) {}
364 };
365
366 /** Computes x^(len*8) modulo CRC32-C polynomial, which is useful, when you need
367 to conceptually append len bytes of zeros to already computed hash.
368 @param[in] len The value of len in the x^(len*8) mod CRC32-C
369 @return the rest of x^(len*8) mod CRC32-C, with the most significant coefficient
370 of the resulting rest - the one which is for x^31 - stored as the most
371 significant bit of the uint32_t (the one at 1U<<31) */
372 constexpr uint32_t compute_x_to_8len(size_t len) {
373 // The x^(len*8) mod CRC32 polynomial depends on len only.
374 uint32_t x_to_8len = 1;
375 // push len bytes worth of zeros
376 for (size_t i = 0; i < len * 8; ++i) {
377 const bool will_wrap = x_to_8len >> 31 & 1;
378 x_to_8len <<= 1;
379 if (will_wrap) x_to_8len ^= CRC32C_POLYNOMIAL;
380 }
381 return x_to_8len;
382 }
383
384 /** Produces a 64-bit result by moving i-th bit of 32-bit input to the
385 32-i-th position (zeroing the other bits). Please note that in particular this
386 moves 0-th bit to 32-nd, and 31-st bit to 1-st, so the range in which data
387 resides is not only mirrored, but also shifted one bit. Such operation is useful
388 for implementing polynomial multiplication when one of the operands is given in
389 reverse and we need the result reversed, too (as is the case in CRC32-C):
390 rev(w * v) = rev(w)*flip_at_32(v)
391 proof:
392 rev(w * v)[i] = (w * v)[63-i] = sum(0<=j<=31){w[j]*v[63-i-j]} =
393 sum(0<=j<=31){rev(w)[31-j]*v[63-i-j]} =
394 sum(0<=j<=31){rev(w)[31-j]*flip_at_32(v)[32-63+i+j]} =
395 sum(0<=j<=31){rev(w)[31-j]*flip_at_32(v)[i-(j-31)]} =
396 sum(0<=j<=31){rev(w)[j]*flip_at_32(v)[i-j]} =
397 rev(w)*flip_at_32(v)[i]
398 So, for example, if crc32=rev(w) is the variable storing the CRC32-C hash of a
399 buffer, and you want to conceptually append len bytes of zeros to it, then you
400 can precompute v = compute_x_to_8len(len), and are interested in rev(w*v), which
401 you can achieve by crc32 * flip_at_32(compute_x_to_8len(len)).
402 @param[in] w The input 32-bit polynomial
403 @return The polynomial flipped and shifted, so that i-th bit becomes 32-i-th. */
404 constexpr uint64_t flip_at_32(uint32_t w) {
405 uint64_t f{0};
406 for (int i = 0; i < 32; ++i) {
407 if (((w >> i) & 1)) {
408 f ^= uint64_t{1} << (32 - i);
409 }
410 }
411 return f;
412 }
413
414 /** The collection of functions implementing hardware accelerated updating of
415 CRC32-C hash by processing a few (1,2,4 or 8) bytes of input. They are grouped
416 together in a type, so it's easier to swap their implementation by providing
417 algo_to_use template argument to higher level functions. */
418 struct crc32_impl {
419 static inline uint32_t update(uint32_t crc, unsigned char data);
420 static inline uint32_t update(uint32_t crc, uint16_t data);
421 static inline uint32_t update(uint32_t crc, uint32_t data);
422 static inline uint64_t update(uint64_t crc, uint64_t data);
423 };
424
425 #ifdef CRC32_x86_64
426 MY_ATTRIBUTE((target("sse4.2")))
427 uint32_t crc32_impl::update(uint32_t crc, unsigned char data) {
428 return _mm_crc32_u8(crc, data);
429 }
430 MY_ATTRIBUTE((target("sse4.2")))
431 uint32_t crc32_impl::update(uint32_t crc, uint16_t data) {
432 return _mm_crc32_u16(crc, data);
433 }
434 MY_ATTRIBUTE((target("sse4.2")))
435 uint32_t crc32_impl::update(uint32_t crc, uint32_t data) {
436 return _mm_crc32_u32(crc, data);
437 }
438 MY_ATTRIBUTE((target("sse4.2")))
439 uint64_t crc32_impl::update(uint64_t crc, uint64_t data) {
440 return _mm_crc32_u64(crc, data);
441 }
442 #endif /* CRC32_x86_64 */
443
444 #ifdef CRC32_ARM64
445 #ifdef CRC32_ARM64_DEFAULT
446 MY_ATTRIBUTE((target("+crc")))
447 #endif /* CRC32_ARM64_DEFAULT */
448 uint32_t crc32_impl::update(uint32_t crc, unsigned char data) {
449 return __crc32cb(crc, data);
450 }
451 #ifdef CRC32_ARM64_DEFAULT
452 MY_ATTRIBUTE((target("+crc")))
453 #endif /* CRC32_ARM64_DEFAULT */
454 uint32_t crc32_impl::update(uint32_t crc, uint16_t data) {
455 return __crc32ch(crc, data);
456 }
457 #ifdef CRC32_ARM64_DEFAULT
458 MY_ATTRIBUTE((target("+crc")))
459 #endif /* CRC32_ARM64_DEFAULT */
460 uint32_t crc32_impl::update(uint32_t crc, uint32_t data) {
461 return __crc32cw(crc, data);
462 }
463 #ifdef CRC32_ARM64_DEFAULT
464 MY_ATTRIBUTE((target("+crc")))
465 #endif /* CRC32_ARM64_DEFAULT */
466 uint64_t crc32_impl::update(uint64_t crc, uint64_t data) {
467 return (uint64_t)__crc32cd((uint32_t)crc, data);
468 }
469 #endif /* CRC32_ARM64 */
470
471 /** Implementation of polynomial_mul_rev<w>(rev_u) function which uses hardware
472 accelerated polynomial multiplication to compute rev(w*u), where rev_u=rev(u).
473 This is accomplished by using rev_u * flip_at_32(w), @see flip_at_32 for
474 explanation why it works and why this is useful. */
475 struct use_pclmul : crc32_impl {
476 template <uint32_t w>
477 inline static uint64_t polynomial_mul_rev(uint32_t rev_u);
478 };
479 #ifdef CRC32_x86_64
480 template <uint32_t w>
481 MY_ATTRIBUTE((target("sse4.2,pclmul")))
482 uint64_t use_pclmul::polynomial_mul_rev(uint32_t rev_u) {
483 constexpr uint64_t flipped_w = flip_at_32(w);
484 return _mm_cvtsi128_si64(_mm_clmulepi64_si128(
485 _mm_set_epi64x(0, rev_u), _mm_set_epi64x(0, flipped_w), 0x00));
486 }
487 #endif /* CRC32_x86_64 */
488
489 #ifdef CRC32_ARM64
490 /** This function performs just a "type casts" from uint64_t to poly64_t.
491 @param[in] w The 64 coefficients of the polynomial
492 @return the polynomial w(x) = sum_{i=0}^{63} { (w&(1ULL<<i)) * x^{i} }
493 */
494 static inline poly64_t uint64_t_to_poly_64_t(uint64_t w) {
495 /* This should compile down to nothing */
496 return vget_lane_p64(vcreate_p64(w), 0);
497 }
498 /** This function takes a polynomial and extracts the 64 least significant
499 coefficients.
500 @param[in] w The polynomial w(x) = sum_{i=0}^{127} { a_i * x^{i} }
501 @return The lowest 64 coefficients, i.e. (result & (1ULL<<i)) == a_i for 0<=i<64
502 */
503 static inline uint64_t less_significant_half_of_poly128_t_to_uint64_t(
504 poly128_t w) {
505 /* This should compile down to just a single mov */
506 return vgetq_lane_u64(vreinterpretq_u64_p128(w), 0);
507 }
508 template <uint32_t w>
509 #ifdef CRC32_ARM64_DEFAULT
510 MY_ATTRIBUTE((target("+crypto")))
511 #endif /* CRC32_ARM64_DEFAULT */
512 uint64_t use_pclmul::polynomial_mul_rev(uint32_t rev_u) {
513 constexpr uint64_t flipped_w = flip_at_32(w);
514 return less_significant_half_of_poly128_t_to_uint64_t(vmull_p64(
515 uint64_t_to_poly_64_t(flipped_w), uint64_t_to_poly_64_t(rev_u)));
516 }
517 #endif /* CRC32_ARM64 */
518
519 /** Implementation of polynomial_mul_rev<w>(rev_u) function which uses a simple
520 loop over i: if(w>>i&1)result^=rev_u<<(32-i), which is equivalent to
521 w * flip_at_32(rev_u), which in turn is equivalent to rev(rev(w) * rev_u),
522 @see flip_at_32 for explanation why this holds,
523 @see use_pclmul for explanation of what polynomial_mul_rev is computing.
524 This implementation is to be used when hardware accelerated polynomial
525 multiplication is not available. It tries to unroll the simple loop, so just
526 the few xors and shifts for non-zero bits of w are emitted. */
527 struct use_unrolled_loop_poly_mul : crc32_impl {
528 template <uint32_t x_to_len_8>
529 struct Polynomial_mul_rev_step_executor {
530 template <size_t i>
531 static void run(uint64_t &acc, const uint32_t hash_1 [[maybe_unused]]) {
532 if constexpr (x_to_len_8 >> ((uint32_t)i) & 1) {
533 acc ^= uint64_t{hash_1} << (32 - i);
534 }
535 }
536 };
537 template <uint32_t w>
538 inline static uint64_t polynomial_mul_rev(uint32_t rev_u) {
539 uint64_t rev_w_times_u{0};
540 Loop<32>::run<Polynomial_mul_rev_step_executor<w>>(rev_w_times_u, rev_u);
541 return rev_w_times_u;
542 }
543 };
544
545 /** Rolls the crc forward by len bytes, that is updates it as if 8*len zero bits
546 were processed.
547 @param[in] crc initial value of the hash
548 @return Updated value of the hash: rev(rev(crc)*(x^{8*len} mod CRC32-C)) */
549 template <size_t len, typename algo_to_use>
550 inline static uint64_t roll(uint32_t crc) {
551 return algo_to_use::template polynomial_mul_rev<compute_x_to_8len(len)>(crc);
552 }
553
554 /** Takes a 64-bit reversed representation of a polynomial, and computes the
555 32-bit reversed representation of it modulo CRC32-C.
556 @param[in] big The 64-bit representation of polynomial w, with the most
557 significant coefficient (the one for x^63) stored at least
558 significant bit (the one at 1<<0).
559 @return The 32-bit representation of w mod CRC-32, in which the most significant
560 coefficient (the one for x^31) stored at least significant bit
561 (the one at 1<<0). */
562 template <typename algo_to_use>
563 static inline uint32_t fold_64_to_32(uint64_t big) {
564 /* crc is stored in bit-reversed format, so "significant part of uint64_t" is
565 actually the least significant part of the polynomial, and the "insignificant
566 part of uint64_t" are the coefficients of highest degrees for which we need to
567 compute the rest mod crc32-c polynomial. */
568 return algo_to_use::update((uint32_t)big, uint32_t{0}) ^ (big >> 32);
569 }
570
571 /** The body of unrolled loop used to process slices in parallel, which in i-th
572 iteration processes 8 bytes from the i-th slice of data, where each slice has
573 slice_len bytes. */
574 template <typename algo_to_use, size_t slice_len>
575 struct Update_step_executor {
576 template <size_t i>
577 static void run(uint64_t *crc, const uint64_t *data64) {
578 crc[i] = algo_to_use::update(crc[i], *(data64 + i * (slice_len / 8)));
579 }
580 };
581
582 /** The body of unrolled loop used to combine partial results from each slice
583 into the final hash of whole chunk, which in i-th iteration takes the crc of
584 i-th slice and "rolls it forward" by virtually processing as many zeros as there
585 are from the end of the i-th slice to the end of the chunk. */
586 template <typename algo_to_use, size_t slice_len, size_t slices_count>
587 struct Combination_step_executor {
588 template <size_t i>
589 static void run(uint64_t &combined, const uint64_t *crc) {
590 combined ^= roll<slice_len *(slices_count - 1 - i), algo_to_use>(crc[i]);
591 }
592 };
593
594 /** Updates the crc checksum by processing slices_count*slice_len bytes of data.
595 The chunk is processed as slice_count independent slices of length slice_len,
596 and the results are combined together at the end to compute correct result.
597 @param[in] crc0 initial value of the hash
598 @param[in] data data over which to calculate CRC32-C
599 @return The value of _crc updated by processing the range
600 data[0]...data[slices_count*slice_len-1]. */
601 template <size_t slice_len, size_t slices_count, typename algo_to_use>
602 static inline uint32_t consume_chunk(uint32_t crc0, const unsigned char *data) {
603 static_assert(slices_count > 0, "there must be at least one slice");
604 const uint64_t *data64 = (const uint64_t *)data;
605 /* crc[i] is the hash for i-th slice, data[i*slice_len...(i+1)*slice_len)
606 where the initial value for each crc[i] is zero, except crc[0] for which we
607 use the initial value crc0 passed in by the caller. */
608 uint64_t crc[slices_count]{crc0};
609 /* Each iteration of the for() loop will eat 8 bytes (single uint64_t) from
610 each slice. */
611 static_assert(
612 slice_len % sizeof(uint64_t) == 0,
613 "we must be able to process a slice efficiently using 8-byte updates");
614 constexpr auto iters = slice_len / sizeof(uint64_t);
615 for (size_t i = 0; i < iters; ++i) {
616 Loop<slices_count>::template run<
617 Update_step_executor<algo_to_use, slice_len>>(crc, data64);
618 ++data64;
619 }
620 /* combined_crc = sum crc[i]*x^{slices_count-i-1} mod CRC32-C */
621 uint64_t combined_crc{0};
622 /* This ugly if is here to ensure that fold_64_to_32 is called just once, as
623 opposed to being done as part of combining each individual slice, which would
624 also be correct, but would mean that CPU can't process roll()s in parallel.
625 That is:
626 combined ^= roll<"n-1 slices">(crc[0])
627 combined ^= roll<"n-2 slices">(crc[1])
628 ...
629 combined ^= roll<1>(crc[n-2])
630 return fold_64_to_32(combined) ^ crc[n-1]
631 is faster than:
632 crc[1] ^= fold_64_to_32(roll<"n-1 slices">(crc[0]))
633 crc[2] ^= fold_64_to_32(roll<"n-1 slices">(crc[1]))
634 ...
635 crc[n-1] ^= fold_64_to_32(roll<1>(crc[n-2]))
636 return crc[n-1]
637 as the inputs to roll()s are independent, but now fold_64_to_32 is only needed
638 conditionally, when slices_count > 1. */
639 if constexpr (1 < slices_count) {
640 Loop<slices_count - 1>::template run<
641 Combination_step_executor<algo_to_use, slice_len, slices_count>>(
642 combined_crc, crc);
643 combined_crc = fold_64_to_32<algo_to_use>(combined_crc);
644 }
645 return combined_crc ^ crc[slices_count - 1];
646 }
647
648 /** Updates the crc checksum by processing at most len bytes of data.
649 The data is consumed in chunks of size slice_len*slices_count, and stops when
650 no more full chunks can be fit into len bytes.
651 Each chunk is processed as slice_count independent slices of length slice_len,
652 and the results are combined together at the end to compute correct result.
653 @param[in,out] crc initial value of the hash. Updated by this function by
654 processing data[0]...data[B*(slice_len * slices_count)],
655 where B = floor(len / (slice_len * slices_count)).
656 @param[in,out] data data over which to calculate CRC32-C. Advanced by this
657 function to point to unprocessed part of the buffer.
658 @param[in,out] len data length to be processed. Updated by this function
659 to be len % (slice_len * slices_count). */
660 template <size_t slice_len, size_t slices_count, typename algo_to_use>
661 static inline void consume_chunks(uint32_t &crc, const byte *&data,
662 size_t &len) {
663 while (len >= slice_len * slices_count) {
664 crc = consume_chunk<slice_len, slices_count, algo_to_use>(crc, data);
665 len -= slice_len * slices_count;
666 data += slice_len * slices_count;
667 }
668 }
669 /** Updates the crc checksum by processing Chunk (1,2 or 4 bytes) of data,
670 but only when the len of the data provided, when decomposed into powers of two,
671 has a Chunk of this length. This is used to process the prefix of the buffer to
672 get to the position which is aligned mod 8, and to process the remaining suffix
673 which starts at position aligned mod 8, but has less than 8 bytes.
674 @param[in,out] crc initial value of the hash. Updated by this function by
675 processing Chunk pointed by data.
676 @param[in,out] data data over which to calculate CRC32-C. Advanced by this
677 function to point to unprocessed part of the buffer.
678 @param[in,out] len data length, allowed to be processed. */
679 template <typename Chunk, typename algo_to_use>
680 static inline void consume_pow2(uint32_t &crc, const byte *&data, size_t len) {
681 if (len & sizeof(Chunk)) {
682 crc = algo_to_use::update(crc, *(Chunk *)data);
683 data += sizeof(Chunk);
684 }
685 }
686 /** The hardware accelerated implementation of CRC32-C exploiting within-core
687 parallelism on reordering processors, by consuming the data in large chunks
688 split into 3 independent slices each. It's optimized for handling buffers of
689 length typical for 16kb pages and redo log blocks, but it works correctly for
690 any len and alignment.
691 @param[in] crc initial value of the hash (0 for first block, or the
692 result of CRC32-C for the data processed so far)
693 @param[in] data data over which to calculate CRC32-C
694 @param[in] len data length
695 @return CRC-32C (polynomial 0x11EDC6F41) */
696 template <typename algo_to_use>
697 static uint32_t crc32(uint32_t crc, const byte *data, size_t len) {
698 crc = ~crc;
699 if (8 <= len) {
700 /* For performance, the main loop will operate on uint64_t[].
701 On some platforms unaligned reads are not allowed, on others they are
702 slower, so we start by consuming the unaligned prefix of the data. */
703 const size_t prefix_len = (8 - reinterpret_cast<uintptr_t>(data)) & 7;
704 /* data address may be unaligned, so we read just one byte if it's odd */
705 consume_pow2<byte, algo_to_use>(crc, data, prefix_len);
706 /* data address is now aligned mod 2, but may be unaligned mod 4*/
707 consume_pow2<uint16_t, algo_to_use>(crc, data, prefix_len);
708 /* data address is now aligned mod 4, but may be unaligned mod 8 */
709 consume_pow2<uint32_t, algo_to_use>(crc, data, prefix_len);
710 /* data is now aligned mod 8 */
711 len -= prefix_len;
712 /* The suffix_len will be needed later, but we can compute it here already,
713 as len will only be modified by subtracting multiples of 8, and hopefully,
714 learning suffix_len sooner will make it easier for branch predictor later.*/
715 const size_t suffix_len = len & 7;
716 /* A typical page is 16kb, but the part for which we compute crc32 is a bit
717 shorter, thus 5440*3 is the largest multiple of 8*3 that fits. For pages
718 larger than 16kb, there's not much gain from handling them specially. */
719 consume_chunks<5440, 3, algo_to_use>(crc, data, len);
720 /* A typical redo log block is 0.5kb, but 168*3 is the largest multiple of
721 8*3 which fits in the part for which we compute crc32. */
722 consume_chunks<168, 3, algo_to_use>(crc, data, len);
723 /* In general there can be some left-over (smaller than 168*3) which we
724 consume 8*1 bytes at a time. */
725 consume_chunks<8, 1, algo_to_use>(crc, data, len);
726 /* Finally, there might be unprocessed suffix_len < 8, which we deal with
727 minimal number of computations caring about proper alignment. */
728 consume_pow2<uint32_t, algo_to_use>(crc, data, suffix_len);
729 consume_pow2<uint16_t, algo_to_use>(crc, data, suffix_len);
730 consume_pow2<byte, algo_to_use>(crc, data, suffix_len);
731 } else {
732 while (len--) {
733 crc = algo_to_use::update(crc, *data++);
734 }
735 }
736 return ~crc;
737 }
738
739 /** The specialization of crc32<> template for use_pclmul and 0 as initial
740 value of the hash. Used on platforms which support hardware accelerated
741 polynomial multiplication.
742 It's non-static so it can be unit-tested.
743 @param[in] data data over which to calculate CRC32-C
744 @param[in] len data length
745 @return CRC-32C (polynomial 0x11EDC6F41) */
746 #ifdef CRC32_x86_64_DEFAULT
747 MY_ATTRIBUTE((target("sse4.2,pclmul"), flatten))
748 #endif /* CRC32_x86_64_DEFAULT */
749 #ifdef CRC32_ARM64_APPLE
750 MY_ATTRIBUTE((flatten))
751 #endif /* CRC32_ARM64_APPLE */
752 #ifdef CRC32_ARM64_DEFAULT
753 MY_ATTRIBUTE((target("+crc+crypto"), flatten))
754 #endif /* CRC32_ARM64_DEFAULT */
755 uint32_t crc32_using_pclmul(const byte *data, size_t len) {
756 return crc32<use_pclmul>(0, data, len);
757 }
758
759 /** The specialization of crc32<> template for use_unrolled_loop_poly_mul and 0
760 as initial value of the hash. Used on platforms which do not support hardware
761 accelerated polynomial multiplication.
762 It's non-static so it can be unit-tested.
763 @param[in] data data over which to calculate CRC32-C
764 @param[in] len data length
765 @return CRC-32C (polynomial 0x11EDC6F41) */
766 #ifdef CRC32_x86_64_DEFAULT
767 MY_ATTRIBUTE((target("sse4.2"), flatten))
768 #endif /* CRC32_x86_64_DEFAULT */
769 #ifdef CRC32_ARM64_APPLE
770 MY_ATTRIBUTE((flatten))
771 #endif /* CRC32_ARM64_APPLE */
772 #ifdef CRC32_ARM64_DEFAULT
773 MY_ATTRIBUTE((target("+crc"), flatten))
774 #endif /* CRC32_ARM64_DEFAULT */
775 uint32_t crc32_using_unrolled_loop_poly_mul(const byte *data, size_t len) {
776 return crc32<use_unrolled_loop_poly_mul>(0, data, len);
777 }
778
779 } /* namespace hardware */
780
781 #endif /* !CRC32_DEFAULT */
782
783 /** Initializes the data structures used by ut_crc32*(). Does not do any
784 allocations, would not hurt if called twice, but would be pointless. */
785 void ut_crc32_init() {
786 software::crc32_slice8_table_init();
787 #ifndef CRC32_DEFAULT
788
789 #ifdef WORDS_BIGENDIAN
790 #error The current crc32 implementation assumes that on big-endian platforms we\
791 will use the default software implementation, because current hardware\
792 implementation supports only little-endian platforms
793 #endif /* WORDS_BIGENDIAN */
794
795 ut_crc32_cpu_enabled = hardware::can_use_crc32();
796 ut_poly_mul_cpu_enabled = hardware::can_use_poly_mul();
797 if (ut_crc32_cpu_enabled) {
798 if (ut_poly_mul_cpu_enabled) {
799 ut_crc32 = hardware::crc32_using_pclmul;
800 } else {
801 ut_crc32 = hardware::crc32_using_unrolled_loop_poly_mul;
802 }
803 return;
804 }
805 #endif /* !CRC32_DEFAULT */
806 ut_crc32 = software::crc32;
807 }