Debian Codegraph @

debian/rust-vendor/chacha20/src/backends/neon.rs

raw
1 //! NEON-optimized implementation for aarch64 CPUs.
2 //!
3 //! Adapted from the Crypto++ `chacha_simd` implementation by Jack Lloyd and
4 //! Jeffrey Walton (public domain), but uses **8-block** outer batches for
5 //! bulk paths (see `ChaCha20_512_neon` in OpenSSL).
6
7 #![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
8
9 use crate::{Rounds, STATE_WORDS, Variant};
10 use core::{arch::aarch64::*, marker::PhantomData};
11
12 #[cfg(feature = "rng")]
13 use crate::ChaChaCore;
14
15 #[cfg(feature = "cipher")]
16 use crate::chacha::Block;
17
18 #[cfg(feature = "cipher")]
19 use cipher::{
20 BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
21 consts::{U8, U64},
22 };
23
24 struct Backend<R: Rounds, V: Variant> {
25 state: [uint32x4_t; 4],
26 ctrs: [uint32x4_t; 8],
27 _pd: PhantomData<(R, V)>,
28 }
29
30 macro_rules! add_counter {
31 ($a:expr, $b:expr, $variant:ty) => {
32 match size_of::<<$variant>::Counter>() {
33 4 => vaddq_u32($a, $b),
34 8 => vreinterpretq_u32_u64(vaddq_u64(
35 vreinterpretq_u64_u32($a),
36 vreinterpretq_u64_u32($b),
37 )),
38 _ => unreachable!(),
39 }
40 };
41 }
42
43 impl<R: Rounds, V: Variant> Backend<R, V> {
44 #[inline]
45 unsafe fn new(state: &mut [u32; STATE_WORDS]) -> Self {
46 let state = [
47 vld1q_u32(state.as_ptr().offset(0)),
48 vld1q_u32(state.as_ptr().offset(4)),
49 vld1q_u32(state.as_ptr().offset(8)),
50 vld1q_u32(state.as_ptr().offset(12)),
51 ];
52 let ctrs = [
53 vld1q_u32([1, 0, 0, 0].as_ptr()),
54 vld1q_u32([2, 0, 0, 0].as_ptr()),
55 vld1q_u32([3, 0, 0, 0].as_ptr()),
56 vld1q_u32([4, 0, 0, 0].as_ptr()),
57 vld1q_u32([5, 0, 0, 0].as_ptr()),
58 vld1q_u32([6, 0, 0, 0].as_ptr()),
59 vld1q_u32([7, 0, 0, 0].as_ptr()),
60 vld1q_u32([8, 0, 0, 0].as_ptr()),
61 ];
62 Backend::<R, V> {
63 state,
64 ctrs,
65 _pd: PhantomData,
66 }
67 }
68 }
69
70 #[inline]
71 #[cfg(feature = "cipher")]
72 #[target_feature(enable = "neon")]
73 pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
74 where
75 R: Rounds,
76 F: StreamCipherClosure<BlockSize = U64>,
77 V: Variant,
78 {
79 let mut backend = Backend::<R, V>::new(state);
80
81 f.call(&mut backend);
82
83 match size_of::<V::Counter>() {
84 4 => state[12] = vgetq_lane_u32(backend.state[3], 0),
85 8 => vst1q_u64(
86 state.as_mut_ptr().offset(12).cast::<u64>(),
87 vreinterpretq_u64_u32(backend.state[3]),
88 ),
89 _ => unreachable!(),
90 }
91 }
92
93 /// Sets up backend and blindly writes 4 blocks to dest_ptr.
94 #[cfg(feature = "rng")]
95 #[inline]
96 #[target_feature(enable = "neon")]
97 pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
98 where
99 R: Rounds,
100 V: Variant,
101 {
102 let mut backend = Backend::<R, V>::new(&mut core.state);
103
104 backend.write_par_ks_blocks(buffer);
105
106 vst1q_u64(
107 core.state.as_mut_ptr().offset(12).cast::<u64>(),
108 vreinterpretq_u64_u32(backend.state[3]),
109 );
110 }
111
112 #[cfg(feature = "cipher")]
113 impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
114 type BlockSize = U64;
115 }
116 #[cfg(feature = "cipher")]
117 impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
118 /// Match OpenSSL's large-buffer path: 8 blocks
119 type ParBlocksSize = U8;
120 }
121
122 /// Evaluates to `a = a + b`, where the operands are u32x4s
123 macro_rules! add_assign_vec {
124 ($a:expr, $b:expr) => {
125 $a = vaddq_u32($a, $b)
126 };
127 }
128
129 #[cfg(feature = "cipher")]
130 impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
131 #[inline(always)]
132 fn gen_ks_block(&mut self, block: &mut Block) {
133 let state3 = self.state[3];
134 let mut par = ParBlocks::<Self>::default();
135 self.gen_par_ks_blocks(&mut par);
136 *block = par[0];
137
138 // SAFETY: we have used conditional compilation to ensure NEON is available
139 unsafe {
140 self.state[3] = add_counter!(state3, vld1q_u32([1, 0, 0, 0].as_ptr()), V);
141 }
142 }
143
144 #[inline(always)]
145 fn gen_par_ks_blocks(&mut self, dest: &mut ParBlocks<Self>) {
146 // SAFETY: we have used conditional compilation to ensure NEON is available
147 unsafe {
148 let mut blocks = [
149 [self.state[0], self.state[1], self.state[2], self.state[3]],
150 [
151 self.state[0],
152 self.state[1],
153 self.state[2],
154 add_counter!(self.state[3], self.ctrs[0], V),
155 ],
156 [
157 self.state[0],
158 self.state[1],
159 self.state[2],
160 add_counter!(self.state[3], self.ctrs[1], V),
161 ],
162 [
163 self.state[0],
164 self.state[1],
165 self.state[2],
166 add_counter!(self.state[3], self.ctrs[2], V),
167 ],
168 [
169 self.state[0],
170 self.state[1],
171 self.state[2],
172 add_counter!(self.state[3], self.ctrs[3], V),
173 ],
174 [
175 self.state[0],
176 self.state[1],
177 self.state[2],
178 add_counter!(self.state[3], self.ctrs[4], V),
179 ],
180 [
181 self.state[0],
182 self.state[1],
183 self.state[2],
184 add_counter!(self.state[3], self.ctrs[5], V),
185 ],
186 [
187 self.state[0],
188 self.state[1],
189 self.state[2],
190 add_counter!(self.state[3], self.ctrs[6], V),
191 ],
192 ];
193
194 for _ in 0..R::COUNT {
195 double_quarter_round(&mut blocks);
196 }
197
198 for block in 0..8 {
199 // add state to block
200 for state_row in 0..3 {
201 add_assign_vec!(blocks[block][state_row], self.state[state_row]);
202 }
203 if block > 0 {
204 add_assign_vec!(
205 blocks[block][3],
206 add_counter!(self.state[3], self.ctrs[block - 1], V)
207 );
208 } else {
209 add_assign_vec!(blocks[block][3], self.state[3]);
210 }
211 // write blocks to dest
212 for state_row in 0..4 {
213 vst1q_u8(
214 dest[block].as_mut_ptr().add(state_row << 4),
215 vreinterpretq_u8_u32(blocks[block][state_row]),
216 );
217 }
218 }
219 self.state[3] = add_counter!(self.state[3], self.ctrs[7], V);
220 }
221 }
222 }
223
224 macro_rules! rotate_left {
225 ($v:expr, 8) => {{
226 let maskb = [3u8, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14];
227 let mask = vld1q_u8(maskb.as_ptr());
228
229 $v = vreinterpretq_u32_u8(vqtbl1q_u8(vreinterpretq_u8_u32($v), mask))
230 }};
231 ($v:expr, 16) => {
232 $v = vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32($v)))
233 };
234 ($v:expr, $r:literal) => {
235 $v = vorrq_u32(vshlq_n_u32($v, $r), vshrq_n_u32($v, 32 - $r))
236 };
237 }
238
239 macro_rules! extract {
240 ($v:expr, $s:literal) => {
241 $v = vextq_u32($v, $v, $s)
242 };
243 }
244
245 impl<R: Rounds, V: Variant> Backend<R, V> {
246 #[inline(always)]
247 /// Generates `num_blocks` blocks and blindly writes them to `dest_ptr`
248 ///
249 /// `num_blocks` must be greater than 0, and less than or equal to 4.
250 ///
251 /// # Safety
252 /// `dest_ptr` must have at least `64 * num_blocks` bytes available to be
253 /// overwritten, or else it could produce undefined behavior
254 #[cfg(feature = "rng")]
255 unsafe fn write_par_ks_blocks(&mut self, buffer: &mut [u32; 64]) {
256 let mut blocks = [
257 [self.state[0], self.state[1], self.state[2], self.state[3]],
258 [
259 self.state[0],
260 self.state[1],
261 self.state[2],
262 add_counter!(self.state[3], self.ctrs[0], V),
263 ],
264 [
265 self.state[0],
266 self.state[1],
267 self.state[2],
268 add_counter!(self.state[3], self.ctrs[1], V),
269 ],
270 [
271 self.state[0],
272 self.state[1],
273 self.state[2],
274 add_counter!(self.state[3], self.ctrs[2], V),
275 ],
276 ];
277
278 for _ in 0..R::COUNT {
279 double_quarter_round(&mut blocks);
280 }
281
282 let mut dest_ptr = buffer.as_mut_ptr().cast::<u8>();
283 for block in 0..4 {
284 // add state to block
285 for state_row in 0..3 {
286 add_assign_vec!(blocks[block][state_row], self.state[state_row]);
287 }
288 if block > 0 {
289 add_assign_vec!(
290 blocks[block][3],
291 add_counter!(self.state[3], self.ctrs[block - 1], V)
292 );
293 } else {
294 add_assign_vec!(blocks[block][3], self.state[3]);
295 }
296 // write blocks to buffer
297 for state_row in 0..4 {
298 #[allow(clippy::cast_sign_loss)]
299 vst1q_u8(
300 dest_ptr.offset(state_row << 4),
301 vreinterpretq_u8_u32(blocks[block][state_row as usize]),
302 );
303 }
304 dest_ptr = dest_ptr.add(64);
305 }
306 self.state[3] = add_counter!(self.state[3], self.ctrs[3], V);
307 }
308 }
309
310 #[inline]
311 unsafe fn double_quarter_round<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
312 add_xor_rot(blocks);
313 rows_to_cols(blocks);
314 add_xor_rot(blocks);
315 cols_to_rows(blocks);
316 }
317
318 #[inline]
319 unsafe fn add_xor_rot<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
320 /// Evaluates to `a = a ^ b`, where the operands are u32x4s
321 macro_rules! xor_assign_vec {
322 ($a:expr, $b:expr) => {
323 $a = veorq_u32($a, $b)
324 };
325 }
326 for block in blocks.iter_mut() {
327 // this part of the code cannot be reduced much more without having
328 // to deal with some problems regarding `rotate_left` requiring the second
329 // argument to be a const, and const arrays cannot be indexed by non-consts
330 add_assign_vec!(block[0], block[1]);
331 xor_assign_vec!(block[3], block[0]);
332 rotate_left!(block[3], 16);
333
334 add_assign_vec!(block[2], block[3]);
335 xor_assign_vec!(block[1], block[2]);
336 rotate_left!(block[1], 12);
337
338 add_assign_vec!(block[0], block[1]);
339 xor_assign_vec!(block[3], block[0]);
340 rotate_left!(block[3], 8);
341
342 add_assign_vec!(block[2], block[3]);
343 xor_assign_vec!(block[1], block[2]);
344 rotate_left!(block[1], 7);
345 }
346 }
347
348 #[inline]
349 unsafe fn rows_to_cols<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
350 for block in blocks.iter_mut() {
351 extract!(block[1], 1);
352 extract!(block[2], 2);
353 extract!(block[3], 3);
354 }
355 }
356
357 #[inline]
358 unsafe fn cols_to_rows<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
359 for block in blocks.iter_mut() {
360 extract!(block[1], 3);
361 extract!(block[2], 2);
362 extract!(block[3], 1);
363 }
364 }