1 // Copyright 2022 The Abseil Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Simultaneous memcopy and CRC-32C for x86-64 and ARM 64. Uses integer
16 // registers because XMM registers do not support the CRC instruction (yet).
17 // While copying, compute the running CRC of the data being copied.
18 //
19 // It is assumed that any CPU running this code has SSE4.2 instructions
20 // available (for CRC32C). This file will do nothing if that is not true.
21 //
22 // The CRC instruction has a 3-byte latency, and we are stressing the ALU ports
23 // here (unlike a traditional memcopy, which has almost no ALU use), so we will
24 // need to copy in such a way that the CRC unit is used efficiently. We have two
25 // regimes in this code:
26 // 1. For operations of size < kCrcSmallSize, do the CRC then the memcpy
27 // 2. For operations of size > kCrcSmallSize:
28 // a) compute an initial CRC + copy on a small amount of data to align the
29 // destination pointer on a 16-byte boundary.
30 // b) Split the data into 3 main regions and a tail (smaller than 48 bytes)
31 // c) Do the copy and CRC of the 3 main regions, interleaving (start with
32 // full cache line copies for each region, then move to single 16 byte
33 // pieces per region).
34 // d) Combine the CRCs with CRC32C::Concat.
35 // e) Copy the tail and extend the CRC with the CRC of the tail.
36 // This method is not ideal for op sizes between ~1k and ~8k because CRC::Concat
37 // takes a significant amount of time. A medium-sized approach could be added
38 // using 3 CRCs over fixed-size blocks where the zero-extensions required for
39 // CRC32C::Concat can be precomputed.
40
41 #ifdef __SSE4_2__
42 #include <immintrin.h>
43 #endif
44
45 #ifdef _MSC_VER
46 #include <intrin.h>
47 #endif
48
49 #include <array>
50 #include <cstddef>
51 #include <cstdint>
52 #include <cstring>
53 #include <memory>
54
55 #include "absl/base/config.h"
56 #include "absl/base/optimization.h"
57 #include "absl/base/prefetch.h"
58 #include "absl/crc/crc32c.h"
59 #include "absl/crc/internal/cpu_detect.h"
60 #include "absl/crc/internal/crc32_x86_arm_combined_simd.h"
61 #include "absl/crc/internal/crc_memcpy.h"
62 #include "absl/strings/string_view.h"
63
64 #if defined(ABSL_INTERNAL_HAVE_X86_64_ACCELERATED_CRC_MEMCPY_ENGINE) || \
65 defined(ABSL_INTERNAL_HAVE_ARM_ACCELERATED_CRC_MEMCPY_ENGINE)
66
67 namespace absl {
68 ABSL_NAMESPACE_BEGIN
69 namespace crc_internal {
70
71 namespace {
72
ShortCrcCopy(char * dst,const char * src,std::size_t length,crc32c_t crc)73 inline crc32c_t ShortCrcCopy(char* dst, const char* src, std::size_t length,
74 crc32c_t crc) {
75 // Small copy: just go 1 byte at a time: being nice to the branch predictor
76 // is more important here than anything else
77 uint32_t crc_uint32 = static_cast<uint32_t>(crc);
78 for (std::size_t i = 0; i < length; i++) {
79 uint8_t data = *reinterpret_cast<const uint8_t*>(src);
80 crc_uint32 = CRC32_u8(crc_uint32, data);
81 *reinterpret_cast<uint8_t*>(dst) = data;
82 ++src;
83 ++dst;
84 }
85 return crc32c_t{crc_uint32};
86 }
87
88 constexpr size_t kIntLoadsPerVec = sizeof(V128) / sizeof(uint64_t);
89
90 // Common function for copying the tails of multiple large regions.
91 template <size_t vec_regions, size_t int_regions>
LargeTailCopy(crc32c_t * crcs,char ** dst,const char ** src,size_t region_size,size_t copy_rounds)92 inline void LargeTailCopy(crc32c_t* crcs, char** dst, const char** src,
93 size_t region_size, size_t copy_rounds) {
94 std::array<V128, vec_regions> data;
95 std::array<uint64_t, kIntLoadsPerVec * int_regions> int_data;
96
97 while (copy_rounds > 0) {
98 for (size_t i = 0; i < vec_regions; i++) {
99 size_t region = i;
100
101 auto* vsrc = reinterpret_cast<const V128*>(*src + region_size * region);
102 auto* vdst = reinterpret_cast<V128*>(*dst + region_size * region);
103
104 // Load the blocks, unaligned
105 data[i] = V128_LoadU(vsrc);
106
107 // Store the blocks, aligned
108 V128_Store(vdst, data[i]);
109
110 // Compute the running CRC
111 crcs[region] = crc32c_t{static_cast<uint32_t>(
112 CRC32_u64(static_cast<uint32_t>(crcs[region]),
113 static_cast<uint64_t>(V128_Extract64<0>(data[i]))))};
114 crcs[region] = crc32c_t{static_cast<uint32_t>(
115 CRC32_u64(static_cast<uint32_t>(crcs[region]),
116 static_cast<uint64_t>(V128_Extract64<1>(data[i]))))};
117 }
118
119 for (size_t i = 0; i < int_regions; i++) {
120 size_t region = vec_regions + i;
121
122 auto* usrc =
123 reinterpret_cast<const uint64_t*>(*src + region_size * region);
124 auto* udst = reinterpret_cast<uint64_t*>(*dst + region_size * region);
125
126 for (size_t j = 0; j < kIntLoadsPerVec; j++) {
127 size_t data_index = i * kIntLoadsPerVec + j;
128
129 int_data[data_index] = *(usrc + j);
130 crcs[region] = crc32c_t{static_cast<uint32_t>(CRC32_u64(
131 static_cast<uint32_t>(crcs[region]), int_data[data_index]))};
132
133 *(udst + j) = int_data[data_index];
134 }
135 }
136
137 // Increment pointers
138 *src += sizeof(V128);
139 *dst += sizeof(V128);
140 --copy_rounds;
141 }
142 }
143
144 } // namespace
145
146 template <size_t vec_regions, size_t int_regions>
147 class AcceleratedCrcMemcpyEngine : public CrcMemcpyEngine {
148 public:
149 AcceleratedCrcMemcpyEngine() = default;
150 AcceleratedCrcMemcpyEngine(const AcceleratedCrcMemcpyEngine&) = delete;
151 AcceleratedCrcMemcpyEngine operator=(const AcceleratedCrcMemcpyEngine&) =
152 delete;
153
154 crc32c_t Compute(void* __restrict dst, const void* __restrict src,
155 std::size_t length, crc32c_t initial_crc) const override;
156 };
157
158 template <size_t vec_regions, size_t int_regions>
Compute(void * __restrict dst,const void * __restrict src,std::size_t length,crc32c_t initial_crc) const159 crc32c_t AcceleratedCrcMemcpyEngine<vec_regions, int_regions>::Compute(
160 void* __restrict dst, const void* __restrict src, std::size_t length,
161 crc32c_t initial_crc) const {
162 constexpr std::size_t kRegions = vec_regions + int_regions;
163 static_assert(kRegions > 0, "Must specify at least one region.");
164 constexpr uint32_t kCrcDataXor = uint32_t{0xffffffff};
165 constexpr std::size_t kBlockSize = sizeof(V128);
166 constexpr std::size_t kCopyRoundSize = kRegions * kBlockSize;
167
168 // Number of blocks per cacheline.
169 constexpr std::size_t kBlocksPerCacheLine = ABSL_CACHELINE_SIZE / kBlockSize;
170
171 char* dst_bytes = static_cast<char*>(dst);
172 const char* src_bytes = static_cast<const char*>(src);
173
174 // Make sure that one prefetch per big block is enough to cover the whole
175 // dataset, and we don't prefetch too much.
176 static_assert(ABSL_CACHELINE_SIZE % kBlockSize == 0,
177 "Cache lines are not divided evenly into blocks, may have "
178 "unintended behavior!");
179
180 // Experimentally-determined boundary between a small and large copy.
181 // Below this number, spin-up and concatenation of CRCs takes enough time that
182 // it kills the throughput gains of using 3 regions and wide vectors.
183 constexpr size_t kCrcSmallSize = 256;
184
185 // Experimentally-determined prefetch distance. Main loop copies will
186 // prefeth data 2 cache lines ahead.
187 constexpr std::size_t kPrefetchAhead = 2 * ABSL_CACHELINE_SIZE;
188
189 // Small-size CRC-memcpy : just do CRC + memcpy
190 if (length < kCrcSmallSize) {
191 crc32c_t crc =
192 ExtendCrc32c(initial_crc, absl::string_view(src_bytes, length));
193 memcpy(dst, src, length);
194 return crc;
195 }
196
197 // Start work on the CRC: undo the XOR from the previous calculation or set up
198 // the initial value of the CRC.
199 // initial_crc ^= kCrcDataXor;
200 initial_crc = crc32c_t{static_cast<uint32_t>(initial_crc) ^ kCrcDataXor};
201
202 // Do an initial alignment copy, so we can use aligned store instructions to
203 // the destination pointer. We align the destination pointer because the
204 // penalty for an unaligned load is small compared to the penalty of an
205 // unaligned store on modern CPUs.
206 std::size_t bytes_from_last_aligned =
207 reinterpret_cast<uintptr_t>(dst) & (kBlockSize - 1);
208 if (bytes_from_last_aligned != 0) {
209 std::size_t bytes_for_alignment = kBlockSize - bytes_from_last_aligned;
210
211 // Do the short-sized copy and CRC.
212 initial_crc =
213 ShortCrcCopy(dst_bytes, src_bytes, bytes_for_alignment, initial_crc);
214 src_bytes += bytes_for_alignment;
215 dst_bytes += bytes_for_alignment;
216 length -= bytes_for_alignment;
217 }
218
219 // We are going to do the copy and CRC in kRegions regions to make sure that
220 // we can saturate the CRC unit. The CRCs will be combined at the end of the
221 // run. Copying will use the SSE registers, and we will extract words from
222 // the SSE registers to add to the CRC. Initially, we run the loop one full
223 // cache line per region at a time, in order to insert prefetches.
224
225 // Initialize CRCs for kRegions regions.
226 crc32c_t crcs[kRegions];
227 crcs[0] = initial_crc;
228 for (size_t i = 1; i < kRegions; i++) {
229 crcs[i] = crc32c_t{kCrcDataXor};
230 }
231
232 // Find the number of rounds to copy and the region size. Also compute the
233 // tail size here.
234 size_t copy_rounds = length / kCopyRoundSize;
235
236 // Find the size of each region and the size of the tail.
237 const std::size_t region_size = copy_rounds * kBlockSize;
238 const std::size_t tail_size = length - (kRegions * region_size);
239
240 // Holding registers for data in each region.
241 std::array<V128, vec_regions> vec_data;
242 std::array<uint64_t, int_regions * kIntLoadsPerVec> int_data;
243
244 // Main loop.
245 while (copy_rounds > kBlocksPerCacheLine) {
246 // Prefetch kPrefetchAhead bytes ahead of each pointer.
247 for (size_t i = 0; i < kRegions; i++) {
248 absl::PrefetchToLocalCache(src_bytes + kPrefetchAhead + region_size * i);
249 #ifdef ABSL_INTERNAL_HAVE_X86_64_ACCELERATED_CRC_MEMCPY_ENGINE
250 // TODO(b/297082454): investigate dropping prefetch on x86.
251 absl::PrefetchToLocalCache(dst_bytes + kPrefetchAhead + region_size * i);
252 #endif
253 }
254
255 // Load and store data, computing CRC on the way.
256 for (size_t i = 0; i < kBlocksPerCacheLine; i++) {
257 // Copy and CRC the data for the CRC regions.
258 for (size_t j = 0; j < vec_regions; j++) {
259 // Cycle which regions get vector load/store and integer load/store, to
260 // engage prefetching logic around vector load/stores and save issue
261 // slots by using the integer registers.
262 size_t region = (j + i) % kRegions;
263
264 auto* vsrc =
265 reinterpret_cast<const V128*>(src_bytes + region_size * region);
266 auto* vdst = reinterpret_cast<V128*>(dst_bytes + region_size * region);
267
268 // Load and CRC data.
269 vec_data[j] = V128_LoadU(vsrc + i);
270 crcs[region] = crc32c_t{static_cast<uint32_t>(
271 CRC32_u64(static_cast<uint32_t>(crcs[region]),
272 static_cast<uint64_t>(V128_Extract64<0>(vec_data[j]))))};
273 crcs[region] = crc32c_t{static_cast<uint32_t>(
274 CRC32_u64(static_cast<uint32_t>(crcs[region]),
275 static_cast<uint64_t>(V128_Extract64<1>(vec_data[j]))))};
276
277 // Store the data.
278 V128_Store(vdst + i, vec_data[j]);
279 }
280
281 // Preload the partial CRCs for the CLMUL subregions.
282 for (size_t j = 0; j < int_regions; j++) {
283 // Cycle which regions get vector load/store and integer load/store, to
284 // engage prefetching logic around vector load/stores and save issue
285 // slots by using the integer registers.
286 size_t region = (j + vec_regions + i) % kRegions;
287
288 auto* usrc =
289 reinterpret_cast<const uint64_t*>(src_bytes + region_size * region);
290 auto* udst =
291 reinterpret_cast<uint64_t*>(dst_bytes + region_size * region);
292
293 for (size_t k = 0; k < kIntLoadsPerVec; k++) {
294 size_t data_index = j * kIntLoadsPerVec + k;
295
296 // Load and CRC the data.
297 int_data[data_index] = *(usrc + i * kIntLoadsPerVec + k);
298 crcs[region] = crc32c_t{static_cast<uint32_t>(CRC32_u64(
299 static_cast<uint32_t>(crcs[region]), int_data[data_index]))};
300
301 // Store the data.
302 *(udst + i * kIntLoadsPerVec + k) = int_data[data_index];
303 }
304 }
305 }
306
307 // Increment pointers
308 src_bytes += kBlockSize * kBlocksPerCacheLine;
309 dst_bytes += kBlockSize * kBlocksPerCacheLine;
310 copy_rounds -= kBlocksPerCacheLine;
311 }
312
313 // Copy and CRC the tails of each region.
314 LargeTailCopy<vec_regions, int_regions>(crcs, &dst_bytes, &src_bytes,
315 region_size, copy_rounds);
316
317 // Move the source and destination pointers to the end of the region
318 src_bytes += region_size * (kRegions - 1);
319 dst_bytes += region_size * (kRegions - 1);
320
321 // Copy and CRC the tail through the XMM registers.
322 std::size_t tail_blocks = tail_size / kBlockSize;
323 LargeTailCopy<0, 1>(&crcs[kRegions - 1], &dst_bytes, &src_bytes, 0,
324 tail_blocks);
325
326 // Final tail copy for under 16 bytes.
327 crcs[kRegions - 1] =
328 ShortCrcCopy(dst_bytes, src_bytes, tail_size - tail_blocks * kBlockSize,
329 crcs[kRegions - 1]);
330
331 if (kRegions == 1) {
332 // If there is only one region, finalize and return its CRC.
333 return crc32c_t{static_cast<uint32_t>(crcs[0]) ^ kCrcDataXor};
334 }
335
336 // Finalize the first CRCs: XOR the internal CRCs by the XOR mask to undo the
337 // XOR done before doing block copy + CRCs.
338 for (size_t i = 0; i + 1 < kRegions; i++) {
339 crcs[i] = crc32c_t{static_cast<uint32_t>(crcs[i]) ^ kCrcDataXor};
340 }
341
342 // Build a CRC of the first kRegions - 1 regions.
343 crc32c_t full_crc = crcs[0];
344 for (size_t i = 1; i + 1 < kRegions; i++) {
345 full_crc = ConcatCrc32c(full_crc, crcs[i], region_size);
346 }
347
348 // Finalize and concatenate the final CRC, then return.
349 crcs[kRegions - 1] =
350 crc32c_t{static_cast<uint32_t>(crcs[kRegions - 1]) ^ kCrcDataXor};
351 return ConcatCrc32c(full_crc, crcs[kRegions - 1], region_size + tail_size);
352 }
353
GetArchSpecificEngines()354 CrcMemcpy::ArchSpecificEngines CrcMemcpy::GetArchSpecificEngines() {
355 #ifdef UNDEFINED_BEHAVIOR_SANITIZER
356 // UBSAN does not play nicely with unaligned loads (which we use a lot).
357 // Get the underlying architecture.
358 CpuType cpu_type = GetCpuType();
359 switch (cpu_type) {
360 case CpuType::kAmdRome:
361 case CpuType::kAmdNaples:
362 case CpuType::kAmdMilan:
363 case CpuType::kAmdGenoa:
364 case CpuType::kAmdRyzenV3000:
365 case CpuType::kIntelCascadelakeXeon:
366 case CpuType::kIntelSkylakeXeon:
367 case CpuType::kIntelSkylake:
368 case CpuType::kIntelBroadwell:
369 case CpuType::kIntelHaswell:
370 case CpuType::kIntelIvybridge:
371 return {
372 /*.temporal=*/new FallbackCrcMemcpyEngine(),
373 /*.non_temporal=*/new CrcNonTemporalMemcpyAVXEngine(),
374 };
375 // INTEL_SANDYBRIDGE performs better with SSE than AVX.
376 case CpuType::kIntelSandybridge:
377 return {
378 /*.temporal=*/new FallbackCrcMemcpyEngine(),
379 /*.non_temporal=*/new CrcNonTemporalMemcpyEngine(),
380 };
381 default:
382 return {/*.temporal=*/new FallbackCrcMemcpyEngine(),
383 /*.non_temporal=*/new FallbackCrcMemcpyEngine()};
384 }
385 #else
386 // Get the underlying architecture.
387 CpuType cpu_type = GetCpuType();
388 switch (cpu_type) {
389 // On Zen 2, PEXTRQ uses 2 micro-ops, including one on the vector store port
390 // which data movement from the vector registers to the integer registers
391 // (where CRC32C happens) to crowd the same units as vector stores. As a
392 // result, using that path exclusively causes bottlenecking on this port.
393 // We can avoid this bottleneck by using the integer side of the CPU for
394 // most operations rather than the vector side. We keep a vector region to
395 // engage some of the prefetching logic in the cache hierarchy which seems
396 // to give vector instructions special treatment. These prefetch units see
397 // strided access to each region, and do the right thing.
398 case CpuType::kAmdRome:
399 case CpuType::kAmdNaples:
400 case CpuType::kAmdMilan:
401 case CpuType::kAmdGenoa:
402 case CpuType::kAmdRyzenV3000:
403 return {
404 /*.temporal=*/new AcceleratedCrcMemcpyEngine<1, 2>(),
405 /*.non_temporal=*/new CrcNonTemporalMemcpyAVXEngine(),
406 };
407 // PCLMULQDQ is slow and we don't have wide enough issue width to take
408 // advantage of it. For an unknown architecture, don't risk using CLMULs.
409 case CpuType::kIntelCascadelakeXeon:
410 case CpuType::kIntelSkylakeXeon:
411 case CpuType::kIntelSkylake:
412 case CpuType::kIntelBroadwell:
413 case CpuType::kIntelHaswell:
414 case CpuType::kIntelIvybridge:
415 return {
416 /*.temporal=*/new AcceleratedCrcMemcpyEngine<3, 0>(),
417 /*.non_temporal=*/new CrcNonTemporalMemcpyAVXEngine(),
418 };
419 // INTEL_SANDYBRIDGE performs better with SSE than AVX.
420 case CpuType::kIntelSandybridge:
421 return {
422 /*.temporal=*/new AcceleratedCrcMemcpyEngine<3, 0>(),
423 /*.non_temporal=*/new CrcNonTemporalMemcpyEngine(),
424 };
425 default:
426 return {/*.temporal=*/new FallbackCrcMemcpyEngine(),
427 /*.non_temporal=*/new FallbackCrcMemcpyEngine()};
428 }
429 #endif // UNDEFINED_BEHAVIOR_SANITIZER
430 }
431
432 // For testing, allow the user to specify which engine they want.
GetTestEngine(int vector,int integer)433 std::unique_ptr<CrcMemcpyEngine> CrcMemcpy::GetTestEngine(int vector,
434 int integer) {
435 if (vector == 3 && integer == 0) {
436 return std::make_unique<AcceleratedCrcMemcpyEngine<3, 0>>();
437 } else if (vector == 1 && integer == 2) {
438 return std::make_unique<AcceleratedCrcMemcpyEngine<1, 2>>();
439 } else if (vector == 1 && integer == 0) {
440 return std::make_unique<AcceleratedCrcMemcpyEngine<1, 0>>();
441 }
442 return nullptr;
443 }
444
445 } // namespace crc_internal
446 ABSL_NAMESPACE_END
447 } // namespace absl
448
449 #endif // ABSL_INTERNAL_HAVE_X86_64_ACCELERATED_CRC_MEMCPY_ENGINE ||
450 // ABSL_INTERNAL_HAVE_ARM_ACCELERATED_CRC_MEMCPY_ENGINE
451