Debian Codegraph @

debian/rust-vendor/sha2/src/sha256/riscv_zknh/utils.rs

raw
1 use core::{arch::asm, ptr};
2
3 #[inline(always)]
4 pub(super) fn load_block(block: &[u8; 64]) -> [u32; 16] {
5 if block.as_ptr().cast::<u32>().is_aligned() {
6 load_aligned_block(block)
7 } else {
8 load_unaligned_block(block)
9 }
10 }
11
12 #[inline(always)]
13 fn load_aligned_block(block: &[u8; 64]) -> [u32; 16] {
14 let p: *const u32 = block.as_ptr().cast();
15 debug_assert!(p.is_aligned());
16 let mut res = [0u32; 16];
17 for i in 0..16 {
18 let val = unsafe { ptr::read(p.add(i)) };
19 res[i] = val.to_be();
20 }
21 res
22 }
23
24 /// Use LW instruction on RV32 and LWU on RV64
25 #[cfg(target_arch = "riscv32")]
26 macro_rules! lw {
27 ($r:literal) => {
28 concat!("lw ", $r)
29 };
30 }
31 #[cfg(target_arch = "riscv64")]
32 macro_rules! lw {
33 ($r:literal) => {
34 concat!("lwu ", $r)
35 };
36 }
37
38 #[inline(always)]
39 fn load_unaligned_block(block: &[u8; 64]) -> [u32; 16] {
40 let offset = (block.as_ptr() as usize) % align_of::<u32>();
41 debug_assert_ne!(offset, 0);
42 let off1 = (8 * offset) % 32;
43 let off2 = (32 - off1) % 32;
44 let bp: *const u32 = block.as_ptr().wrapping_sub(offset).cast();
45
46 let mut left: u32;
47 let mut res = [0u32; 16];
48
49 unsafe {
50 asm!(
51 lw!("{left}, 0({bp})"), // left = unsafe { ptr::read(bp) };
52 "srl {left}, {left}, {off1}", // left >>= off1;
53 bp = in(reg) bp,
54 off1 = in(reg) off1,
55 left = out(reg) left,
56 options(pure, nostack, readonly, preserves_flags),
57 );
58 }
59
60 for i in 0..15 {
61 let right = unsafe { ptr::read(bp.add(1 + i)) };
62 res[i] = (left | (right << off2)).to_be();
63 left = right >> off1;
64 }
65
66 let right: u32;
67 unsafe {
68 asm!(
69 lw!("{right}, 16 * 4({bp})"), // right = ptr::read(bp.add(16));
70 "sll {right}, {right}, {off2}", // right <<= off2;
71 bp = in(reg) bp,
72 off2 = in(reg) off2,
73 right = out(reg) right,
74 options(pure, nostack, readonly, preserves_flags),
75 );
76 }
77 res[15] = (left | right).to_be();
78
79 res
80 }
81
82 /// This function returns `k[R]`, but prevents compiler from inlining the indexed value
83 #[cfg(not(sha2_backend_riscv_zknh = "compact"))]
84 pub(super) fn opaque_load<const R: usize>(k: &[u32]) -> u32 {
85 assert!(R < k.len());
86 let dst;
87 unsafe {
88 core::arch::asm!(
89 lw!("{dst}, 4*{R}({k})"),
90 R = const R,
91 k = in(reg) k.as_ptr(),
92 dst = out(reg) dst,
93 options(pure, readonly, nostack, preserves_flags),
94 );
95 }
96 dst
97 }