xref: /freebsd/contrib/xz/src/liblzma/check/crc64_fast.c (revision c07d6445eb89d9dd3950361b065b7bd110e3a043)
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       crc64.c
4 /// \brief      CRC64 calculation
5 ///
6 /// There are two methods in this file. crc64_generic uses the
7 /// the slice-by-four algorithm. This is the same idea that is
8 /// used in crc32_fast.c, but for CRC64 we use only four tables
9 /// instead of eight to avoid increasing CPU cache usage.
10 ///
11 /// crc64_clmul uses 32/64-bit x86 SSSE3, SSE4.1, and CLMUL instructions.
12 /// It was derived from
13 /// https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf
14 /// and the public domain code from https://github.com/rawrunprotected/crc
15 /// (URLs were checked on 2022-11-07).
16 ///
17 /// FIXME: Builds for 32-bit x86 use crc64_x86.S by default instead
18 /// of this file and thus CLMUL version isn't available on 32-bit x86
19 /// unless configured with --disable-assembler. Even then the lookup table
20 /// isn't omitted in crc64_table.c since it doesn't know that assembly
21 /// code has been disabled.
22 //
23 //  Authors:    Lasse Collin
24 //              Ilya Kurdyukov
25 //
26 //  This file has been put into the public domain.
27 //  You can do whatever you want with this file.
28 //
29 ///////////////////////////////////////////////////////////////////////////////
30 
31 #include "check.h"
32 
33 #undef CRC_GENERIC
34 #undef CRC_CLMUL
35 #undef CRC_USE_GENERIC_FOR_SMALL_INPUTS
36 
37 // If CLMUL cannot be used then only the generic slice-by-four is built.
38 #if !defined(HAVE_USABLE_CLMUL)
39 #	define CRC_GENERIC 1
40 
41 // If CLMUL is allowed unconditionally in the compiler options then the
42 // generic version can be omitted. Note that this doesn't work with MSVC
43 // as I don't know how to detect the features here.
44 //
45 // NOTE: Keep this this in sync with crc64_table.c.
46 #elif (defined(__SSSE3__) && defined(__SSE4_1__) && defined(__PCLMUL__)) \
47 		|| (defined(__e2k__) && __iset__ >= 6)
48 #	define CRC_CLMUL 1
49 
50 // Otherwise build both and detect at runtime which version to use.
51 #else
52 #	define CRC_GENERIC 1
53 #	define CRC_CLMUL 1
54 
55 /*
56 	// The generic code is much faster with 1-8-byte inputs and has
57 	// similar performance up to 16 bytes  at least in microbenchmarks
58 	// (it depends on input buffer alignment too). If both versions are
59 	// built, this #define will use the generic version for inputs up to
60 	// 16 bytes and CLMUL for bigger inputs. It saves a little in code
61 	// size since the special cases for 0-16-byte inputs will be omitted
62 	// from the CLMUL code.
63 #	define CRC_USE_GENERIC_FOR_SMALL_INPUTS 1
64 */
65 
66 #	if defined(_MSC_VER)
67 #		include <intrin.h>
68 #	elif defined(HAVE_CPUID_H)
69 #		include <cpuid.h>
70 #	endif
71 #endif
72 
73 
74 /////////////////////////////////
75 // Generic slice-by-four CRC64 //
76 /////////////////////////////////
77 
78 #ifdef CRC_GENERIC
79 
80 #include "crc_macros.h"
81 
82 
83 #ifdef WORDS_BIGENDIAN
84 #	define A1(x) ((x) >> 56)
85 #else
86 #	define A1 A
87 #endif
88 
89 
90 // See the comments in crc32_fast.c. They aren't duplicated here.
91 static uint64_t
92 crc64_generic(const uint8_t *buf, size_t size, uint64_t crc)
93 {
94 	crc = ~crc;
95 
96 #ifdef WORDS_BIGENDIAN
97 	crc = bswap64(crc);
98 #endif
99 
100 	if (size > 4) {
101 		while ((uintptr_t)(buf) & 3) {
102 			crc = lzma_crc64_table[0][*buf++ ^ A1(crc)] ^ S8(crc);
103 			--size;
104 		}
105 
106 		const uint8_t *const limit = buf + (size & ~(size_t)(3));
107 		size &= (size_t)(3);
108 
109 		while (buf < limit) {
110 #ifdef WORDS_BIGENDIAN
111 			const uint32_t tmp = (uint32_t)(crc >> 32)
112 					^ aligned_read32ne(buf);
113 #else
114 			const uint32_t tmp = (uint32_t)crc
115 					^ aligned_read32ne(buf);
116 #endif
117 			buf += 4;
118 
119 			crc = lzma_crc64_table[3][A(tmp)]
120 			    ^ lzma_crc64_table[2][B(tmp)]
121 			    ^ S32(crc)
122 			    ^ lzma_crc64_table[1][C(tmp)]
123 			    ^ lzma_crc64_table[0][D(tmp)];
124 		}
125 	}
126 
127 	while (size-- != 0)
128 		crc = lzma_crc64_table[0][*buf++ ^ A1(crc)] ^ S8(crc);
129 
130 #ifdef WORDS_BIGENDIAN
131 	crc = bswap64(crc);
132 #endif
133 
134 	return ~crc;
135 }
136 #endif
137 
138 
139 /////////////////////
140 // x86 CLMUL CRC64 //
141 /////////////////////
142 
143 #ifdef CRC_CLMUL
144 
145 #include <immintrin.h>
146 
147 
148 /*
149 // These functions were used to generate the constants
150 // at the top of crc64_clmul().
151 static uint64_t
152 calc_lo(uint64_t poly)
153 {
154 	uint64_t a = poly;
155 	uint64_t b = 0;
156 
157 	for (unsigned i = 0; i < 64; ++i) {
158 		b = (b >> 1) | (a << 63);
159 		a = (a >> 1) ^ (a & 1 ? poly : 0);
160 	}
161 
162 	return b;
163 }
164 
165 static uint64_t
166 calc_hi(uint64_t poly, uint64_t a)
167 {
168 	for (unsigned i = 0; i < 64; ++i)
169 		a = (a >> 1) ^ (a & 1 ? poly : 0);
170 
171 	return a;
172 }
173 */
174 
175 
176 #define MASK_L(in, mask, r) \
177 	r = _mm_shuffle_epi8(in, mask)
178 
179 #define MASK_H(in, mask, r) \
180 	r = _mm_shuffle_epi8(in, _mm_xor_si128(mask, vsign))
181 
182 #define MASK_LH(in, mask, low, high) \
183 	MASK_L(in, mask, low); \
184 	MASK_H(in, mask, high)
185 
186 
187 // EDG-based compilers (Intel's classic compiler and compiler for E2K) can
188 // define __GNUC__ but the attribute must not be used with them.
189 // The new Clang-based ICX needs the attribute.
190 //
191 // NOTE: Build systems check for this too, keep them in sync with this.
192 #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
193 __attribute__((__target__("ssse3,sse4.1,pclmul")))
194 #endif
195 static uint64_t
196 crc64_clmul(const uint8_t *buf, size_t size, uint64_t crc)
197 {
198 	// The prototypes of the intrinsics use signed types while most of
199 	// the values are treated as unsigned here. These warnings in this
200 	// function have been checked and found to be harmless so silence them.
201 #if TUKLIB_GNUC_REQ(4, 6) || defined(__clang__)
202 #	pragma GCC diagnostic push
203 #	pragma GCC diagnostic ignored "-Wsign-conversion"
204 #	pragma GCC diagnostic ignored "-Wconversion"
205 #endif
206 
207 #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
208 	// The code assumes that there is at least one byte of input.
209 	if (size == 0)
210 		return crc;
211 #endif
212 
213 	// const uint64_t poly = 0xc96c5795d7870f42; // CRC polynomial
214 	const uint64_t p  = 0x92d8af2baf0e1e85; // (poly << 1) | 1
215 	const uint64_t mu = 0x9c3e466c172963d5; // (calc_lo(poly) << 1) | 1
216 	const uint64_t k2 = 0xdabe95afc7875f40; // calc_hi(poly, 1)
217 	const uint64_t k1 = 0xe05dd497ca393ae4; // calc_hi(poly, k2)
218 	const __m128i vfold0 = _mm_set_epi64x(p, mu);
219 	const __m128i vfold1 = _mm_set_epi64x(k2, k1);
220 
221 	// Create a vector with 8-bit values 0 to 15. This is used to
222 	// construct control masks for _mm_blendv_epi8 and _mm_shuffle_epi8.
223 	const __m128i vramp = _mm_setr_epi32(
224 			0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c);
225 
226 	// This is used to inverse the control mask of _mm_shuffle_epi8
227 	// so that bytes that wouldn't be picked with the original mask
228 	// will be picked and vice versa.
229 	const __m128i vsign = _mm_set1_epi8(0x80);
230 
231 	// Memory addresses A to D and the distances between them:
232 	//
233 	//     A           B     C         D
234 	//     [skip_start][size][skip_end]
235 	//     [     size2      ]
236 	//
237 	// A and D are 16-byte aligned. B and C are 1-byte aligned.
238 	// skip_start and skip_end are 0-15 bytes. size is at least 1 byte.
239 	//
240 	// A = aligned_buf will initially point to this address.
241 	// B = The address pointed by the caller-supplied buf.
242 	// C = buf + size == aligned_buf + size2
243 	// D = buf + size + skip_end == aligned_buf + size2 + skip_end
244 	const size_t skip_start = (size_t)((uintptr_t)buf & 15);
245 	const size_t skip_end = (size_t)(-(uintptr_t)(buf + size) & 15);
246 	const __m128i *aligned_buf = (const __m128i *)(
247 			(uintptr_t)buf & ~(uintptr_t)15);
248 
249 	// If size2 <= 16 then the whole input fits into a single 16-byte
250 	// vector. If size2 > 16 then at least two 16-byte vectors must
251 	// be processed. If size2 > 16 && size <= 16 then there is only
252 	// one 16-byte vector's worth of input but it is unaligned in memory.
253 	//
254 	// NOTE: There is no integer overflow here if the arguments are valid.
255 	// If this overflowed, buf + size would too.
256 	size_t size2 = skip_start + size;
257 
258 	// Masks to be used with _mm_blendv_epi8 and _mm_shuffle_epi8:
259 	// The first skip_start or skip_end bytes in the vectors will have
260 	// the high bit (0x80) set. _mm_blendv_epi8 and _mm_shuffle_epi8
261 	// will produce zeros for these positions. (Bitwise-xor of these
262 	// masks with vsign will produce the opposite behavior.)
263 	const __m128i mask_start
264 			= _mm_sub_epi8(vramp, _mm_set1_epi8(skip_start));
265 	const __m128i mask_end = _mm_sub_epi8(vramp, _mm_set1_epi8(skip_end));
266 
267 	// Get the first 1-16 bytes into data0. If loading less than 16 bytes,
268 	// the bytes are loaded to the high bits of the vector and the least
269 	// significant positions are filled with zeros.
270 	const __m128i data0 = _mm_blendv_epi8(_mm_load_si128(aligned_buf),
271 			_mm_setzero_si128(), mask_start);
272 	++aligned_buf;
273 
274 #if defined(__i386__) || defined(_M_IX86)
275 	const __m128i initial_crc = _mm_set_epi64x(0, ~crc);
276 #else
277 	// GCC and Clang would produce good code with _mm_set_epi64x
278 	// but MSVC needs _mm_cvtsi64_si128 on x86-64.
279 	const __m128i initial_crc = _mm_cvtsi64_si128(~crc);
280 #endif
281 
282 	__m128i v0, v1, v2, v3;
283 
284 #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
285 	if (size <= 16) {
286 		// Right-shift initial_crc by 1-16 bytes based on "size"
287 		// and store the result in v1 (high bytes) and v0 (low bytes).
288 		//
289 		// NOTE: The highest 8 bytes of initial_crc are zeros so
290 		// v1 will be filled with zeros if size >= 8. The highest 8
291 		// bytes of v1 will always become zeros.
292 		//
293 		// [      v1      ][      v0      ]
294 		//  [ initial_crc  ]                  size == 1
295 		//   [ initial_crc  ]                 size == 2
296 		//                [ initial_crc  ]    size == 15
297 		//                 [ initial_crc  ]   size == 16 (all in v0)
298 		const __m128i mask_low = _mm_add_epi8(
299 				vramp, _mm_set1_epi8(size - 16));
300 		MASK_LH(initial_crc, mask_low, v0, v1);
301 
302 		if (size2 <= 16) {
303 			// There are 1-16 bytes of input and it is all
304 			// in data0. Copy the input bytes to v3. If there
305 			// are fewer than 16 bytes, the low bytes in v3
306 			// will be filled with zeros. That is, the input
307 			// bytes are stored to the same position as
308 			// (part of) initial_crc is in v0.
309 			MASK_L(data0, mask_end, v3);
310 		} else {
311 			// There are 2-16 bytes of input but not all bytes
312 			// are in data0.
313 			const __m128i data1 = _mm_load_si128(aligned_buf);
314 
315 			// Collect the 2-16 input bytes from data0 and data1
316 			// to v2 and v3, and bitwise-xor them with the
317 			// low bits of initial_crc in v0. Note that the
318 			// the second xor is below this else-block as it
319 			// is shared with the other branch.
320 			MASK_H(data0, mask_end, v2);
321 			MASK_L(data1, mask_end, v3);
322 			v0 = _mm_xor_si128(v0, v2);
323 		}
324 
325 		v0 = _mm_xor_si128(v0, v3);
326 		v1 = _mm_alignr_epi8(v1, v0, 8);
327 	} else
328 #endif
329 	{
330 		const __m128i data1 = _mm_load_si128(aligned_buf);
331 		MASK_LH(initial_crc, mask_start, v0, v1);
332 		v0 = _mm_xor_si128(v0, data0);
333 		v1 = _mm_xor_si128(v1, data1);
334 
335 #define FOLD \
336 	v1 = _mm_xor_si128(v1, _mm_clmulepi64_si128(v0, vfold1, 0x00)); \
337 	v0 = _mm_xor_si128(v1, _mm_clmulepi64_si128(v0, vfold1, 0x11));
338 
339 		while (size2 > 32) {
340 			++aligned_buf;
341 			size2 -= 16;
342 			FOLD
343 			v1 = _mm_load_si128(aligned_buf);
344 		}
345 
346 		if (size2 < 32) {
347 			MASK_H(v0, mask_end, v2);
348 			MASK_L(v0, mask_end, v0);
349 			MASK_L(v1, mask_end, v3);
350 			v1 = _mm_or_si128(v2, v3);
351 		}
352 
353 		FOLD
354 		v1 = _mm_srli_si128(v0, 8);
355 #undef FOLD
356 	}
357 
358 	v1 = _mm_xor_si128(_mm_clmulepi64_si128(v0, vfold1, 0x10), v1);
359 	v0 = _mm_clmulepi64_si128(v1, vfold0, 0x00);
360 	v2 = _mm_clmulepi64_si128(v0, vfold0, 0x10);
361 	v0 = _mm_xor_si128(_mm_xor_si128(v2, _mm_slli_si128(v0, 8)), v1);
362 
363 #if defined(__i386__) || defined(_M_IX86)
364 	return ~(((uint64_t)(uint32_t)_mm_extract_epi32(v0, 3) << 32) |
365 			(uint64_t)(uint32_t)_mm_extract_epi32(v0, 2));
366 #else
367 	return ~(uint64_t)_mm_extract_epi64(v0, 1);
368 #endif
369 
370 #if TUKLIB_GNUC_REQ(4, 6) || defined(__clang__)
371 #	pragma GCC diagnostic pop
372 #endif
373 }
374 #endif
375 
376 
377 ////////////////////////
378 // Detect CPU support //
379 ////////////////////////
380 
381 #if defined(CRC_GENERIC) && defined(CRC_CLMUL)
382 static inline bool
383 is_clmul_supported(void)
384 {
385 	int success = 1;
386 	uint32_t r[4]; // eax, ebx, ecx, edx
387 
388 #if defined(_MSC_VER)
389 	// This needs <intrin.h> with MSVC. ICC has it as a built-in
390 	// on all platforms.
391 	__cpuid(r, 1);
392 #elif defined(HAVE_CPUID_H)
393 	// Compared to just using __asm__ to run CPUID, this also checks
394 	// that CPUID is supported and saves and restores ebx as that is
395 	// needed with GCC < 5 with position-independent code (PIC).
396 	success = __get_cpuid(1, &r[0], &r[1], &r[2], &r[3]);
397 #else
398 	// Just a fallback that shouldn't be needed.
399 	__asm__("cpuid\n\t"
400 			: "=a"(r[0]), "=b"(r[1]), "=c"(r[2]), "=d"(r[3])
401 			: "a"(1), "c"(0));
402 #endif
403 
404 	// Returns true if these are supported:
405 	// CLMUL (bit 1 in ecx)
406 	// SSSE3 (bit 9 in ecx)
407 	// SSE4.1 (bit 19 in ecx)
408 	const uint32_t ecx_mask = (1 << 1) | (1 << 9) | (1 << 19);
409 	return success && (r[2] & ecx_mask) == ecx_mask;
410 
411 	// Alternative methods that weren't used:
412 	//   - ICC's _may_i_use_cpu_feature: the other methods should work too.
413 	//   - GCC >= 6 / Clang / ICX __builtin_cpu_supports("pclmul")
414 	//
415 	// CPUID decding is needed with MSVC anyway and older GCC. This keeps
416 	// the feature checks in the build system simpler too. The nice thing
417 	// about __builtin_cpu_supports would be that it generates very short
418 	// code as is it only reads a variable set at startup but a few bytes
419 	// doesn't matter here.
420 }
421 
422 
423 #ifdef HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR
424 #	define CRC64_FUNC_INIT
425 #	define CRC64_SET_FUNC_ATTR __attribute__((__constructor__))
426 #else
427 #	define CRC64_FUNC_INIT = &crc64_dispatch
428 #	define CRC64_SET_FUNC_ATTR
429 static uint64_t crc64_dispatch(const uint8_t *buf, size_t size, uint64_t crc);
430 #endif
431 
432 
433 // Pointer to the the selected CRC64 method.
434 static uint64_t (*crc64_func)(const uint8_t *buf, size_t size, uint64_t crc)
435 		CRC64_FUNC_INIT;
436 
437 
438 CRC64_SET_FUNC_ATTR
439 static void
440 crc64_set_func(void)
441 {
442 	crc64_func = is_clmul_supported() ? &crc64_clmul : &crc64_generic;
443 	return;
444 }
445 
446 
447 #ifndef HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR
448 static uint64_t
449 crc64_dispatch(const uint8_t *buf, size_t size, uint64_t crc)
450 {
451 	// When __attribute__((__constructor__)) isn't supported, set the
452 	// function pointer without any locking. If multiple threads run
453 	// the detection code in parallel, they will all end up setting
454 	// the pointer to the same value. This avoids the use of
455 	// mythread_once() on every call to lzma_crc64() but this likely
456 	// isn't strictly standards compliant. Let's change it if it breaks.
457 	crc64_set_func();
458 	return crc64_func(buf, size, crc);
459 }
460 #endif
461 #endif
462 
463 
464 extern LZMA_API(uint64_t)
465 lzma_crc64(const uint8_t *buf, size_t size, uint64_t crc)
466 {
467 #if defined(CRC_GENERIC) && defined(CRC_CLMUL)
468 	// If CLMUL is available, it is the best for non-tiny inputs,
469 	// being over twice as fast as the generic slice-by-four version.
470 	// However, for size <= 16 it's different. In the extreme case
471 	// of size == 1 the generic version can be five times faster.
472 	// At size >= 8 the CLMUL starts to become reasonable. It
473 	// varies depending on the alignment of buf too.
474 	//
475 	// The above doesn't include the overhead of mythread_once().
476 	// At least on x86-64 GNU/Linux, pthread_once() is very fast but
477 	// it still makes lzma_crc64(buf, 1, crc) 50-100 % slower. When
478 	// size reaches 12-16 bytes the overhead becomes negligible.
479 	//
480 	// So using the generic version for size <= 16 may give better
481 	// performance with tiny inputs but if such inputs happen rarely
482 	// it's not so obvious because then the lookup table of the
483 	// generic version may not be in the processor cache.
484 #ifdef CRC_USE_GENERIC_FOR_SMALL_INPUTS
485 	if (size <= 16)
486 		return crc64_generic(buf, size, crc);
487 #endif
488 
489 /*
490 #ifndef HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR
491 	// See crc64_dispatch(). This would be the alternative which uses
492 	// locking and doesn't use crc64_dispatch(). Note that on Windows
493 	// this method needs Vista threads.
494 	mythread_once(crc64_set_func);
495 #endif
496 */
497 
498 	return crc64_func(buf, size, crc);
499 
500 #elif defined(CRC_CLMUL)
501 	// If CLMUL is used unconditionally without runtime CPU detection
502 	// then omitting the generic version and its 8 KiB lookup table
503 	// makes the library smaller.
504 	//
505 	// FIXME: Lookup table isn't currently omitted on 32-bit x86,
506 	// see crc64_table.c.
507 	return crc64_clmul(buf, size, crc);
508 
509 #else
510 	return crc64_generic(buf, size, crc);
511 #endif
512 }
513