crc64_fast.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. // EDG-based compilers (Intel's classic compiler and compiler for E2K) can
  149. // define __GNUC__ but the attribute must not be used with them.
  150. // The new Clang-based ICX needs the attribute.
  151. //
  152. // NOTE: Build systems check for this too, keep them in sync with this.
  153. #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
  154. __attribute__((__target__("ssse3,sse4.1,pclmul")))
  155. #endif
  156. static uint64_t
  157. crc64_clmul(const uint8_t *buf, size_t size, uint64_t crc)
  158. {
  159. // The prototypes of the intrinsics use signed types while most of
  160. // the values are treated as unsigned here. These warnings in this
  161. // function have been checked and found to be harmless so silence them.
  162. #if TUKLIB_GNUC_REQ(4, 6) || defined(__clang__)
  163. # pragma GCC diagnostic push
  164. # pragma GCC diagnostic ignored "-Wsign-conversion"
  165. # pragma GCC diagnostic ignored "-Wconversion"
  166. #endif
  167. #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
  168. // The code assumes that there is at least one byte of input.
  169. if (size == 0)
  170. return crc;
  171. #endif
  172. // const uint64_t poly = 0xc96c5795d7870f42; // CRC polynomial
  173. const uint64_t p = 0x92d8af2baf0e1e85; // (poly << 1) | 1
  174. const uint64_t mu = 0x9c3e466c172963d5; // (calc_lo(poly) << 1) | 1
  175. const uint64_t k2 = 0xdabe95afc7875f40; // calc_hi(poly, 1)
  176. const uint64_t k1 = 0xe05dd497ca393ae4; // calc_hi(poly, k2)
  177. const __m128i vfold0 = _mm_set_epi64x(p, mu);
  178. const __m128i vfold1 = _mm_set_epi64x(k2, k1);
  179. // Create a vector with 8-bit values 0 to 15. This is used to
  180. // construct control masks for _mm_blendv_epi8 and _mm_shuffle_epi8.
  181. const __m128i vramp = _mm_setr_epi32(
  182. 0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c);
  183. // This is used to inverse the control mask of _mm_shuffle_epi8
  184. // so that bytes that wouldn't be picked with the original mask
  185. // will be picked and vice versa.
  186. const __m128i vsign = _mm_set1_epi8(0x80);
  187. // Memory addresses A to D and the distances between them:
  188. //
  189. // A B C D
  190. // [skip_start][size][skip_end]
  191. // [ size2 ]
  192. //
  193. // A and D are 16-byte aligned. B and C are 1-byte aligned.
  194. // skip_start and skip_end are 0-15 bytes. size is at least 1 byte.
  195. //
  196. // A = aligned_buf will initially point to this address.
  197. // B = The address pointed by the caller-supplied buf.
  198. // C = buf + size == aligned_buf + size2
  199. // D = buf + size + skip_end == aligned_buf + size2 + skip_end
  200. const size_t skip_start = (size_t)((uintptr_t)buf & 15);
  201. const size_t skip_end = (size_t)(-(uintptr_t)(buf + size) & 15);
  202. const __m128i *aligned_buf = (const __m128i *)(
  203. (uintptr_t)buf & ~(uintptr_t)15);
  204. // If size2 <= 16 then the whole input fits into a single 16-byte
  205. // vector. If size2 > 16 then at least two 16-byte vectors must
  206. // be processed. If size2 > 16 && size <= 16 then there is only
  207. // one 16-byte vector's worth of input but it is unaligned in memory.
  208. //
  209. // NOTE: There is no integer overflow here if the arguments are valid.
  210. // If this overflowed, buf + size would too.
  211. size_t size2 = skip_start + size;
  212. // Masks to be used with _mm_blendv_epi8 and _mm_shuffle_epi8:
  213. // The first skip_start or skip_end bytes in the vectors will have
  214. // the high bit (0x80) set. _mm_blendv_epi8 and _mm_shuffle_epi8
  215. // will produce zeros for these positions. (Bitwise-xor of these
  216. // masks with vsign will produce the opposite behavior.)
  217. const __m128i mask_start
  218. = _mm_sub_epi8(vramp, _mm_set1_epi8(skip_start));
  219. const __m128i mask_end = _mm_sub_epi8(vramp, _mm_set1_epi8(skip_end));
  220. // Get the first 1-16 bytes into data0. If loading less than 16 bytes,
  221. // the bytes are loaded to the high bits of the vector and the least
  222. // significant positions are filled with zeros.
  223. const __m128i data0 = _mm_blendv_epi8(_mm_load_si128(aligned_buf),
  224. _mm_setzero_si128(), mask_start);
  225. ++aligned_buf;
  226. #if defined(__i386__) || defined(_M_IX86)
  227. const __m128i initial_crc = _mm_set_epi64x(0, ~crc);
  228. #else
  229. // GCC and Clang would produce good code with _mm_set_epi64x
  230. // but MSVC needs _mm_cvtsi64_si128 on x86-64.
  231. const __m128i initial_crc = _mm_cvtsi64_si128(~crc);
  232. #endif
  233. __m128i v0, v1, v2, v3;
  234. #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
  235. if (size <= 16) {
  236. // Right-shift initial_crc by 1-16 bytes based on "size"
  237. // and store the result in v1 (high bytes) and v0 (low bytes).
  238. //
  239. // NOTE: The highest 8 bytes of initial_crc are zeros so
  240. // v1 will be filled with zeros if size >= 8. The highest 8
  241. // bytes of v1 will always become zeros.
  242. //
  243. // [ v1 ][ v0 ]
  244. // [ initial_crc ] size == 1
  245. // [ initial_crc ] size == 2
  246. // [ initial_crc ] size == 15
  247. // [ initial_crc ] size == 16 (all in v0)
  248. const __m128i mask_low = _mm_add_epi8(
  249. vramp, _mm_set1_epi8(size - 16));
  250. MASK_LH(initial_crc, mask_low, v0, v1);
  251. if (size2 <= 16) {
  252. // There are 1-16 bytes of input and it is all
  253. // in data0. Copy the input bytes to v3. If there
  254. // are fewer than 16 bytes, the low bytes in v3
  255. // will be filled with zeros. That is, the input
  256. // bytes are stored to the same position as
  257. // (part of) initial_crc is in v0.
  258. MASK_L(data0, mask_end, v3);
  259. } else {
  260. // There are 2-16 bytes of input but not all bytes
  261. // are in data0.
  262. const __m128i data1 = _mm_load_si128(aligned_buf);
  263. // Collect the 2-16 input bytes from data0 and data1
  264. // to v2 and v3, and bitwise-xor them with the
  265. // low bits of initial_crc in v0. Note that the
  266. // the second xor is below this else-block as it
  267. // is shared with the other branch.
  268. MASK_H(data0, mask_end, v2);
  269. MASK_L(data1, mask_end, v3);
  270. v0 = _mm_xor_si128(v0, v2);
  271. }
  272. v0 = _mm_xor_si128(v0, v3);
  273. v1 = _mm_alignr_epi8(v1, v0, 8);
  274. } else
  275. #endif
  276. {
  277. const __m128i data1 = _mm_load_si128(aligned_buf);
  278. MASK_LH(initial_crc, mask_start, v0, v1);
  279. v0 = _mm_xor_si128(v0, data0);
  280. v1 = _mm_xor_si128(v1, data1);
  281. #define FOLD \
  282. v1 = _mm_xor_si128(v1, _mm_clmulepi64_si128(v0, vfold1, 0x00)); \
  283. v0 = _mm_xor_si128(v1, _mm_clmulepi64_si128(v0, vfold1, 0x11));
  284. while (size2 > 32) {
  285. ++aligned_buf;
  286. size2 -= 16;
  287. FOLD
  288. v1 = _mm_load_si128(aligned_buf);
  289. }
  290. if (size2 < 32) {
  291. MASK_H(v0, mask_end, v2);
  292. MASK_L(v0, mask_end, v0);
  293. MASK_L(v1, mask_end, v3);
  294. v1 = _mm_or_si128(v2, v3);
  295. }
  296. FOLD
  297. v1 = _mm_srli_si128(v0, 8);
  298. #undef FOLD
  299. }
  300. v1 = _mm_xor_si128(_mm_clmulepi64_si128(v0, vfold1, 0x10), v1);
  301. v0 = _mm_clmulepi64_si128(v1, vfold0, 0x00);
  302. v2 = _mm_clmulepi64_si128(v0, vfold0, 0x10);
  303. v0 = _mm_xor_si128(_mm_xor_si128(v2, _mm_slli_si128(v0, 8)), v1);
  304. #if defined(__i386__) || defined(_M_IX86)
  305. return ~(((uint64_t)(uint32_t)_mm_extract_epi32(v0, 3) << 32) |
  306. (uint64_t)(uint32_t)_mm_extract_epi32(v0, 2));
  307. #else
  308. return ~(uint64_t)_mm_extract_epi64(v0, 1);
  309. #endif
  310. #if TUKLIB_GNUC_REQ(4, 6) || defined(__clang__)
  311. # pragma GCC diagnostic pop
  312. #endif
  313. }
  314. #endif
  315. ////////////////////////
  316. // Detect CPU support //
  317. ////////////////////////
  318. #if defined(CRC_GENERIC) && defined(CRC_CLMUL)
  319. static inline bool
  320. is_clmul_supported(void)
  321. {
  322. int success = 1;
  323. uint32_t r[4]; // eax, ebx, ecx, edx
  324. #if defined(_MSC_VER)
  325. // This needs <intrin.h> with MSVC. ICC has it as a built-in
  326. // on all platforms.
  327. __cpuid(r, 1);
  328. #elif defined(HAVE_CPUID_H)
  329. // Compared to just using __asm__ to run CPUID, this also checks
  330. // that CPUID is supported and saves and restores ebx as that is
  331. // needed with GCC < 5 with position-independent code (PIC).
  332. success = __get_cpuid(1, &r[0], &r[1], &r[2], &r[3]);
  333. #else
  334. // Just a fallback that shouldn't be needed.
  335. __asm__("cpuid\n\t"
  336. : "=a"(r[0]), "=b"(r[1]), "=c"(r[2]), "=d"(r[3])
  337. : "a"(1), "c"(0));
  338. #endif
  339. // Returns true if these are supported:
  340. // CLMUL (bit 1 in ecx)
  341. // SSSE3 (bit 9 in ecx)
  342. // SSE4.1 (bit 19 in ecx)
  343. const uint32_t ecx_mask = (1 << 1) | (1 << 9) | (1 << 19);
  344. return success && (r[2] & ecx_mask) == ecx_mask;
  345. // Alternative methods that weren't used:
  346. // - ICC's _may_i_use_cpu_feature: the other methods should work too.
  347. // - GCC >= 6 / Clang / ICX __builtin_cpu_supports("pclmul")
  348. //
  349. // CPUID decding is needed with MSVC anyway and older GCC. This keeps
  350. // the feature checks in the build system simpler too. The nice thing
  351. // about __builtin_cpu_supports would be that it generates very short
  352. // code as is it only reads a variable set at startup but a few bytes
  353. // doesn't matter here.
  354. }
  355. #ifdef HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR
  356. # define CRC64_FUNC_INIT
  357. # define CRC64_SET_FUNC_ATTR __attribute__((__constructor__))
  358. #else
  359. # define CRC64_FUNC_INIT = &crc64_dispatch
  360. # define CRC64_SET_FUNC_ATTR
  361. static uint64_t crc64_dispatch(const uint8_t *buf, size_t size, uint64_t crc);
  362. #endif
  363. // Pointer to the the selected CRC64 method.
  364. static uint64_t (*crc64_func)(const uint8_t *buf, size_t size, uint64_t crc)
  365. CRC64_FUNC_INIT;
  366. CRC64_SET_FUNC_ATTR
  367. static void
  368. crc64_set_func(void)
  369. {
  370. crc64_func = is_clmul_supported() ? &crc64_clmul : &crc64_generic;
  371. return;
  372. }
  373. #ifndef HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR
  374. static uint64_t
  375. crc64_dispatch(const uint8_t *buf, size_t size, uint64_t crc)
  376. {
  377. // When __attribute__((__constructor__)) isn't supported, set the
  378. // function pointer without any locking. If multiple threads run
  379. // the detection code in parallel, they will all end up setting
  380. // the pointer to the same value. This avoids the use of
  381. // mythread_once() on every call to lzma_crc64() but this likely
  382. // isn't strictly standards compliant. Let's change it if it breaks.
  383. crc64_set_func();
  384. return crc64_func(buf, size, crc);
  385. }
  386. #endif
  387. #endif
  388. extern LZMA_API(uint64_t)
  389. lzma_crc64(const uint8_t *buf, size_t size, uint64_t crc)
  390. {
  391. #if defined(CRC_GENERIC) && defined(CRC_CLMUL)
  392. // If CLMUL is available, it is the best for non-tiny inputs,
  393. // being over twice as fast as the generic slice-by-four version.
  394. // However, for size <= 16 it's different. In the extreme case
  395. // of size == 1 the generic version can be five times faster.
  396. // At size >= 8 the CLMUL starts to become reasonable. It
  397. // varies depending on the alignment of buf too.
  398. //
  399. // The above doesn't include the overhead of mythread_once().
  400. // At least on x86-64 GNU/Linux, pthread_once() is very fast but
  401. // it still makes lzma_crc64(buf, 1, crc) 50-100 % slower. When
  402. // size reaches 12-16 bytes the overhead becomes negligible.
  403. //
  404. // So using the generic version for size <= 16 may give better
  405. // performance with tiny inputs but if such inputs happen rarely
  406. // it's not so obvious because then the lookup table of the
  407. // generic version may not be in the processor cache.
  408. #ifdef CRC_USE_GENERIC_FOR_SMALL_INPUTS
  409. if (size <= 16)
  410. return crc64_generic(buf, size, crc);
  411. #endif
  412. /*
  413. #ifndef HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR
  414. // See crc64_dispatch(). This would be the alternative which uses
  415. // locking and doesn't use crc64_dispatch(). Note that on Windows
  416. // this method needs Vista threads.
  417. mythread_once(crc64_set_func);
  418. #endif
  419. */
  420. return crc64_func(buf, size, crc);
  421. #elif defined(CRC_CLMUL)
  422. // If CLMUL is used unconditionally without runtime CPU detection
  423. // then omitting the generic version and its 8 KiB lookup table
  424. // makes the library smaller.
  425. //
  426. // FIXME: Lookup table isn't currently omitted on 32-bit x86,
  427. // see crc64_table.c.
  428. return crc64_clmul(buf, size, crc);
  429. #else
  430. return crc64_generic(buf, size, crc);
  431. #endif
  432. }