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