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