xref: /openbsd-src/lib/libcrypto/bn/arch/riscv64/bn_arch.h (revision c6b817c5bbc1cc7268260d27e0db2999c4e52fdc)
1 /*	$OpenBSD: bn_arch.h,v 1.7 2023/07/09 10:37:32 jsing Exp $ */
2 /*
3  * Copyright (c) 2023 Joel Sing <jsing@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <openssl/bn.h>
19 
20 #ifndef HEADER_BN_ARCH_H
21 #define HEADER_BN_ARCH_H
22 
23 #ifndef OPENSSL_NO_ASM
24 
25 #if defined(__GNUC__)
26 
27 #define HAVE_BN_ADDW
28 
29 static inline void
bn_addw(BN_ULONG a,BN_ULONG b,BN_ULONG * out_r1,BN_ULONG * out_r0)30 bn_addw(BN_ULONG a, BN_ULONG b, BN_ULONG *out_r1, BN_ULONG *out_r0)
31 {
32 	BN_ULONG carry, r0;
33 
34 	__asm__ (
35 	    "add   %[r0], %[a], %[b] \n"
36 	    "sltu  %[carry], %[r0], %[a] \n"
37 	    : [carry]"=r"(carry), [r0]"=&r"(r0)
38 	    : [a]"r"(a), [b]"r"(b));
39 
40 	*out_r1 = carry;
41 	*out_r0 = r0;
42 }
43 
44 #define HAVE_BN_MULW
45 
46 static inline void
bn_mulw(BN_ULONG a,BN_ULONG b,BN_ULONG * out_r1,BN_ULONG * out_r0)47 bn_mulw(BN_ULONG a, BN_ULONG b, BN_ULONG *out_r1, BN_ULONG *out_r0)
48 {
49 	BN_ULONG r1, r0;
50 
51 	/*
52 	 * Unsigned multiplication using a mulh/mul pair. Note that the order
53 	 * of these instructions is important, as they can potentially be fused
54 	 * into a single operation.
55 	 */
56 	__asm__ (
57 	    "mulhu %[r1], %[a], %[b] \n"
58 	    "mul   %[r0], %[a], %[b] \n"
59 	    : [r1]"=&r"(r1), [r0]"=r"(r0)
60 	    : [a]"r"(a), [b]"r"(b));
61 
62 	*out_r1 = r1;
63 	*out_r0 = r0;
64 }
65 
66 #define HAVE_BN_SUBW
67 
68 static inline void
bn_subw(BN_ULONG a,BN_ULONG b,BN_ULONG * out_borrow,BN_ULONG * out_r0)69 bn_subw(BN_ULONG a, BN_ULONG b, BN_ULONG *out_borrow, BN_ULONG *out_r0)
70 {
71 	BN_ULONG borrow, r0;
72 
73 	__asm__ (
74 	    "sub   %[r0], %[a], %[b] \n"
75 	    "sltu  %[borrow], %[a], %[r0] \n"
76 	    : [borrow]"=r"(borrow), [r0]"=&r"(r0)
77 	    : [a]"r"(a), [b]"r"(b));
78 
79 	*out_borrow = borrow;
80 	*out_r0 = r0;
81 }
82 
83 #endif /* __GNUC__ */
84 
85 #endif
86 #endif
87