blob: bf043258fa0082b4cc1100a982d2ed38e21b1c0e [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Jiong Wang06ae4822018-07-06 15:13:18 -07002#include <linux/bug.h>
Hannes Frederic Sowa809fa972014-01-22 02:29:41 +01003#include <linux/kernel.h>
Eric Dumazet6a2d7a92006-12-13 00:34:27 -08004#include <asm/div64.h>
5#include <linux/reciprocal_div.h>
Eric Dumazet8af2a212011-12-08 06:06:03 +00006#include <linux/export.h>
Eric Dumazet6a2d7a92006-12-13 00:34:27 -08007
Hannes Frederic Sowa809fa972014-01-22 02:29:41 +01008/*
9 * For a description of the algorithm please have a look at
10 * include/linux/reciprocal_div.h
11 */
12
13struct reciprocal_value reciprocal_value(u32 d)
Eric Dumazet6a2d7a92006-12-13 00:34:27 -080014{
Hannes Frederic Sowa809fa972014-01-22 02:29:41 +010015 struct reciprocal_value R;
16 u64 m;
17 int l;
18
19 l = fls(d - 1);
20 m = ((1ULL << 32) * ((1ULL << l) - d));
21 do_div(m, d);
22 ++m;
23 R.m = (u32)m;
24 R.sh1 = min(l, 1);
25 R.sh2 = max(l - 1, 0);
26
27 return R;
Eric Dumazet6a2d7a92006-12-13 00:34:27 -080028}
Eric Dumazet8af2a212011-12-08 06:06:03 +000029EXPORT_SYMBOL(reciprocal_value);
Jiong Wang06ae4822018-07-06 15:13:18 -070030
31struct reciprocal_value_adv reciprocal_value_adv(u32 d, u8 prec)
32{
33 struct reciprocal_value_adv R;
34 u32 l, post_shift;
35 u64 mhigh, mlow;
36
37 /* ceil(log2(d)) */
38 l = fls(d - 1);
39 /* NOTE: mlow/mhigh could overflow u64 when l == 32. This case needs to
40 * be handled before calling "reciprocal_value_adv", please see the
41 * comment at include/linux/reciprocal_div.h.
42 */
43 WARN(l == 32,
44 "ceil(log2(0x%08x)) == 32, %s doesn't support such divisor",
45 d, __func__);
46 post_shift = l;
47 mlow = 1ULL << (32 + l);
48 do_div(mlow, d);
49 mhigh = (1ULL << (32 + l)) + (1ULL << (32 + l - prec));
50 do_div(mhigh, d);
51
52 for (; post_shift > 0; post_shift--) {
53 u64 lo = mlow >> 1, hi = mhigh >> 1;
54
55 if (lo >= hi)
56 break;
57
58 mlow = lo;
59 mhigh = hi;
60 }
61
62 R.m = (u32)mhigh;
63 R.sh = post_shift;
64 R.exp = l;
65 R.is_wide_m = mhigh > U32_MAX;
66
67 return R;
68}
69EXPORT_SYMBOL(reciprocal_value_adv);