Skip to content

Commit 8c86fb6

Browse files
Uwe Kleine-Königakpm00
Uwe Kleine-König
authored andcommitted
mul_u64_u64_div_u64: increase precision by conditionally swapping a and b
As indicated in the added comment, the algorithm works better if b is big. As multiplication is commutative, a and b can be swapped. Do this if a is bigger than b. Link: https://lkml.kernel.org/r/20240303092408.662449-2-u.kleine-koenig@pengutronix.de Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de> Tested-by: Biju Das <biju.das.jz@bp.renesas.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
1 parent 4bb7be9 commit 8c86fb6

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

lib/math/div64.c

+15
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <linux/export.h>
2323
#include <linux/math.h>
2424
#include <linux/math64.h>
25+
#include <linux/minmax.h>
2526
#include <linux/log2.h>
2627

2728
/* Not needed on 64bit architectures */
@@ -190,6 +191,20 @@ u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 c)
190191

191192
/* can a * b overflow ? */
192193
if (ilog2(a) + ilog2(b) > 62) {
194+
/*
195+
* Note that the algorithm after the if block below might lose
196+
* some precision and the result is more exact for b > a. So
197+
* exchange a and b if a is bigger than b.
198+
*
199+
* For example with a = 43980465100800, b = 100000000, c = 1000000000
200+
* the below calculation doesn't modify b at all because div == 0
201+
* and then shift becomes 45 + 26 - 62 = 9 and so the result
202+
* becomes 4398035251080. However with a and b swapped the exact
203+
* result is calculated (i.e. 4398046510080).
204+
*/
205+
if (a > b)
206+
swap(a, b);
207+
193208
/*
194209
* (b * a) / c is equal to
195210
*

0 commit comments

Comments
 (0)