4af8bfb9a3d6320dfa5da2e0f3cafd82b698fd23
[openssl.git] / crypto / bn / bn_lcl.h
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #ifndef HEADER_BN_LCL_H
112 # define HEADER_BN_LCL_H
113
114 /*
115  * The EDK2 build doesn't use bn_conf.h; it sets THIRTY_TWO_BIT or
116  * SIXTY_FOUR_BIT in its own environment since it doesn't re-run our
117  * Configure script and needs to support both 32-bit and 64-bit.
118  */
119 # include <openssl/opensslconf.h>
120
121 # if !defined(OPENSSL_SYS_UEFI)
122 #  include "internal/bn_conf.h"
123 # endif
124
125 # include "internal/bn_int.h"
126
127 #ifdef  __cplusplus
128 extern "C" {
129 #endif
130
131 /*
132  * These preprocessor symbols control various aspects of the bignum headers
133  * and library code. They're not defined by any "normal" configuration, as
134  * they are intended for development and testing purposes. NB: defining all
135  * three can be useful for debugging application code as well as openssl
136  * itself. BN_DEBUG - turn on various debugging alterations to the bignum
137  * code BN_DEBUG_RAND - uses random poisoning of unused words to trip up
138  * mismanagement of bignum internals. You must also define BN_DEBUG.
139  */
140 /* #define BN_DEBUG */
141 /* #define BN_DEBUG_RAND */
142
143 # ifndef OPENSSL_SMALL_FOOTPRINT
144 #  define BN_MUL_COMBA
145 #  define BN_SQR_COMBA
146 #  define BN_RECURSION
147 # endif
148
149 /*
150  * This next option uses the C libraries (2 word)/(1 word) function. If it is
151  * not defined, I use my C version (which is slower). The reason for this
152  * flag is that when the particular C compiler library routine is used, and
153  * the library is linked with a different compiler, the library is missing.
154  * This mostly happens when the library is built with gcc and then linked
155  * using normal cc.  This would be a common occurrence because gcc normally
156  * produces code that is 2 times faster than system compilers for the big
157  * number stuff. For machines with only one compiler (or shared libraries),
158  * this should be on.  Again this in only really a problem on machines using
159  * "long long's", are 32bit, and are not using my assembler code.
160  */
161 # if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || \
162     defined(OPENSSL_SYS_WIN32) || defined(linux)
163 #  define BN_DIV2W
164 # endif
165
166 /*
167  * 64-bit processor with LP64 ABI
168  */
169 # ifdef SIXTY_FOUR_BIT_LONG
170 #  define BN_ULLONG       unsigned long long
171 #  define BN_BITS4        32
172 #  define BN_MASK2        (0xffffffffffffffffL)
173 #  define BN_MASK2l       (0xffffffffL)
174 #  define BN_MASK2h       (0xffffffff00000000L)
175 #  define BN_MASK2h1      (0xffffffff80000000L)
176 #  define BN_DEC_CONV     (10000000000000000000UL)
177 #  define BN_DEC_NUM      19
178 #  define BN_DEC_FMT1     "%lu"
179 #  define BN_DEC_FMT2     "%019lu"
180 # endif
181
182 /*
183  * 64-bit processor other than LP64 ABI
184  */
185 # ifdef SIXTY_FOUR_BIT
186 #  undef BN_LLONG
187 #  undef BN_ULLONG
188 #  define BN_BITS4        32
189 #  define BN_MASK2        (0xffffffffffffffffLL)
190 #  define BN_MASK2l       (0xffffffffL)
191 #  define BN_MASK2h       (0xffffffff00000000LL)
192 #  define BN_MASK2h1      (0xffffffff80000000LL)
193 #  define BN_DEC_CONV     (10000000000000000000ULL)
194 #  define BN_DEC_NUM      19
195 #  define BN_DEC_FMT1     "%llu"
196 #  define BN_DEC_FMT2     "%019llu"
197 # endif
198
199 # ifdef THIRTY_TWO_BIT
200 #  ifdef BN_LLONG
201 #   if defined(_WIN32) && !defined(__GNUC__)
202 #    define BN_ULLONG     unsigned __int64
203 #   else
204 #    define BN_ULLONG     unsigned long long
205 #   endif
206 #  endif
207 #  define BN_BITS4        16
208 #  define BN_MASK2        (0xffffffffL)
209 #  define BN_MASK2l       (0xffff)
210 #  define BN_MASK2h1      (0xffff8000L)
211 #  define BN_MASK2h       (0xffff0000L)
212 #  define BN_DEC_CONV     (1000000000L)
213 #  define BN_DEC_NUM      9
214 #  define BN_DEC_FMT1     "%u"
215 #  define BN_DEC_FMT2     "%09u"
216 # endif
217
218
219 /*-
220  * Bignum consistency macros
221  * There is one "API" macro, bn_fix_top(), for stripping leading zeroes from
222  * bignum data after direct manipulations on the data. There is also an
223  * "internal" macro, bn_check_top(), for verifying that there are no leading
224  * zeroes. Unfortunately, some auditing is required due to the fact that
225  * bn_fix_top() has become an overabused duct-tape because bignum data is
226  * occasionally passed around in an inconsistent state. So the following
227  * changes have been made to sort this out;
228  * - bn_fix_top()s implementation has been moved to bn_correct_top()
229  * - if BN_DEBUG isn't defined, bn_fix_top() maps to bn_correct_top(), and
230  *   bn_check_top() is as before.
231  * - if BN_DEBUG *is* defined;
232  *   - bn_check_top() tries to pollute unused words even if the bignum 'top' is
233  *     consistent. (ed: only if BN_DEBUG_RAND is defined)
234  *   - bn_fix_top() maps to bn_check_top() rather than "fixing" anything.
235  * The idea is to have debug builds flag up inconsistent bignums when they
236  * occur. If that occurs in a bn_fix_top(), we examine the code in question; if
237  * the use of bn_fix_top() was appropriate (ie. it follows directly after code
238  * that manipulates the bignum) it is converted to bn_correct_top(), and if it
239  * was not appropriate, we convert it permanently to bn_check_top() and track
240  * down the cause of the bug. Eventually, no internal code should be using the
241  * bn_fix_top() macro. External applications and libraries should try this with
242  * their own code too, both in terms of building against the openssl headers
243  * with BN_DEBUG defined *and* linking with a version of OpenSSL built with it
244  * defined. This not only improves external code, it provides more test
245  * coverage for openssl's own code.
246  */
247
248 # ifdef BN_DEBUG
249
250 /* We only need assert() when debugging */
251 #  include <assert.h>
252
253 #  ifdef BN_DEBUG_RAND
254 /* To avoid "make update" cvs wars due to BN_DEBUG, use some tricks */
255 #   ifndef RAND_pseudo_bytes
256 int RAND_pseudo_bytes(unsigned char *buf, int num);
257 #    define BN_DEBUG_TRIX
258 #   endif
259 #   define bn_pollute(a) \
260         do { \
261                 const BIGNUM *_bnum1 = (a); \
262                 if(_bnum1->top < _bnum1->dmax) { \
263                         unsigned char _tmp_char; \
264                         /* We cast away const without the compiler knowing, any \
265                          * *genuinely* constant variables that aren't mutable \
266                          * wouldn't be constructed with top!=dmax. */ \
267                         BN_ULONG *_not_const; \
268                         memcpy(&_not_const, &_bnum1->d, sizeof(_not_const)); \
269                         RAND_bytes(&_tmp_char, 1); /* Debug only - safe to ignore error return */\
270                         memset(_not_const + _bnum1->top, _tmp_char, \
271                                 sizeof(*_not_const) * (_bnum1->dmax - _bnum1->top)); \
272                 } \
273         } while(0)
274 #   ifdef BN_DEBUG_TRIX
275 #    undef RAND_pseudo_bytes
276 #   endif
277 #  else
278 #   define bn_pollute(a)
279 #  endif
280 #  define bn_check_top(a) \
281         do { \
282                 const BIGNUM *_bnum2 = (a); \
283                 if (_bnum2 != NULL) { \
284                         assert((_bnum2->top == 0) || \
285                                 (_bnum2->d[_bnum2->top - 1] != 0)); \
286                         bn_pollute(_bnum2); \
287                 } \
288         } while(0)
289
290 #  define bn_fix_top(a)           bn_check_top(a)
291
292 #  define bn_check_size(bn, bits) bn_wcheck_size(bn, ((bits+BN_BITS2-1))/BN_BITS2)
293 #  define bn_wcheck_size(bn, words) \
294         do { \
295                 const BIGNUM *_bnum2 = (bn); \
296                 assert((words) <= (_bnum2)->dmax && (words) >= (_bnum2)->top); \
297                 /* avoid unused variable warning with NDEBUG */ \
298                 (void)(_bnum2); \
299         } while(0)
300
301 # else                          /* !BN_DEBUG */
302
303 #  define bn_pollute(a)
304 #  define bn_check_top(a)
305 #  define bn_fix_top(a)           bn_correct_top(a)
306 #  define bn_check_size(bn, bits)
307 #  define bn_wcheck_size(bn, words)
308
309 # endif
310
311 BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num,
312                           BN_ULONG w);
313 BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w);
314 void bn_sqr_words(BN_ULONG *rp, const BN_ULONG *ap, int num);
315 BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d);
316 BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
317                       int num);
318 BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
319                       int num);
320
321 struct bignum_st {
322     BN_ULONG *d;                /* Pointer to an array of 'BN_BITS2' bit
323                                  * chunks. */
324     int top;                    /* Index of last used d +1. */
325     /* The next are internal book keeping for bn_expand. */
326     int dmax;                   /* Size of the d array. */
327     int neg;                    /* one if the number is negative */
328     int flags;
329 };
330
331 /* Used for montgomery multiplication */
332 struct bn_mont_ctx_st {
333     int ri;                     /* number of bits in R */
334     BIGNUM RR;                  /* used to convert to montgomery form */
335     BIGNUM N;                   /* The modulus */
336     BIGNUM Ni;                  /* R*(1/R mod N) - N*Ni = 1 (Ni is only
337                                  * stored for bignum algorithm) */
338     BN_ULONG n0[2];             /* least significant word(s) of Ni; (type
339                                  * changed with 0.9.9, was "BN_ULONG n0;"
340                                  * before) */
341     int flags;
342 };
343
344 /*
345  * Used for reciprocal division/mod functions It cannot be shared between
346  * threads
347  */
348 struct bn_recp_ctx_st {
349     BIGNUM N;                   /* the divisor */
350     BIGNUM Nr;                  /* the reciprocal */
351     int num_bits;
352     int shift;
353     int flags;
354 };
355
356 /* Used for slow "generation" functions. */
357 struct bn_gencb_st {
358     unsigned int ver;           /* To handle binary (in)compatibility */
359     void *arg;                  /* callback-specific data */
360     union {
361         /* if(ver==1) - handles old style callbacks */
362         void (*cb_1) (int, int, void *);
363         /* if(ver==2) - new callback style */
364         int (*cb_2) (int, int, BN_GENCB *);
365     } cb;
366 };
367
368 /*-
369  * BN_window_bits_for_exponent_size -- macro for sliding window mod_exp functions
370  *
371  *
372  * For window size 'w' (w >= 2) and a random 'b' bits exponent,
373  * the number of multiplications is a constant plus on average
374  *
375  *    2^(w-1) + (b-w)/(w+1);
376  *
377  * here  2^(w-1)  is for precomputing the table (we actually need
378  * entries only for windows that have the lowest bit set), and
379  * (b-w)/(w+1)  is an approximation for the expected number of
380  * w-bit windows, not counting the first one.
381  *
382  * Thus we should use
383  *
384  *    w >= 6  if        b > 671
385  *     w = 5  if  671 > b > 239
386  *     w = 4  if  239 > b >  79
387  *     w = 3  if   79 > b >  23
388  *    w <= 2  if   23 > b
389  *
390  * (with draws in between).  Very small exponents are often selected
391  * with low Hamming weight, so we use  w = 1  for b <= 23.
392  */
393 # define BN_window_bits_for_exponent_size(b) \
394                 ((b) > 671 ? 6 : \
395                  (b) > 239 ? 5 : \
396                  (b) >  79 ? 4 : \
397                  (b) >  23 ? 3 : 1)
398
399 /*
400  * BN_mod_exp_mont_conttime is based on the assumption that the L1 data cache
401  * line width of the target processor is at least the following value.
402  */
403 # define MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH      ( 64 )
404 # define MOD_EXP_CTIME_MIN_CACHE_LINE_MASK       (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - 1)
405
406 /*
407  * Window sizes optimized for fixed window size modular exponentiation
408  * algorithm (BN_mod_exp_mont_consttime). To achieve the security goals of
409  * BN_mode_exp_mont_consttime, the maximum size of the window must not exceed
410  * log_2(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH). Window size thresholds are
411  * defined for cache line sizes of 32 and 64, cache line sizes where
412  * log_2(32)=5 and log_2(64)=6 respectively. A window size of 7 should only be
413  * used on processors that have a 128 byte or greater cache line size.
414  */
415 # if MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 64
416
417 #  define BN_window_bits_for_ctime_exponent_size(b) \
418                 ((b) > 937 ? 6 : \
419                  (b) > 306 ? 5 : \
420                  (b) >  89 ? 4 : \
421                  (b) >  22 ? 3 : 1)
422 #  define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE    (6)
423
424 # elif MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 32
425
426 #  define BN_window_bits_for_ctime_exponent_size(b) \
427                 ((b) > 306 ? 5 : \
428                  (b) >  89 ? 4 : \
429                  (b) >  22 ? 3 : 1)
430 #  define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE    (5)
431
432 # endif
433
434 /* Pentium pro 16,16,16,32,64 */
435 /* Alpha       16,16,16,16.64 */
436 # define BN_MULL_SIZE_NORMAL                     (16)/* 32 */
437 # define BN_MUL_RECURSIVE_SIZE_NORMAL            (16)/* 32 less than */
438 # define BN_SQR_RECURSIVE_SIZE_NORMAL            (16)/* 32 */
439 # define BN_MUL_LOW_RECURSIVE_SIZE_NORMAL        (32)/* 32 */
440 # define BN_MONT_CTX_SET_SIZE_WORD               (64)/* 32 */
441
442 /*
443  * 2011-02-22 SMS. In various places, a size_t variable or a type cast to
444  * size_t was used to perform integer-only operations on pointers.  This
445  * failed on VMS with 64-bit pointers (CC /POINTER_SIZE = 64) because size_t
446  * is still only 32 bits.  What's needed in these cases is an integer type
447  * with the same size as a pointer, which size_t is not certain to be. The
448  * only fix here is VMS-specific.
449  */
450 # if defined(OPENSSL_SYS_VMS)
451 #  if __INITIAL_POINTER_SIZE == 64
452 #   define PTR_SIZE_INT long long
453 #  else                         /* __INITIAL_POINTER_SIZE == 64 */
454 #   define PTR_SIZE_INT int
455 #  endif                        /* __INITIAL_POINTER_SIZE == 64 [else] */
456 # elif !defined(PTR_SIZE_INT)   /* defined(OPENSSL_SYS_VMS) */
457 #  define PTR_SIZE_INT size_t
458 # endif                         /* defined(OPENSSL_SYS_VMS) [else] */
459
460 # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) && !defined(PEDANTIC)
461 /*
462  * BN_UMULT_HIGH section.
463  *
464  * No, I'm not trying to overwhelm you when stating that the
465  * product of N-bit numbers is 2*N bits wide:-) No, I don't expect
466  * you to be impressed when I say that if the compiler doesn't
467  * support 2*N integer type, then you have to replace every N*N
468  * multiplication with 4 (N/2)*(N/2) accompanied by some shifts
469  * and additions which unavoidably results in severe performance
470  * penalties. Of course provided that the hardware is capable of
471  * producing 2*N result... That's when you normally start
472  * considering assembler implementation. However! It should be
473  * pointed out that some CPUs (most notably Alpha, PowerPC and
474  * upcoming IA-64 family:-) provide *separate* instruction
475  * calculating the upper half of the product placing the result
476  * into a general purpose register. Now *if* the compiler supports
477  * inline assembler, then it's not impossible to implement the
478  * "bignum" routines (and have the compiler optimize 'em)
479  * exhibiting "native" performance in C. That's what BN_UMULT_HIGH
480  * macro is about:-)
481  *
482  *                                      <appro@fy.chalmers.se>
483  */
484 #  if defined(__alpha) && (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT))
485 #   if defined(__DECC)
486 #    include <c_asm.h>
487 #    define BN_UMULT_HIGH(a,b)   (BN_ULONG)asm("umulh %a0,%a1,%v0",(a),(b))
488 #   elif defined(__GNUC__) && __GNUC__>=2
489 #    define BN_UMULT_HIGH(a,b)   ({      \
490         register BN_ULONG ret;          \
491         asm ("umulh     %1,%2,%0"       \
492              : "=r"(ret)                \
493              : "r"(a), "r"(b));         \
494         ret;                    })
495 #   endif                       /* compiler */
496 #  elif defined(_ARCH_PPC) && defined(__64BIT__) && defined(SIXTY_FOUR_BIT_LONG)
497 #   if defined(__GNUC__) && __GNUC__>=2
498 #    define BN_UMULT_HIGH(a,b)   ({      \
499         register BN_ULONG ret;          \
500         asm ("mulhdu    %0,%1,%2"       \
501              : "=r"(ret)                \
502              : "r"(a), "r"(b));         \
503         ret;                    })
504 #   endif                       /* compiler */
505 #  elif (defined(__x86_64) || defined(__x86_64__)) && \
506        (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT))
507 #   if defined(__GNUC__) && __GNUC__>=2
508 #    define BN_UMULT_HIGH(a,b)   ({      \
509         register BN_ULONG ret,discard;  \
510         asm ("mulq      %3"             \
511              : "=a"(discard),"=d"(ret)  \
512              : "a"(a), "g"(b)           \
513              : "cc");                   \
514         ret;                    })
515 #    define BN_UMULT_LOHI(low,high,a,b)  \
516         asm ("mulq      %3"             \
517                 : "=a"(low),"=d"(high)  \
518                 : "a"(a),"g"(b)         \
519                 : "cc");
520 #   endif
521 #  elif (defined(_M_AMD64) || defined(_M_X64)) && defined(SIXTY_FOUR_BIT)
522 #   if defined(_MSC_VER) && _MSC_VER>=1400
523 unsigned __int64 __umulh(unsigned __int64 a, unsigned __int64 b);
524 unsigned __int64 _umul128(unsigned __int64 a, unsigned __int64 b,
525                           unsigned __int64 *h);
526 #    pragma intrinsic(__umulh,_umul128)
527 #    define BN_UMULT_HIGH(a,b)           __umulh((a),(b))
528 #    define BN_UMULT_LOHI(low,high,a,b)  ((low)=_umul128((a),(b),&(high)))
529 #   endif
530 #  elif defined(__mips) && (defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG))
531 #   if defined(__GNUC__) && __GNUC__>=2
532 #    if __GNUC__>4 || (__GNUC__>=4 && __GNUC_MINOR__>=4)
533                                      /* "h" constraint is no more since 4.4 */
534 #     define BN_UMULT_HIGH(a,b)          (((__uint128_t)(a)*(b))>>64)
535 #     define BN_UMULT_LOHI(low,high,a,b) ({     \
536         __uint128_t ret=(__uint128_t)(a)*(b);   \
537         (high)=ret>>64; (low)=ret;       })
538 #    else
539 #     define BN_UMULT_HIGH(a,b) ({      \
540         register BN_ULONG ret;          \
541         asm ("dmultu    %1,%2"          \
542              : "=h"(ret)                \
543              : "r"(a), "r"(b) : "l");   \
544         ret;                    })
545 #     define BN_UMULT_LOHI(low,high,a,b)\
546         asm ("dmultu    %2,%3"          \
547              : "=l"(low),"=h"(high)     \
548              : "r"(a), "r"(b));
549 #    endif
550 #   endif
551 #  elif defined(__aarch64__) && defined(SIXTY_FOUR_BIT_LONG)
552 #   if defined(__GNUC__) && __GNUC__>=2
553 #    define BN_UMULT_HIGH(a,b)   ({      \
554         register BN_ULONG ret;          \
555         asm ("umulh     %0,%1,%2"       \
556              : "=r"(ret)                \
557              : "r"(a), "r"(b));         \
558         ret;                    })
559 #   endif
560 #  endif                        /* cpu */
561 # endif                         /* OPENSSL_NO_ASM */
562
563 /*************************************************************
564  * Using the long long type
565  */
566 # define Lw(t)    (((BN_ULONG)(t))&BN_MASK2)
567 # define Hw(t)    (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2)
568
569 # ifdef BN_DEBUG_RAND
570 #  define bn_clear_top2max(a) \
571         { \
572         int      ind = (a)->dmax - (a)->top; \
573         BN_ULONG *ftl = &(a)->d[(a)->top-1]; \
574         for (; ind != 0; ind--) \
575                 *(++ftl) = 0x0; \
576         }
577 # else
578 #  define bn_clear_top2max(a)
579 # endif
580
581 # ifdef BN_LLONG
582 #  define mul_add(r,a,w,c) { \
583         BN_ULLONG t; \
584         t=(BN_ULLONG)w * (a) + (r) + (c); \
585         (r)= Lw(t); \
586         (c)= Hw(t); \
587         }
588
589 #  define mul(r,a,w,c) { \
590         BN_ULLONG t; \
591         t=(BN_ULLONG)w * (a) + (c); \
592         (r)= Lw(t); \
593         (c)= Hw(t); \
594         }
595
596 #  define sqr(r0,r1,a) { \
597         BN_ULLONG t; \
598         t=(BN_ULLONG)(a)*(a); \
599         (r0)=Lw(t); \
600         (r1)=Hw(t); \
601         }
602
603 # elif defined(BN_UMULT_LOHI)
604 #  define mul_add(r,a,w,c) {              \
605         BN_ULONG high,low,ret,tmp=(a);  \
606         ret =  (r);                     \
607         BN_UMULT_LOHI(low,high,w,tmp);  \
608         ret += (c);                     \
609         (c) =  (ret<(c))?1:0;           \
610         (c) += high;                    \
611         ret += low;                     \
612         (c) += (ret<low)?1:0;           \
613         (r) =  ret;                     \
614         }
615
616 #  define mul(r,a,w,c)    {               \
617         BN_ULONG high,low,ret,ta=(a);   \
618         BN_UMULT_LOHI(low,high,w,ta);   \
619         ret =  low + (c);               \
620         (c) =  high;                    \
621         (c) += (ret<low)?1:0;           \
622         (r) =  ret;                     \
623         }
624
625 #  define sqr(r0,r1,a)    {               \
626         BN_ULONG tmp=(a);               \
627         BN_UMULT_LOHI(r0,r1,tmp,tmp);   \
628         }
629
630 # elif defined(BN_UMULT_HIGH)
631 #  define mul_add(r,a,w,c) {              \
632         BN_ULONG high,low,ret,tmp=(a);  \
633         ret =  (r);                     \
634         high=  BN_UMULT_HIGH(w,tmp);    \
635         ret += (c);                     \
636         low =  (w) * tmp;               \
637         (c) =  (ret<(c))?1:0;           \
638         (c) += high;                    \
639         ret += low;                     \
640         (c) += (ret<low)?1:0;           \
641         (r) =  ret;                     \
642         }
643
644 #  define mul(r,a,w,c)    {               \
645         BN_ULONG high,low,ret,ta=(a);   \
646         low =  (w) * ta;                \
647         high=  BN_UMULT_HIGH(w,ta);     \
648         ret =  low + (c);               \
649         (c) =  high;                    \
650         (c) += (ret<low)?1:0;           \
651         (r) =  ret;                     \
652         }
653
654 #  define sqr(r0,r1,a)    {               \
655         BN_ULONG tmp=(a);               \
656         (r0) = tmp * tmp;               \
657         (r1) = BN_UMULT_HIGH(tmp,tmp);  \
658         }
659
660 # else
661 /*************************************************************
662  * No long long type
663  */
664
665 #  define LBITS(a)        ((a)&BN_MASK2l)
666 #  define HBITS(a)        (((a)>>BN_BITS4)&BN_MASK2l)
667 #  define L2HBITS(a)      (((a)<<BN_BITS4)&BN_MASK2)
668
669 #  define LLBITS(a)       ((a)&BN_MASKl)
670 #  define LHBITS(a)       (((a)>>BN_BITS2)&BN_MASKl)
671 #  define LL2HBITS(a)     ((BN_ULLONG)((a)&BN_MASKl)<<BN_BITS2)
672
673 #  define mul64(l,h,bl,bh) \
674         { \
675         BN_ULONG m,m1,lt,ht; \
676  \
677         lt=l; \
678         ht=h; \
679         m =(bh)*(lt); \
680         lt=(bl)*(lt); \
681         m1=(bl)*(ht); \
682         ht =(bh)*(ht); \
683         m=(m+m1)&BN_MASK2; if (m < m1) ht+=L2HBITS((BN_ULONG)1); \
684         ht+=HBITS(m); \
685         m1=L2HBITS(m); \
686         lt=(lt+m1)&BN_MASK2; if (lt < m1) ht++; \
687         (l)=lt; \
688         (h)=ht; \
689         }
690
691 #  define sqr64(lo,ho,in) \
692         { \
693         BN_ULONG l,h,m; \
694  \
695         h=(in); \
696         l=LBITS(h); \
697         h=HBITS(h); \
698         m =(l)*(h); \
699         l*=l; \
700         h*=h; \
701         h+=(m&BN_MASK2h1)>>(BN_BITS4-1); \
702         m =(m&BN_MASK2l)<<(BN_BITS4+1); \
703         l=(l+m)&BN_MASK2; if (l < m) h++; \
704         (lo)=l; \
705         (ho)=h; \
706         }
707
708 #  define mul_add(r,a,bl,bh,c) { \
709         BN_ULONG l,h; \
710  \
711         h= (a); \
712         l=LBITS(h); \
713         h=HBITS(h); \
714         mul64(l,h,(bl),(bh)); \
715  \
716         /* non-multiply part */ \
717         l=(l+(c))&BN_MASK2; if (l < (c)) h++; \
718         (c)=(r); \
719         l=(l+(c))&BN_MASK2; if (l < (c)) h++; \
720         (c)=h&BN_MASK2; \
721         (r)=l; \
722         }
723
724 #  define mul(r,a,bl,bh,c) { \
725         BN_ULONG l,h; \
726  \
727         h= (a); \
728         l=LBITS(h); \
729         h=HBITS(h); \
730         mul64(l,h,(bl),(bh)); \
731  \
732         /* non-multiply part */ \
733         l+=(c); if ((l&BN_MASK2) < (c)) h++; \
734         (c)=h&BN_MASK2; \
735         (r)=l&BN_MASK2; \
736         }
737 # endif                         /* !BN_LLONG */
738
739 void BN_RECP_CTX_init(BN_RECP_CTX *recp);
740 void BN_MONT_CTX_init(BN_MONT_CTX *ctx);
741
742 void bn_init(BIGNUM *a);
743 void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb);
744 void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
745 void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
746 void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, int n, BN_ULONG *tmp);
747 void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a);
748 void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a);
749 int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n);
750 int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl);
751 void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2,
752                       int dna, int dnb, BN_ULONG *t);
753 void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b,
754                            int n, int tna, int tnb, BN_ULONG *t);
755 void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t);
756 void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n);
757 void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2,
758                           BN_ULONG *t);
759 void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2,
760                  BN_ULONG *t);
761 BN_ULONG bn_add_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
762                            int cl, int dl);
763 BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
764                            int cl, int dl);
765 int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
766                 const BN_ULONG *np, const BN_ULONG *n0, int num);
767
768 BIGNUM *int_bn_mod_inverse(BIGNUM *in,
769                            const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx,
770                            int *noinv);
771
772 int bn_probable_prime_dh(BIGNUM *rnd, int bits,
773                          const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx);
774 int bn_probable_prime_dh_retry(BIGNUM *rnd, int bits, BN_CTX *ctx);
775 int bn_probable_prime_dh_coprime(BIGNUM *rnd, int bits, BN_CTX *ctx);
776
777 #ifdef  __cplusplus
778 }
779 #endif
780
781 #endif