1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2017 Cavium, Inc
7 * Used with permission from original authors
8 * Hannes Frederic Sowa and Daniel Borkmann
10 * This algorithm is based on the paper "Division by Invariant
11 * Integers Using Multiplication" by Torbjörn Granlund and Peter
14 * The assembler implementation from Agner Fog, which this code is
15 * based on, can be found here:
16 * http://www.agner.org/optimize/asmlib.zip
18 * This optimization for A/B is helpful if the divisor B is mostly
19 * runtime invariant. The reciprocal of B is calculated in the
20 * slow-path with reciprocal_value(). The fast-path can then just use
21 * a much faster multiplication operation with a variable dividend A
22 * to calculate the division A/B.
25 #ifndef _RTE_RECIPROCAL_H_
26 #define _RTE_RECIPROCAL_H_
30 #include <rte_common.h>
36 struct rte_reciprocal {
41 struct rte_reciprocal_u64 {
46 static inline uint32_t rte_reciprocal_divide(uint32_t a, struct rte_reciprocal R)
48 uint32_t t = (uint32_t)(((uint64_t)a * R.m) >> 32);
50 return (t + ((a - t) >> R.sh1)) >> R.sh2;
53 static __rte_always_inline uint64_t
54 mullhi_u64(uint64_t x, uint64_t y)
56 #ifdef __SIZEOF_INT128__
58 __uint128_t rl = xl * y;
62 uint64_t u0, u1, v0, v1, k, t;
66 u1 = x >> 32; u0 = x & 0xFFFFFFFF;
67 v1 = y >> 32; v0 = y & 0xFFFFFFFF;
85 static __rte_always_inline uint64_t
86 rte_reciprocal_divide_u64(uint64_t a, const struct rte_reciprocal_u64 *R)
88 uint64_t t = mullhi_u64(a, R->m);
90 return (t + ((a - t) >> R->sh1)) >> R->sh2;
93 struct rte_reciprocal rte_reciprocal_value(uint32_t d);
94 struct rte_reciprocal_u64 rte_reciprocal_value_u64(uint64_t d);
100 #endif /* _RTE_RECIPROCAL_H_ */