crc64_fast.c 17 KB

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