Debian Codegraph @

debian/rust-vendor/crc-fast/src/arch/mod.rs

raw
1 // Copyright 2025 Don MacAskill. Licensed under MIT or Apache-2.0.
2
3 //! This module provides the main entry point for the SIMD CRC calculation.
4 //!
5 //! It dispatches to the appropriate architecture-specific implementation
6
7 #[cfg(all(target_arch = "aarch64", feature = "std"))]
8 use std::arch::is_aarch64_feature_detected;
9
10 use crate::CrcParams;
11
12 #[cfg(target_arch = "aarch64")]
13 use crate::arch::aarch64::aes::Aarch64AesOps;
14
15 #[cfg(target_arch = "aarch64")]
16 use crate::arch::aarch64::aes_sha3::Aarch64AesSha3Ops;
17
18 #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))]
19 use crate::{
20 algorithm,
21 structs::{Width16, Width32, Width64},
22 };
23
24 pub mod aarch64;
25 pub mod software;
26 pub mod x86;
27 pub mod x86_64;
28
29 /// Main entry point that dispatches to the appropriate architecture
30 ///
31 /// # Safety
32 /// May use native CPU features
33 #[inline(always)]
34 #[cfg(target_arch = "aarch64")]
35 pub(crate) unsafe fn update(state: u64, bytes: &[u8], params: &CrcParams) -> u64 {
36 use crate::feature_detection::{get_arch_ops, ArchOpsInstance};
37
38 match get_arch_ops() {
39 ArchOpsInstance::Aarch64AesSha3(ops) => update_aarch64_aes_sha3(state, bytes, params, *ops),
40 ArchOpsInstance::Aarch64Aes(ops) => update_aarch64_aes(state, bytes, params, *ops),
41 ArchOpsInstance::SoftwareFallback => {
42 #[cfg(feature = "std")]
43 let has_features =
44 is_aarch64_feature_detected!("aes") && is_aarch64_feature_detected!("neon");
45 #[cfg(not(feature = "std"))]
46 let has_features = cfg!(target_feature = "aes") && cfg!(target_feature = "neon");
47
48 if !has_features {
49 #[cfg(any(not(target_feature = "aes"), not(target_feature = "neon")))]
50 {
51 // Use software implementation when no SIMD support is available
52 return crate::arch::software::update(state, bytes, params);
53 }
54 }
55
56 // This should likely never happen, but just in case
57 panic!("aarch64 features missing (NEON and/or AES)");
58 }
59 }
60 }
61
62 #[inline]
63 #[cfg(target_arch = "aarch64")]
64 #[target_feature(enable = "aes")]
65 unsafe fn update_aarch64_aes(
66 state: u64,
67 bytes: &[u8],
68 params: &CrcParams,
69 ops: Aarch64AesOps,
70 ) -> u64 {
71 match params.width {
72 64 => algorithm::update::<_, Width64>(state, bytes, params, &ops),
73 32 => algorithm::update::<_, Width32>(state as u32, bytes, params, &ops) as u64,
74 16 => algorithm::update::<_, Width16>(state as u16, bytes, params, &ops) as u64,
75 _ => panic!("Unsupported CRC width: {}", params.width),
76 }
77 }
78
79 #[inline]
80 #[cfg(target_arch = "aarch64")]
81 #[target_feature(enable = "aes,sha3")]
82 unsafe fn update_aarch64_aes_sha3(
83 state: u64,
84 bytes: &[u8],
85 params: &CrcParams,
86 ops: Aarch64AesSha3Ops,
87 ) -> u64 {
88 match params.width {
89 64 => algorithm::update::<_, Width64>(state, bytes, params, &ops),
90 32 => algorithm::update::<_, Width32>(state as u32, bytes, params, &ops) as u64,
91 16 => algorithm::update::<_, Width16>(state as u16, bytes, params, &ops) as u64,
92 _ => panic!("Unsupported CRC width: {}", params.width),
93 }
94 }
95
96 /// Main entry point for x86/x86_64 (Rust 1.89+ which supports AVX-512)
97 ///
98 /// # Safety
99 /// May use native CPU features
100 #[rustversion::since(1.89)]
101 #[inline(always)]
102 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
103 pub(crate) unsafe fn update(state: u64, bytes: &[u8], params: &CrcParams) -> u64 {
104 use crate::feature_detection::{get_arch_ops, ArchOpsInstance};
105
106 match get_arch_ops() {
107 #[cfg(target_arch = "x86_64")]
108 ArchOpsInstance::X86_64Avx512Vpclmulqdq(ops) => {
109 update_x86_64_avx512_vpclmulqdq(state, bytes, params, *ops)
110 }
111 #[cfg(target_arch = "x86_64")]
112 ArchOpsInstance::X86_64Avx512Pclmulqdq(ops) => {
113 update_x86_64_avx512_pclmulqdq(state, bytes, params, *ops)
114 }
115 ArchOpsInstance::X86SsePclmulqdq(ops) => {
116 update_x86_sse_pclmulqdq(state, bytes, params, *ops)
117 }
118 ArchOpsInstance::SoftwareFallback => crate::arch::software::update(state, bytes, params),
119 }
120 }
121
122 /// Main entry point for x86/x86_64 (Rust < 1.89 with no AVX-512 support)
123 ///
124 /// # Safety
125 /// May use native CPU features
126 #[rustversion::before(1.89)]
127 #[inline(always)]
128 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
129 pub(crate) unsafe fn update(state: u64, bytes: &[u8], params: &CrcParams) -> u64 {
130 use crate::feature_detection::{get_arch_ops, ArchOpsInstance};
131
132 match get_arch_ops() {
133 ArchOpsInstance::X86SsePclmulqdq(ops) => {
134 update_x86_sse_pclmulqdq(state, bytes, params, *ops)
135 }
136 ArchOpsInstance::SoftwareFallback => crate::arch::software::update(state, bytes, params),
137 }
138 }
139
140 #[inline]
141 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
142 #[target_feature(enable = "sse4.1,pclmulqdq")]
143 unsafe fn update_x86_sse_pclmulqdq(
144 state: u64,
145 bytes: &[u8],
146 params: &CrcParams,
147 ops: crate::arch::x86::sse::X86SsePclmulqdqOps,
148 ) -> u64 {
149 match params.width {
150 64 => algorithm::update::<_, Width64>(state, bytes, params, &ops),
151 32 => algorithm::update::<_, Width32>(state as u32, bytes, params, &ops) as u64,
152 16 => algorithm::update::<_, Width16>(state as u16, bytes, params, &ops) as u64,
153 _ => panic!("Unsupported CRC width: {}", params.width),
154 }
155 }
156
157 #[rustversion::since(1.89)]
158 #[inline]
159 #[cfg(target_arch = "x86_64")]
160 #[target_feature(enable = "avx512vl,pclmulqdq")]
161 unsafe fn update_x86_64_avx512_pclmulqdq(
162 state: u64,
163 bytes: &[u8],
164 params: &CrcParams,
165 ops: crate::arch::x86_64::avx512::X86_64Avx512PclmulqdqOps,
166 ) -> u64 {
167 match params.width {
168 64 => algorithm::update::<_, Width64>(state, bytes, params, &ops),
169 32 => algorithm::update::<_, Width32>(state as u32, bytes, params, &ops) as u64,
170 16 => algorithm::update::<_, Width16>(state as u16, bytes, params, &ops) as u64,
171 _ => panic!("Unsupported CRC width: {}", params.width),
172 }
173 }
174
175 #[rustversion::since(1.89)]
176 #[inline]
177 #[cfg(target_arch = "x86_64")]
178 #[target_feature(enable = "avx512vl,vpclmulqdq")]
179 unsafe fn update_x86_64_avx512_vpclmulqdq(
180 state: u64,
181 bytes: &[u8],
182 params: &CrcParams,
183 ops: crate::arch::x86_64::avx512_vpclmulqdq::X86_64Avx512VpclmulqdqOps,
184 ) -> u64 {
185 match params.width {
186 64 => algorithm::update::<_, Width64>(state, bytes, params, &ops),
187 32 => algorithm::update::<_, Width32>(state as u32, bytes, params, &ops) as u64,
188 16 => algorithm::update::<_, Width16>(state as u16, bytes, params, &ops) as u64,
189 _ => panic!("Unsupported CRC width: {}", params.width),
190 }
191 }
192
193 #[inline(always)]
194 #[cfg(all(
195 not(target_arch = "x86"),
196 not(target_arch = "x86_64"),
197 not(target_arch = "aarch64")
198 ))]
199 pub(crate) unsafe fn update(state: u64, bytes: &[u8], params: &CrcParams) -> u64 {
200 crate::arch::software::update(state, bytes, params)
201 }
202
203 #[cfg(test)]
204 mod tests {
205 use super::*;
206 use crate::crc32::consts::CRC32_BZIP2;
207 use crate::crc64::consts::CRC64_NVME;
208 use crate::test::consts::{TEST_256_BYTES_STRING, TEST_ALL_CONFIGS, TEST_CHECK_STRING};
209 use crate::test::create_aligned_data;
210 use crate::test::enums::AnyCrcTestConfig;
211 use rand::{rng, Rng};
212
213 #[test]
214 fn test_check_value() {
215 for config in TEST_ALL_CONFIGS {
216 // direct update() call, which needs XOROUT applied
217 let actual = unsafe {
218 update(
219 config.get_init_algorithm(),
220 TEST_CHECK_STRING,
221 config.get_params(),
222 ) ^ config.get_xorout()
223 };
224
225 assert_eq!(
226 actual,
227 config.get_check(),
228 "Mismatch CRC, {}, expected {:#x}, got {:#x}",
229 config.get_name(),
230 config.get_check(),
231 actual
232 );
233 }
234 }
235
236 #[test]
237 fn test_256_string() {
238 for config in TEST_ALL_CONFIGS {
239 let actual = unsafe {
240 update(
241 config.get_init_algorithm(),
242 &create_aligned_data(TEST_256_BYTES_STRING),
243 config.get_params(),
244 ) ^ config.get_xorout()
245 };
246
247 assert_eq!(
248 actual,
249 config.checksum_with_reference(TEST_256_BYTES_STRING),
250 "Mismatch CRC, {}, expected {:#x}, got {:#x}",
251 config.get_name(),
252 config.get_check(),
253 actual
254 );
255 }
256 }
257
258 #[test]
259 fn test_512_string() {
260 let test_string = b"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234561234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456";
261
262 for config in TEST_ALL_CONFIGS {
263 let actual = unsafe {
264 update(
265 config.get_init_algorithm(),
266 &create_aligned_data(test_string),
267 config.get_params(),
268 ) ^ config.get_xorout()
269 };
270
271 assert_eq!(
272 actual,
273 config.checksum_with_reference(test_string),
274 "Mismatch CRC, {}, expected {:#x}, got {:#x}",
275 config.get_name(),
276 config.get_check(),
277 actual
278 );
279 }
280 }
281
282 #[test]
283 fn test_1024_string() {
284 let test_string = b"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345612345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234561234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456";
285
286 for config in TEST_ALL_CONFIGS {
287 let actual = unsafe {
288 update(
289 config.get_init_algorithm(),
290 &create_aligned_data(test_string),
291 config.get_params(),
292 ) ^ config.get_xorout()
293 };
294
295 assert_eq!(
296 actual,
297 config.checksum_with_reference(test_string),
298 "Mismatch CRC, {}, expected {:#x}, got {:#x}",
299 config.get_name(),
300 config.get_check(),
301 actual
302 );
303 }
304 }
305
306 // CRC-64/NVME is a special flower in that Rust's crc library doesn't support it yet, so we have
307 // tested values to check against.
308 #[test]
309 fn test_crc64_nvme_standard_vectors() {
310 static CASES: &[(&[u8], u64)] = &[
311 // from our own internal tests, since the Check value in the NVM Express® NVM Command
312 // Set Specification (Revision 1.0d, December 2023) is incorrect
313 // (Section 5.2.1.3.4, Figure 120, page 83).
314 (b"123456789", 0xae8b14860a799888),
315
316 // from the NVM Express® NVM Command Set Specification (Revision 1.0d, December 2023),
317 // Section 5.2.1.3.5, Figure 122, page 84.
318 // https://nvmexpress.org/wp-content/uploads/NVM-Express-NVM-Command-Set-Specification-1.0d-2023.12.28-Ratified.pdf
319 // and the Linux kernel
320 // https://github.com/torvalds/linux/blob/f3813f4b287e480b1fcd62ca798d8556644b8278/crypto/testmgr.h#L3685-L3695
321 (&[0; 4096], 0x6482d367eb22b64e),
322 (&[255; 4096], 0xc0ddba7302eca3ac),
323
324 // custom values
325 (TEST_256_BYTES_STRING, 0xabdb9e6c30937916),
326 (b"", 0),
327 (b"@", 0x2808afa9582aa47),
328 (b"1\x97", 0xb4af0ae0feb08e0f),
329 (b"M\"\xdf", 0x85d7cd041a2a8a5d),
330 (b"l\xcd\x13\xd7", 0x1860820ea79b0fa3),
331 (&[0; 32], 0xcf3473434d4ecf3b),
332 (&[255; 32], 0xa0a06974c34d63c4),
333 (b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 0xb9d9d4a8492cbd7f),
334 (&[0; 1024], 0x691bb2b09be5498a),
335 (b"hello, world!", 0xf8046e40c403f1d0),
336 ];
337
338 for (input, expected) in CASES {
339 unsafe {
340 let actual = update(CRC64_NVME.init, input, &CRC64_NVME) ^ CRC64_NVME.xorout;
341
342 assert_eq!(
343 actual, *expected,
344 "Mismatch CRC, expected {:#x}, got {:#x}, input: {:?}",
345 expected, actual, input
346 );
347 }
348 }
349 }
350
351 /// Test the "crc32" variant used in PHP's hash() function, which is different from the
352 /// crc32() function. It's really just CRC-32/BZIP2 with the output byte-reversed to little
353 /// endian.
354 ///
355 /// https://www.php.net/manual/en/function.hash-file.php#104836
356 #[test]
357 fn test_crc32_php_standard_vectors() {
358 static CASES: &[(&[u8], u64)] = &[
359 (b"123456789", 0x181989fc),
360 (&[0; 4096], 0xe3380088),
361 (&[255; 4096], 0x8f2ae650),
362 (b"hello, world!", 0x5eacce7),
363 ];
364
365 for (input, expected) in CASES {
366 let bzip2_crc = unsafe {
367 (update(CRC32_BZIP2.init, input, &CRC32_BZIP2) ^ CRC32_BZIP2.xorout) as u32
368 };
369
370 // PHP reverses the byte order of the CRC for some reason
371 let actual = bzip2_crc.swap_bytes();
372
373 assert_eq!(
374 actual, *expected as u32,
375 "Mismatch CRC, expected {:#x}, got {:#x}, input: {:?}",
376 expected, actual, input
377 );
378 }
379 }
380
381 /// Test CRC-16/IBM-SDLC check value (reflected variant)
382 #[test]
383 fn test_crc16_ibm_sdlc_check_value() {
384 use crate::crc16::consts::CRC16_IBM_SDLC;
385
386 let actual = unsafe {
387 update(CRC16_IBM_SDLC.init, TEST_CHECK_STRING, &CRC16_IBM_SDLC) ^ CRC16_IBM_SDLC.xorout
388 };
389
390 assert_eq!(
391 actual, 0x906E,
392 "CRC-16/IBM-SDLC check value mismatch: expected 0x906E, got {:#x}",
393 actual
394 );
395 }
396
397 /// Test CRC-16/T10-DIF check value (forward/non-reflected variant)
398 #[test]
399 fn test_crc16_t10_dif_check_value() {
400 use crate::crc16::consts::CRC16_T10_DIF;
401
402 let actual = unsafe {
403 update(CRC16_T10_DIF.init, TEST_CHECK_STRING, &CRC16_T10_DIF) ^ CRC16_T10_DIF.xorout
404 };
405
406 assert_eq!(
407 actual, 0xD0DB,
408 "CRC-16/T10-DIF check value mismatch: expected 0xD0DB, got {:#x}",
409 actual
410 );
411 }
412
413 /// Skipping for Miri runs due to time constraints, underlying code already covered by other
414 /// tests.
415 #[test]
416 #[cfg_attr(miri, ignore)]
417 fn test_small_lengths_all() {
418 // Test each CRC variant
419 for config in TEST_ALL_CONFIGS {
420 // Test each length from 0 to 255
421 for len in 0..=255 {
422 test_length(len, config);
423 }
424 }
425 }
426
427 /// Skipping for Miri runs due to time constraints, underlying code already covered by other
428 /// tests.
429 #[test]
430 #[cfg_attr(miri, ignore)]
431 fn test_medium_lengths() {
432 // Test each CRC variant
433 for config in TEST_ALL_CONFIGS {
434 // Test each length from 256 to 1024, which should fold and include handling remainders
435 for len in 256..=1024 {
436 test_length(len, config);
437 }
438 }
439 }
440
441 /// Skipping for Miri runs due to time constraints, underlying code already covered by other
442 /// tests.
443 #[test]
444 #[cfg_attr(miri, ignore)]
445 fn test_large_lengths() {
446 // Test each CRC variant
447 for config in TEST_ALL_CONFIGS {
448 // Test ~1 MiB just before, at, and just after the folding boundaries
449 for len in 1048575..=1048577 {
450 test_length(len, config);
451 }
452 }
453 }
454
455 fn test_length(length: usize, config: &AnyCrcTestConfig) {
456 let mut data = vec![0u8; length];
457 rng().fill(&mut data[..]);
458
459 // Calculate expected CRC using the reference implementation
460 let expected = config.checksum_with_reference(&data);
461
462 // direct update() call, which needs XOROUT applied
463 let actual = unsafe {
464 update(config.get_init_algorithm(), &data, config.get_params()) ^ config.get_xorout()
465 };
466
467 assert_eq!(
468 actual,
469 expected,
470 "\nFailed for {} with length {}\nGot: {:016x}\nExpected: {:016x}",
471 config.get_name(),
472 length,
473 actual,
474 expected
475 );
476 }
477 }