1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2017 Cavium, Inc
3 * Copyright(c) Hannes Frederic Sowa
10 #include <rte_common.h>
12 #include "rte_reciprocal.h"
14 struct rte_reciprocal rte_reciprocal_value(uint32_t d)
16 struct rte_reciprocal R;
20 l = rte_fls_u32(d - 1);
21 m = ((1ULL << 32) * ((1ULL << l) - d));
26 R.sh1 = RTE_MIN(l, 1);
27 R.sh2 = RTE_MAX(l - 1, 0);
33 * Code taken from Hacker's Delight:
34 * http://www.hackersdelight.org/hdcodetxt/divlu.c.txt
35 * License permits inclusion here per:
36 * http://www.hackersdelight.org/permissions.htm
39 divide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r)
41 const uint64_t b = (1ULL << 32); /* Number base (16 bits). */
42 uint64_t un1, un0, /* Norm. dividend LSD's. */
43 vn1, vn0, /* Norm. divisor digits. */
44 q1, q0, /* Quotient digits. */
45 un64, un21, un10, /* Dividend digit pairs. */
46 rhat; /* A remainder. */
47 int s; /* Shift amount for norm. */
49 /* If overflow, set rem. to an impossible value. */
56 /* Count leading zeros. */
57 s = __builtin_clzll(v);
60 un64 = (u1 << s) | ((u0 >> (64 - s)) & (-s >> 31));
72 un0 = un10 & 0xFFFFFFFF;
77 if (q1 >= b || q1*vn0 > b*rhat + un1) {
84 un21 = un64*b + un1 - q1*v;
89 if (q0 >= b || q0*vn0 > b*rhat + un0) {
97 *r = (un21*b + un0 - q0*v) >> s;
101 struct rte_reciprocal_u64
102 rte_reciprocal_value_u64(uint64_t d)
104 struct rte_reciprocal_u64 R;
109 l = 63 - __builtin_clzll(d);
111 m = divide_128_div_64_to_64((1ULL << l), 0, d, &r) << 1;
112 if (r << 1 < r || r << 1 >= d)
114 m = (1ULL << l) - d ? m + 1 : 1;
117 R.sh1 = l > 1 ? 1 : l;
118 R.sh2 = (l > 0) ? l : 0;
119 R.sh2 -= R.sh2 && (m == 1) ? 1 : 0;