Debian Codegraph @

debian/rust-vendor/blake2b_simd/src/guts.rs

raw
1 use crate::*;
2 use core::cmp;
3
4 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
5 pub const MAX_DEGREE: usize = 4;
6
7 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
8 pub const MAX_DEGREE: usize = 1;
9
10 // Variants other than Portable are unreachable in no_std, unless CPU features
11 // are explicitly enabled for the build with e.g. RUSTFLAGS="-C target-feature=avx2".
12 // This might change in the future if is_x86_feature_detected moves into libcore.
13 #[allow(dead_code)]
14 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
15 enum Platform {
16 Portable,
17 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
18 SSE41,
19 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
20 AVX2,
21 }
22
23 #[derive(Clone, Copy, Debug)]
24 pub struct Implementation(Platform);
25
26 impl Implementation {
27 pub fn detect() -> Self {
28 // Try the different implementations in order of how fast/modern they
29 // are. Currently on non-x86, everything just uses portable.
30 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
31 {
32 if let Some(avx2_impl) = Self::avx2_if_supported() {
33 return avx2_impl;
34 }
35 }
36 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
37 {
38 if let Some(sse41_impl) = Self::sse41_if_supported() {
39 return sse41_impl;
40 }
41 }
42 Self::portable()
43 }
44
45 pub fn portable() -> Self {
46 Implementation(Platform::Portable)
47 }
48
49 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
50 #[allow(unreachable_code)]
51 pub fn sse41_if_supported() -> Option<Self> {
52 // Check whether SSE4.1 support is assumed by the build.
53 #[cfg(target_feature = "sse4.1")]
54 {
55 return Some(Implementation(Platform::SSE41));
56 }
57 // Otherwise dynamically check for support if we can.
58 #[cfg(feature = "std")]
59 {
60 if is_x86_feature_detected!("sse4.1") {
61 return Some(Implementation(Platform::SSE41));
62 }
63 }
64 None
65 }
66
67 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
68 #[allow(unreachable_code)]
69 pub fn avx2_if_supported() -> Option<Self> {
70 // Check whether AVX2 support is assumed by the build.
71 #[cfg(target_feature = "avx2")]
72 {
73 return Some(Implementation(Platform::AVX2));
74 }
75 // Otherwise dynamically check for support if we can.
76 #[cfg(feature = "std")]
77 {
78 if is_x86_feature_detected!("avx2") {
79 return Some(Implementation(Platform::AVX2));
80 }
81 }
82 None
83 }
84
85 pub fn degree(&self) -> usize {
86 match self.0 {
87 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
88 Platform::AVX2 => avx2::DEGREE,
89 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
90 Platform::SSE41 => sse41::DEGREE,
91 Platform::Portable => 1,
92 }
93 }
94
95 pub fn compress1_loop(
96 &self,
97 input: &[u8],
98 words: &mut [Word; 8],
99 count: Count,
100 last_node: LastNode,
101 finalize: Finalize,
102 stride: Stride,
103 ) {
104 match self.0 {
105 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
106 Platform::AVX2 => unsafe {
107 avx2::compress1_loop(input, words, count, last_node, finalize, stride);
108 },
109 // Note that there's an SSE version of compress1 in the official C
110 // implementation, but I haven't ported it yet.
111 _ => {
112 portable::compress1_loop(input, words, count, last_node, finalize, stride);
113 }
114 }
115 }
116
117 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
118 pub fn compress2_loop(&self, jobs: &mut [Job; 2], finalize: Finalize, stride: Stride) {
119 match self.0 {
120 Platform::AVX2 | Platform::SSE41 => unsafe {
121 sse41::compress2_loop(jobs, finalize, stride)
122 },
123 _ => panic!("unsupported"),
124 }
125 }
126
127 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
128 pub fn compress4_loop(&self, jobs: &mut [Job; 4], finalize: Finalize, stride: Stride) {
129 match self.0 {
130 Platform::AVX2 => unsafe { avx2::compress4_loop(jobs, finalize, stride) },
131 _ => panic!("unsupported"),
132 }
133 }
134 }
135
136 pub struct Job<'a, 'b> {
137 pub input: &'a [u8],
138 pub words: &'b mut [Word; 8],
139 pub count: Count,
140 pub last_node: LastNode,
141 }
142
143 impl<'a, 'b> core::fmt::Debug for Job<'a, 'b> {
144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 // NB: Don't print the words. Leaking them would allow length extension.
146 write!(
147 f,
148 "Job {{ input_len: {}, count: {}, last_node: {} }}",
149 self.input.len(),
150 self.count,
151 self.last_node.yes(),
152 )
153 }
154 }
155
156 // Finalize could just be a bool, but this is easier to read at callsites.
157 #[derive(Clone, Copy, Debug)]
158 pub enum Finalize {
159 Yes,
160 No,
161 }
162
163 impl Finalize {
164 pub fn yes(&self) -> bool {
165 match self {
166 Finalize::Yes => true,
167 Finalize::No => false,
168 }
169 }
170 }
171
172 // Like Finalize, this is easier to read at callsites.
173 #[derive(Clone, Copy, Debug)]
174 pub enum LastNode {
175 Yes,
176 No,
177 }
178
179 impl LastNode {
180 pub fn yes(&self) -> bool {
181 match self {
182 LastNode::Yes => true,
183 LastNode::No => false,
184 }
185 }
186 }
187
188 #[derive(Clone, Copy, Debug)]
189 pub enum Stride {
190 Serial, // BLAKE2b/BLAKE2s
191 Parallel, // BLAKE2bp/BLAKE2sp
192 }
193
194 impl Stride {
195 pub fn padded_blockbytes(&self) -> usize {
196 match self {
197 Stride::Serial => BLOCKBYTES,
198 Stride::Parallel => blake2bp::DEGREE * BLOCKBYTES,
199 }
200 }
201 }
202
203 pub(crate) fn count_low(count: Count) -> Word {
204 count as Word
205 }
206
207 pub(crate) fn count_high(count: Count) -> Word {
208 (count >> 8 * size_of::<Word>()) as Word
209 }
210
211 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
212 pub(crate) fn assemble_count(low: Word, high: Word) -> Count {
213 low as Count + ((high as Count) << 8 * size_of::<Word>())
214 }
215
216 pub(crate) fn flag_word(flag: bool) -> Word {
217 if flag {
218 !0
219 } else {
220 0
221 }
222 }
223
224 // Pull a array reference at the given offset straight from the input, if
225 // there's a full block of input available. If there's only a partial block,
226 // copy it into the provided buffer, and return an array reference that. Along
227 // with the array, return the number of bytes of real input, and whether the
228 // input can be finalized (i.e. whether there aren't any more bytes after this
229 // block). Note that this is written so that the optimizer can elide bounds
230 // checks, see: https://godbolt.org/z/0hH2bC
231 pub fn final_block<'a>(
232 input: &'a [u8],
233 offset: usize,
234 buffer: &'a mut [u8; BLOCKBYTES],
235 stride: Stride,
236 ) -> (&'a [u8; BLOCKBYTES], usize, bool) {
237 let capped_offset = cmp::min(offset, input.len());
238 let offset_slice = &input[capped_offset..];
239 if offset_slice.len() >= BLOCKBYTES {
240 let block = (&offset_slice[..BLOCKBYTES]).try_into().unwrap();
241 let should_finalize = offset_slice.len() <= stride.padded_blockbytes();
242 (block, BLOCKBYTES, should_finalize)
243 } else {
244 // Copy the final block to the front of the block buffer. The rest of
245 // the buffer is assumed to be initialized to zero.
246 buffer[..offset_slice.len()].copy_from_slice(offset_slice);
247 (buffer, offset_slice.len(), true)
248 }
249 }
250
251 pub fn input_debug_asserts(input: &[u8], finalize: Finalize) {
252 // If we're not finalizing, the input must not be empty, and it must be an
253 // even multiple of the block size.
254 if !finalize.yes() {
255 debug_assert!(!input.is_empty());
256 debug_assert_eq!(0, input.len() % BLOCKBYTES);
257 }
258 }
259
260 #[cfg(test)]
261 mod test {
262 use super::*;
263 use core::mem::size_of;
264
265 #[test]
266 fn test_detection() {
267 assert_eq!(Platform::Portable, Implementation::portable().0);
268
269 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
270 #[cfg(feature = "std")]
271 {
272 if is_x86_feature_detected!("avx2") {
273 assert_eq!(Platform::AVX2, Implementation::detect().0);
274 assert_eq!(
275 Platform::AVX2,
276 Implementation::avx2_if_supported().unwrap().0
277 );
278 assert_eq!(
279 Platform::SSE41,
280 Implementation::sse41_if_supported().unwrap().0
281 );
282 } else if is_x86_feature_detected!("sse4.1") {
283 assert_eq!(Platform::SSE41, Implementation::detect().0);
284 assert!(Implementation::avx2_if_supported().is_none());
285 assert_eq!(
286 Platform::SSE41,
287 Implementation::sse41_if_supported().unwrap().0
288 );
289 } else {
290 assert_eq!(Platform::Portable, Implementation::detect().0);
291 assert!(Implementation::avx2_if_supported().is_none());
292 assert!(Implementation::sse41_if_supported().is_none());
293 }
294 }
295 }
296
297 // TODO: Move all of these case tests into the implementation files.
298 fn exercise_cases<F>(mut f: F)
299 where
300 F: FnMut(Stride, usize, LastNode, Finalize, Count),
301 {
302 // Chose counts to hit the relevant overflow cases.
303 let counts = &[
304 (0 as Count),
305 ((1 as Count) << (8 * size_of::<Word>())) - BLOCKBYTES as Count,
306 (0 as Count).wrapping_sub(BLOCKBYTES as Count),
307 ];
308 for &stride in &[Stride::Serial, Stride::Parallel] {
309 let lengths = [
310 0,
311 1,
312 BLOCKBYTES - 1,
313 BLOCKBYTES,
314 BLOCKBYTES + 1,
315 2 * BLOCKBYTES - 1,
316 2 * BLOCKBYTES,
317 2 * BLOCKBYTES + 1,
318 stride.padded_blockbytes() - 1,
319 stride.padded_blockbytes(),
320 stride.padded_blockbytes() + 1,
321 2 * stride.padded_blockbytes() - 1,
322 2 * stride.padded_blockbytes(),
323 2 * stride.padded_blockbytes() + 1,
324 ];
325 for &length in &lengths {
326 for &last_node in &[LastNode::No, LastNode::Yes] {
327 for &finalize in &[Finalize::No, Finalize::Yes] {
328 if !finalize.yes() && (length == 0 || length % BLOCKBYTES != 0) {
329 // Skip these cases, they're invalid.
330 continue;
331 }
332 for &count in counts {
333 // eprintln!("\ncase -----");
334 // dbg!(stride);
335 // dbg!(length);
336 // dbg!(last_node);
337 // dbg!(finalize);
338 // dbg!(count);
339
340 f(stride, length, last_node, finalize, count);
341 }
342 }
343 }
344 }
345 }
346 }
347
348 fn initial_test_words(input_index: usize) -> [Word; 8] {
349 crate::Params::new()
350 .node_offset(input_index as u64)
351 .to_words()
352 }
353
354 // Use the portable implementation, one block at a time, to compute the
355 // final state words expected for a given test case.
356 fn reference_compression(
357 input: &[u8],
358 stride: Stride,
359 last_node: LastNode,
360 finalize: Finalize,
361 mut count: Count,
362 input_index: usize,
363 ) -> [Word; 8] {
364 let mut words = initial_test_words(input_index);
365 let mut offset = 0;
366 while offset == 0 || offset < input.len() {
367 let block_size = cmp::min(BLOCKBYTES, input.len() - offset);
368 let maybe_finalize = if offset + stride.padded_blockbytes() < input.len() {
369 Finalize::No
370 } else {
371 finalize
372 };
373 portable::compress1_loop(
374 &input[offset..][..block_size],
375 &mut words,
376 count,
377 last_node,
378 maybe_finalize,
379 Stride::Serial,
380 );
381 offset += stride.padded_blockbytes();
382 count = count.wrapping_add(BLOCKBYTES as Count);
383 }
384 words
385 }
386
387 // For various loop lengths and finalization parameters, make sure that the
388 // implementation gives the same answer as the portable implementation does
389 // when invoked one block at a time. (So even the portable implementation
390 // itself is being tested here, to make sure its loop is correct.) Note
391 // that this doesn't include any fixed test vectors; those are taken from
392 // the blake2-kat.json file (copied from upstream) and tested elsewhere.
393 fn exercise_compress1_loop(implementation: Implementation) {
394 let mut input = [0; 100 * BLOCKBYTES];
395 paint_test_input(&mut input);
396
397 exercise_cases(|stride, length, last_node, finalize, count| {
398 let reference_words =
399 reference_compression(&input[..length], stride, last_node, finalize, count, 0);
400
401 let mut test_words = initial_test_words(0);
402 implementation.compress1_loop(
403 &input[..length],
404 &mut test_words,
405 count,
406 last_node,
407 finalize,
408 stride,
409 );
410 assert_eq!(reference_words, test_words);
411 });
412 }
413
414 #[test]
415 fn test_compress1_loop_portable() {
416 exercise_compress1_loop(Implementation::portable());
417 }
418
419 #[test]
420 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
421 fn test_compress1_loop_sse41() {
422 // Currently this just falls back to portable, but we test it anyway.
423 if let Some(imp) = Implementation::sse41_if_supported() {
424 exercise_compress1_loop(imp);
425 }
426 }
427
428 #[test]
429 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
430 fn test_compress1_loop_avx2() {
431 if let Some(imp) = Implementation::avx2_if_supported() {
432 exercise_compress1_loop(imp);
433 }
434 }
435
436 // I use ArrayVec everywhere in here becuase currently these tests pass
437 // under no_std. I might decide that's not worth maintaining at some point,
438 // since really all we care about with no_std is that the library builds,
439 // but for now it's here. Everything is keyed off of this N constant so
440 // that it's easy to copy the code to exercise_compress4_loop.
441 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
442 fn exercise_compress2_loop(implementation: Implementation) {
443 const N: usize = 2;
444
445 let mut input_buffer = [0; 100 * BLOCKBYTES];
446 paint_test_input(&mut input_buffer);
447 let mut inputs = arrayvec::ArrayVec::<_, N>::new();
448 for i in 0..N {
449 inputs.push(&input_buffer[i..]);
450 }
451
452 exercise_cases(|stride, length, last_node, finalize, count| {
453 let mut reference_words = arrayvec::ArrayVec::<_, N>::new();
454 for i in 0..N {
455 let words = reference_compression(
456 &inputs[i][..length],
457 stride,
458 last_node,
459 finalize,
460 count.wrapping_add((i * BLOCKBYTES) as Count),
461 i,
462 );
463 reference_words.push(words);
464 }
465
466 let mut test_words = arrayvec::ArrayVec::<_, N>::new();
467 for i in 0..N {
468 test_words.push(initial_test_words(i));
469 }
470 let mut jobs = arrayvec::ArrayVec::<_, N>::new();
471 for (i, words) in test_words.iter_mut().enumerate() {
472 jobs.push(Job {
473 input: &inputs[i][..length],
474 words,
475 count: count.wrapping_add((i * BLOCKBYTES) as Count),
476 last_node,
477 });
478 }
479 let mut jobs = jobs.into_inner().expect("full");
480 implementation.compress2_loop(&mut jobs, finalize, stride);
481
482 for i in 0..N {
483 assert_eq!(reference_words[i], test_words[i], "words {} unequal", i);
484 }
485 });
486 }
487
488 #[test]
489 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
490 fn test_compress2_loop_sse41() {
491 if let Some(imp) = Implementation::sse41_if_supported() {
492 exercise_compress2_loop(imp);
493 }
494 }
495
496 #[test]
497 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
498 fn test_compress2_loop_avx2() {
499 // Currently this just falls back to SSE4.1, but we test it anyway.
500 if let Some(imp) = Implementation::avx2_if_supported() {
501 exercise_compress2_loop(imp);
502 }
503 }
504
505 // Copied from exercise_compress2_loop, with a different value of N and an
506 // interior call to compress4_loop.
507 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
508 fn exercise_compress4_loop(implementation: Implementation) {
509 const N: usize = 4;
510
511 let mut input_buffer = [0; 100 * BLOCKBYTES];
512 paint_test_input(&mut input_buffer);
513 let mut inputs = arrayvec::ArrayVec::<_, N>::new();
514 for i in 0..N {
515 inputs.push(&input_buffer[i..]);
516 }
517
518 exercise_cases(|stride, length, last_node, finalize, count| {
519 let mut reference_words = arrayvec::ArrayVec::<_, N>::new();
520 for i in 0..N {
521 let words = reference_compression(
522 &inputs[i][..length],
523 stride,
524 last_node,
525 finalize,
526 count.wrapping_add((i * BLOCKBYTES) as Count),
527 i,
528 );
529 reference_words.push(words);
530 }
531
532 let mut test_words = arrayvec::ArrayVec::<_, N>::new();
533 for i in 0..N {
534 test_words.push(initial_test_words(i));
535 }
536 let mut jobs = arrayvec::ArrayVec::<_, N>::new();
537 for (i, words) in test_words.iter_mut().enumerate() {
538 jobs.push(Job {
539 input: &inputs[i][..length],
540 words,
541 count: count.wrapping_add((i * BLOCKBYTES) as Count),
542 last_node,
543 });
544 }
545 let mut jobs = jobs.into_inner().expect("full");
546 implementation.compress4_loop(&mut jobs, finalize, stride);
547
548 for i in 0..N {
549 assert_eq!(reference_words[i], test_words[i], "words {} unequal", i);
550 }
551 });
552 }
553
554 #[test]
555 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
556 fn test_compress4_loop_avx2() {
557 if let Some(imp) = Implementation::avx2_if_supported() {
558 exercise_compress4_loop(imp);
559 }
560 }
561
562 #[test]
563 fn sanity_check_count_size() {
564 assert_eq!(size_of::<Count>(), 2 * size_of::<Word>());
565 }
566 }