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>
32 struct rte_reciprocal {
37 struct rte_reciprocal_u64 {
42 static inline uint32_t rte_reciprocal_divide(uint32_t a, struct rte_reciprocal R)
44 uint32_t t = (uint32_t)(((uint64_t)a * R.m) >> 32);
46 return (t + ((a - t) >> R.sh1)) >> R.sh2;
49 static __rte_always_inline uint64_t
50 mullhi_u64(uint64_t x, uint64_t y)
52 #ifdef __SIZEOF_INT128__
54 __uint128_t rl = xl * y;
58 uint64_t u0, u1, v0, v1, k, t;
62 u1 = x >> 32; u0 = x & 0xFFFFFFFF;
63 v1 = y >> 32; v0 = y & 0xFFFFFFFF;
81 static __rte_always_inline uint64_t
82 rte_reciprocal_divide_u64(uint64_t a, const struct rte_reciprocal_u64 *R)
84 uint64_t t = mullhi_u64(a, R->m);
86 return (t + ((a - t) >> R->sh1)) >> R->sh2;
89 struct rte_reciprocal rte_reciprocal_value(uint32_t d);
90 struct rte_reciprocal_u64 rte_reciprocal_value_u64(uint64_t d);
92 #endif /* _RTE_RECIPROCAL_H_ */