bn_div.c revision 296465
1/* crypto/bn/bn_div.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59#include <stdio.h>
60#include <openssl/bn.h>
61#include "cryptlib.h"
62#include "bn_lcl.h"
63
64/* The old slow way */
65#if 0
66int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
67           BN_CTX *ctx)
68{
69    int i, nm, nd;
70    int ret = 0;
71    BIGNUM *D;
72
73    bn_check_top(m);
74    bn_check_top(d);
75    if (BN_is_zero(d)) {
76        BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
77        return (0);
78    }
79
80    if (BN_ucmp(m, d) < 0) {
81        if (rem != NULL) {
82            if (BN_copy(rem, m) == NULL)
83                return (0);
84        }
85        if (dv != NULL)
86            BN_zero(dv);
87        return (1);
88    }
89
90    BN_CTX_start(ctx);
91    D = BN_CTX_get(ctx);
92    if (dv == NULL)
93        dv = BN_CTX_get(ctx);
94    if (rem == NULL)
95        rem = BN_CTX_get(ctx);
96    if (D == NULL || dv == NULL || rem == NULL)
97        goto end;
98
99    nd = BN_num_bits(d);
100    nm = BN_num_bits(m);
101    if (BN_copy(D, d) == NULL)
102        goto end;
103    if (BN_copy(rem, m) == NULL)
104        goto end;
105
106    /*
107     * The next 2 are needed so we can do a dv->d[0]|=1 later since
108     * BN_lshift1 will only work once there is a value :-)
109     */
110    BN_zero(dv);
111    if (bn_wexpand(dv, 1) == NULL)
112        goto end;
113    dv->top = 1;
114
115    if (!BN_lshift(D, D, nm - nd))
116        goto end;
117    for (i = nm - nd; i >= 0; i--) {
118        if (!BN_lshift1(dv, dv))
119            goto end;
120        if (BN_ucmp(rem, D) >= 0) {
121            dv->d[0] |= 1;
122            if (!BN_usub(rem, rem, D))
123                goto end;
124        }
125/* CAN IMPROVE (and have now :=) */
126        if (!BN_rshift1(D, D))
127            goto end;
128    }
129    rem->neg = BN_is_zero(rem) ? 0 : m->neg;
130    dv->neg = m->neg ^ d->neg;
131    ret = 1;
132 end:
133    BN_CTX_end(ctx);
134    return (ret);
135}
136
137#else
138
139# if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) \
140    && !defined(PEDANTIC) && !defined(BN_DIV3W)
141#  if defined(__GNUC__) && __GNUC__>=2
142#   if defined(__i386) || defined (__i386__)
143   /*-
144    * There were two reasons for implementing this template:
145    * - GNU C generates a call to a function (__udivdi3 to be exact)
146    *   in reply to ((((BN_ULLONG)n0)<<BN_BITS2)|n1)/d0 (I fail to
147    *   understand why...);
148    * - divl doesn't only calculate quotient, but also leaves
149    *   remainder in %edx which we can definitely use here:-)
150    *
151    *                                   <appro@fy.chalmers.se>
152    */
153#    define bn_div_words(n0,n1,d0)                \
154        ({  asm volatile (                      \
155                "divl   %4"                     \
156                : "=a"(q), "=d"(rem)            \
157                : "a"(n1), "d"(n0), "g"(d0)     \
158                : "cc");                        \
159            q;                                  \
160        })
161#    define REMAINDER_IS_ALREADY_CALCULATED
162#   elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG)
163   /*
164    * Same story here, but it's 128-bit by 64-bit division. Wow!
165    *                                   <appro@fy.chalmers.se>
166    */
167#    define bn_div_words(n0,n1,d0)                \
168        ({  asm volatile (                      \
169                "divq   %4"                     \
170                : "=a"(q), "=d"(rem)            \
171                : "a"(n1), "d"(n0), "g"(d0)     \
172                : "cc");                        \
173            q;                                  \
174        })
175#    define REMAINDER_IS_ALREADY_CALCULATED
176#   endif                       /* __<cpu> */
177#  endif                        /* __GNUC__ */
178# endif                         /* OPENSSL_NO_ASM */
179
180/*-
181 * BN_div[_no_branch] computes  dv := num / divisor,  rounding towards
182 * zero, and sets up rm  such that  dv*divisor + rm = num  holds.
183 * Thus:
184 *     dv->neg == num->neg ^ divisor->neg  (unless the result is zero)
185 *     rm->neg == num->neg                 (unless the remainder is zero)
186 * If 'dv' or 'rm' is NULL, the respective value is not returned.
187 */
188static int BN_div_no_branch(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num,
189                            const BIGNUM *divisor, BN_CTX *ctx);
190int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
191           BN_CTX *ctx)
192{
193    int norm_shift, i, loop;
194    BIGNUM *tmp, wnum, *snum, *sdiv, *res;
195    BN_ULONG *resp, *wnump;
196    BN_ULONG d0, d1;
197    int num_n, div_n;
198
199    /*
200     * Invalid zero-padding would have particularly bad consequences in the
201     * case of 'num', so don't just rely on bn_check_top() for this one
202     * (bn_check_top() works only for BN_DEBUG builds)
203     */
204    if (num->top > 0 && num->d[num->top - 1] == 0) {
205        BNerr(BN_F_BN_DIV, BN_R_NOT_INITIALIZED);
206        return 0;
207    }
208
209    bn_check_top(num);
210
211    if ((BN_get_flags(num, BN_FLG_CONSTTIME) != 0)
212        || (BN_get_flags(divisor, BN_FLG_CONSTTIME) != 0)) {
213        return BN_div_no_branch(dv, rm, num, divisor, ctx);
214    }
215
216    bn_check_top(dv);
217    bn_check_top(rm);
218    /*- bn_check_top(num); *//*
219     * 'num' has been checked already
220     */
221    bn_check_top(divisor);
222
223    if (BN_is_zero(divisor)) {
224        BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
225        return (0);
226    }
227
228    if (BN_ucmp(num, divisor) < 0) {
229        if (rm != NULL) {
230            if (BN_copy(rm, num) == NULL)
231                return (0);
232        }
233        if (dv != NULL)
234            BN_zero(dv);
235        return (1);
236    }
237
238    BN_CTX_start(ctx);
239    tmp = BN_CTX_get(ctx);
240    snum = BN_CTX_get(ctx);
241    sdiv = BN_CTX_get(ctx);
242    if (dv == NULL)
243        res = BN_CTX_get(ctx);
244    else
245        res = dv;
246    if (sdiv == NULL || res == NULL || tmp == NULL || snum == NULL)
247        goto err;
248
249    /* First we normalise the numbers */
250    norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
251    if (!(BN_lshift(sdiv, divisor, norm_shift)))
252        goto err;
253    sdiv->neg = 0;
254    norm_shift += BN_BITS2;
255    if (!(BN_lshift(snum, num, norm_shift)))
256        goto err;
257    snum->neg = 0;
258    div_n = sdiv->top;
259    num_n = snum->top;
260    loop = num_n - div_n;
261    /*
262     * Lets setup a 'window' into snum This is the part that corresponds to
263     * the current 'area' being divided
264     */
265    wnum.neg = 0;
266    wnum.d = &(snum->d[loop]);
267    wnum.top = div_n;
268    /*
269     * only needed when BN_ucmp messes up the values between top and max
270     */
271    wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
272
273    /* Get the top 2 words of sdiv */
274    /* div_n=sdiv->top; */
275    d0 = sdiv->d[div_n - 1];
276    d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
277
278    /* pointer to the 'top' of snum */
279    wnump = &(snum->d[num_n - 1]);
280
281    /* Setup to 'res' */
282    res->neg = (num->neg ^ divisor->neg);
283    if (!bn_wexpand(res, (loop + 1)))
284        goto err;
285    res->top = loop;
286    resp = &(res->d[loop - 1]);
287
288    /* space for temp */
289    if (!bn_wexpand(tmp, (div_n + 1)))
290        goto err;
291
292    if (BN_ucmp(&wnum, sdiv) >= 0) {
293        /*
294         * If BN_DEBUG_RAND is defined BN_ucmp changes (via bn_pollute) the
295         * const bignum arguments => clean the values between top and max
296         * again
297         */
298        bn_clear_top2max(&wnum);
299        bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
300        *resp = 1;
301    } else
302        res->top--;
303    /*
304     * if res->top == 0 then clear the neg value otherwise decrease the resp
305     * pointer
306     */
307    if (res->top == 0)
308        res->neg = 0;
309    else
310        resp--;
311
312    for (i = 0; i < loop - 1; i++, wnump--, resp--) {
313        BN_ULONG q, l0;
314        /*
315         * the first part of the loop uses the top two words of snum and sdiv
316         * to calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv
317         */
318# if defined(BN_DIV3W) && !defined(OPENSSL_NO_ASM)
319        BN_ULONG bn_div_3_words(BN_ULONG *, BN_ULONG, BN_ULONG);
320        q = bn_div_3_words(wnump, d1, d0);
321# else
322        BN_ULONG n0, n1, rem = 0;
323
324        n0 = wnump[0];
325        n1 = wnump[-1];
326        if (n0 == d0)
327            q = BN_MASK2;
328        else {                  /* n0 < d0 */
329
330#  ifdef BN_LLONG
331            BN_ULLONG t2;
332
333#   if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words)
334            q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0);
335#   else
336            q = bn_div_words(n0, n1, d0);
337#    ifdef BN_DEBUG_LEVITTE
338            fprintf(stderr, "DEBUG: bn_div_words(0x%08X,0x%08X,0x%08\
339X) -> 0x%08X\n", n0, n1, d0, q);
340#    endif
341#   endif
342
343#   ifndef REMAINDER_IS_ALREADY_CALCULATED
344            /*
345             * rem doesn't have to be BN_ULLONG. The least we
346             * know it's less that d0, isn't it?
347             */
348            rem = (n1 - q * d0) & BN_MASK2;
349#   endif
350            t2 = (BN_ULLONG) d1 *q;
351
352            for (;;) {
353                if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | wnump[-2]))
354                    break;
355                q--;
356                rem += d0;
357                if (rem < d0)
358                    break;      /* don't let rem overflow */
359                t2 -= d1;
360            }
361#  else                         /* !BN_LLONG */
362            BN_ULONG t2l, t2h;
363#   if !defined(BN_UMULT_LOHI) && !defined(BN_UMULT_HIGH)
364            BN_ULONG ql, qh;
365#   endif
366
367            q = bn_div_words(n0, n1, d0);
368#   ifdef BN_DEBUG_LEVITTE
369            fprintf(stderr, "DEBUG: bn_div_words(0x%08X,0x%08X,0x%08\
370X) -> 0x%08X\n", n0, n1, d0, q);
371#   endif
372#   ifndef REMAINDER_IS_ALREADY_CALCULATED
373            rem = (n1 - q * d0) & BN_MASK2;
374#   endif
375
376#   if defined(BN_UMULT_LOHI)
377            BN_UMULT_LOHI(t2l, t2h, d1, q);
378#   elif defined(BN_UMULT_HIGH)
379            t2l = d1 * q;
380            t2h = BN_UMULT_HIGH(d1, q);
381#   else
382            t2l = LBITS(d1);
383            t2h = HBITS(d1);
384            ql = LBITS(q);
385            qh = HBITS(q);
386            mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */
387#   endif
388
389            for (;;) {
390                if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2])))
391                    break;
392                q--;
393                rem += d0;
394                if (rem < d0)
395                    break;      /* don't let rem overflow */
396                if (t2l < d1)
397                    t2h--;
398                t2l -= d1;
399            }
400#  endif                        /* !BN_LLONG */
401        }
402# endif                         /* !BN_DIV3W */
403
404        l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
405        tmp->d[div_n] = l0;
406        wnum.d--;
407        /*
408         * ingore top values of the bignums just sub the two BN_ULONG arrays
409         * with bn_sub_words
410         */
411        if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
412            /*
413             * Note: As we have considered only the leading two BN_ULONGs in
414             * the calculation of q, sdiv * q might be greater than wnum (but
415             * then (q-1) * sdiv is less or equal than wnum)
416             */
417            q--;
418            if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n))
419                /*
420                 * we can't have an overflow here (assuming that q != 0, but
421                 * if q == 0 then tmp is zero anyway)
422                 */
423                (*wnump)++;
424        }
425        /* store part of the result */
426        *resp = q;
427    }
428    bn_correct_top(snum);
429    if (rm != NULL) {
430        /*
431         * Keep a copy of the neg flag in num because if rm==num BN_rshift()
432         * will overwrite it.
433         */
434        int neg = num->neg;
435        BN_rshift(rm, snum, norm_shift);
436        if (!BN_is_zero(rm))
437            rm->neg = neg;
438        bn_check_top(rm);
439    }
440    BN_CTX_end(ctx);
441    return (1);
442 err:
443    bn_check_top(rm);
444    BN_CTX_end(ctx);
445    return (0);
446}
447
448/*
449 * BN_div_no_branch is a special version of BN_div. It does not contain
450 * branches that may leak sensitive information.
451 */
452static int BN_div_no_branch(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num,
453                            const BIGNUM *divisor, BN_CTX *ctx)
454{
455    int norm_shift, i, loop;
456    BIGNUM *tmp, wnum, *snum, *sdiv, *res;
457    BN_ULONG *resp, *wnump;
458    BN_ULONG d0, d1;
459    int num_n, div_n;
460
461    bn_check_top(dv);
462    bn_check_top(rm);
463    /*- bn_check_top(num); *//*
464     * 'num' has been checked in BN_div()
465     */
466    bn_check_top(divisor);
467
468    if (BN_is_zero(divisor)) {
469        BNerr(BN_F_BN_DIV_NO_BRANCH, BN_R_DIV_BY_ZERO);
470        return (0);
471    }
472
473    BN_CTX_start(ctx);
474    tmp = BN_CTX_get(ctx);
475    snum = BN_CTX_get(ctx);
476    sdiv = BN_CTX_get(ctx);
477    if (dv == NULL)
478        res = BN_CTX_get(ctx);
479    else
480        res = dv;
481    if (sdiv == NULL || res == NULL)
482        goto err;
483
484    /* First we normalise the numbers */
485    norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
486    if (!(BN_lshift(sdiv, divisor, norm_shift)))
487        goto err;
488    sdiv->neg = 0;
489    norm_shift += BN_BITS2;
490    if (!(BN_lshift(snum, num, norm_shift)))
491        goto err;
492    snum->neg = 0;
493
494    /*
495     * Since we don't know whether snum is larger than sdiv, we pad snum with
496     * enough zeroes without changing its value.
497     */
498    if (snum->top <= sdiv->top + 1) {
499        if (bn_wexpand(snum, sdiv->top + 2) == NULL)
500            goto err;
501        for (i = snum->top; i < sdiv->top + 2; i++)
502            snum->d[i] = 0;
503        snum->top = sdiv->top + 2;
504    } else {
505        if (bn_wexpand(snum, snum->top + 1) == NULL)
506            goto err;
507        snum->d[snum->top] = 0;
508        snum->top++;
509    }
510
511    div_n = sdiv->top;
512    num_n = snum->top;
513    loop = num_n - div_n;
514    /*
515     * Lets setup a 'window' into snum This is the part that corresponds to
516     * the current 'area' being divided
517     */
518    wnum.neg = 0;
519    wnum.d = &(snum->d[loop]);
520    wnum.top = div_n;
521    /*
522     * only needed when BN_ucmp messes up the values between top and max
523     */
524    wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
525
526    /* Get the top 2 words of sdiv */
527    /* div_n=sdiv->top; */
528    d0 = sdiv->d[div_n - 1];
529    d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
530
531    /* pointer to the 'top' of snum */
532    wnump = &(snum->d[num_n - 1]);
533
534    /* Setup to 'res' */
535    res->neg = (num->neg ^ divisor->neg);
536    if (!bn_wexpand(res, (loop + 1)))
537        goto err;
538    res->top = loop - 1;
539    resp = &(res->d[loop - 1]);
540
541    /* space for temp */
542    if (!bn_wexpand(tmp, (div_n + 1)))
543        goto err;
544
545    /*
546     * if res->top == 0 then clear the neg value otherwise decrease the resp
547     * pointer
548     */
549    if (res->top == 0)
550        res->neg = 0;
551    else
552        resp--;
553
554    for (i = 0; i < loop - 1; i++, wnump--, resp--) {
555        BN_ULONG q, l0;
556        /*
557         * the first part of the loop uses the top two words of snum and sdiv
558         * to calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv
559         */
560# if defined(BN_DIV3W) && !defined(OPENSSL_NO_ASM)
561        BN_ULONG bn_div_3_words(BN_ULONG *, BN_ULONG, BN_ULONG);
562        q = bn_div_3_words(wnump, d1, d0);
563# else
564        BN_ULONG n0, n1, rem = 0;
565
566        n0 = wnump[0];
567        n1 = wnump[-1];
568        if (n0 == d0)
569            q = BN_MASK2;
570        else {                  /* n0 < d0 */
571
572#  ifdef BN_LLONG
573            BN_ULLONG t2;
574
575#   if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words)
576            q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0);
577#   else
578            q = bn_div_words(n0, n1, d0);
579#    ifdef BN_DEBUG_LEVITTE
580            fprintf(stderr, "DEBUG: bn_div_words(0x%08X,0x%08X,0x%08\
581X) -> 0x%08X\n", n0, n1, d0, q);
582#    endif
583#   endif
584
585#   ifndef REMAINDER_IS_ALREADY_CALCULATED
586            /*
587             * rem doesn't have to be BN_ULLONG. The least we
588             * know it's less that d0, isn't it?
589             */
590            rem = (n1 - q * d0) & BN_MASK2;
591#   endif
592            t2 = (BN_ULLONG) d1 *q;
593
594            for (;;) {
595                if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | wnump[-2]))
596                    break;
597                q--;
598                rem += d0;
599                if (rem < d0)
600                    break;      /* don't let rem overflow */
601                t2 -= d1;
602            }
603#  else                         /* !BN_LLONG */
604            BN_ULONG t2l, t2h;
605#   if !defined(BN_UMULT_LOHI) && !defined(BN_UMULT_HIGH)
606            BN_ULONG ql, qh;
607#   endif
608
609            q = bn_div_words(n0, n1, d0);
610#   ifdef BN_DEBUG_LEVITTE
611            fprintf(stderr, "DEBUG: bn_div_words(0x%08X,0x%08X,0x%08\
612X) -> 0x%08X\n", n0, n1, d0, q);
613#   endif
614#   ifndef REMAINDER_IS_ALREADY_CALCULATED
615            rem = (n1 - q * d0) & BN_MASK2;
616#   endif
617
618#   if defined(BN_UMULT_LOHI)
619            BN_UMULT_LOHI(t2l, t2h, d1, q);
620#   elif defined(BN_UMULT_HIGH)
621            t2l = d1 * q;
622            t2h = BN_UMULT_HIGH(d1, q);
623#   else
624            t2l = LBITS(d1);
625            t2h = HBITS(d1);
626            ql = LBITS(q);
627            qh = HBITS(q);
628            mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */
629#   endif
630
631            for (;;) {
632                if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2])))
633                    break;
634                q--;
635                rem += d0;
636                if (rem < d0)
637                    break;      /* don't let rem overflow */
638                if (t2l < d1)
639                    t2h--;
640                t2l -= d1;
641            }
642#  endif                        /* !BN_LLONG */
643        }
644# endif                         /* !BN_DIV3W */
645
646        l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
647        tmp->d[div_n] = l0;
648        wnum.d--;
649        /*
650         * ingore top values of the bignums just sub the two BN_ULONG arrays
651         * with bn_sub_words
652         */
653        if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
654            /*
655             * Note: As we have considered only the leading two BN_ULONGs in
656             * the calculation of q, sdiv * q might be greater than wnum (but
657             * then (q-1) * sdiv is less or equal than wnum)
658             */
659            q--;
660            if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n))
661                /*
662                 * we can't have an overflow here (assuming that q != 0, but
663                 * if q == 0 then tmp is zero anyway)
664                 */
665                (*wnump)++;
666        }
667        /* store part of the result */
668        *resp = q;
669    }
670    bn_correct_top(snum);
671    if (rm != NULL) {
672        /*
673         * Keep a copy of the neg flag in num because if rm==num BN_rshift()
674         * will overwrite it.
675         */
676        int neg = num->neg;
677        BN_rshift(rm, snum, norm_shift);
678        if (!BN_is_zero(rm))
679            rm->neg = neg;
680        bn_check_top(rm);
681    }
682    bn_correct_top(res);
683    BN_CTX_end(ctx);
684    return (1);
685 err:
686    bn_check_top(rm);
687    BN_CTX_end(ctx);
688    return (0);
689}
690
691#endif
692