mul_u64_u64_div_u64: new implementation
v2 cover mul_u64_u64_div_u64: new implementation
This provides an implementation for mul_u64_u64_div_u64() that always produces exact results.
Changes from v1 (https://lkml.org/lkml/2024/6/28/1130):
- Use the already available u128 type instead of "unsigned __int128".
- Add a test module.
PATCH v2 1/2 mul_u64_u64_div_u64: make it precise always
From: Nicolas Pitre <[email protected]>
Library facilities must always return exact results. If the caller may be contented with approximations then it should do the approximation on its own.
In this particular case the comment in the code says "the algorithm ... below might lose some precision". Well, if you try it with e.g.:
a = 18446462598732840960 b = 18446462598732840960 c = 18446462598732840961
then the produced answer is 0 whereas the exact answer should be 18446462598732840959. This is _some_ precision lost indeed!
Let's reimplement this function so it always produces the exact result regardless of its inputs while preserving existing fast paths when possible.
--- lib/math/div64.c | 123 ++++++++++++++++++++++++++++++----------------- 1 file changed, 80 insertions(+), 43 deletions(-)
lib/math/div64.c +80 -43
@@ -186,55 +186,92 @@ EXPORT_SYMBOL(iter_div_u64_rem);#ifndef mul_u64_u64_div_u64u64 mul_u64_u64_div_u64 (u64 a,u64 b,u64 c) { -u64 res =0 , div, rem; -int shift; +if (ilog2 (a) +ilog2 (b) <=62 ) +return div64_u64 (a * b, c); -/* can a * b overflow ? */ -if (ilog2 (a) +ilog2 (b) >62 ) { -/* -* Note that the algorithm after the if block below might lose -* some precision and the result is more exact for b > a. So -* exchange a and b if a is bigger than b. -* -* For example with a = 43980465100800, b = 100000000, c = 1000000000 -* the below calculation doesn't modify b at all because div == 0 -* and then shift becomes 45 + 26 - 62 = 9 and so the result -* becomes 4398035251080. However with a and b swapped the exact -* result is calculated (i.e. 4398046510080). -*/ -if (a > b) -swap (a, b); +#if defined(__SIZEOF_INT128__) + +/* native 64x64=128 bits multiplication */ +u128 prod = (u128 )a * b; +u64 n_lo = prod, n_hi = prod >>64 ; + +#else + +/* perform a 64x64=128 bits multiplication manually */ +union { +u64 v; +struct { +#if defined(CONFIG_CPU_LITTLE_ENDIAN ) +u32 l; +u32 h; +#elif defined(CONFIG_CPU_BIG_ENDIAN ) +u32 h; +u32 l; +#else +#error "unknown endianness" +#endif + }; + }A ,B ,X ,Y ,Z ; + +A .v = a; +B .v = b; + +X .v = (u64 )A .l *B .l; +Y .v = (u64 )A .l *B .h +X .h; +Z .v = (u64 )A .h *B .h +Y .h; +Y .v = (u64 )A .h *B .l +Y .l; +X .h =Y .l; +Z .v +=Y .h; + +u64 n_lo =X .v, n_hi =Z .v; + +#endif +int shift =__builtin_ctzll (c); + +/* try reducing the fraction in case the dividend becomes <= 64 bits */ +if ((n_hi >> shift) ==0 ) { +u64 n = (n_lo >> shift) | (n_hi << (64 - shift)); + +return div64_u64 (n, c >> shift);/* -* (b * a) / c is equal to -* -* (b / c) * a + -* (b % c) * a / c -* -* if nothing overflows. Can the 1st multiplication -* overflow? Yes, but we do not care: this can only -* happen if the end result can't fit in u64 anyway. -* -* So the code below does -* -* res = (b / c) * a; -* b = b % c; +* The remainder value if needed would be: +* res = div64_u64_rem(n, c >> shift, &rem); +* rem = (rem << shift) + (n_lo - (n << shift)); */ - div =div64_u64_rem (b, c, &rem); - res = div * a; - b = rem; - - shift =ilog2 (a) +ilog2 (b) -62 ; -if (shift >0 ) { -/* drop precision */ - b >>= shift; - c >>= shift; -if (!c) -return res; - } } -return res +div64_u64 (a * b, c); +if (n_hi >= c) { +/* overflow: result is unrepresentable in a u64 */ +return -1 ; + } + +/* Do the full 128 by 64 bits division */ + + shift =__builtin_clzll (c); + c <<= shift; + +int p =64 + shift; +u64 res =0 ; +bool carry; + +do { + carry = n_hi >>63 ; + shift = carry ?1 :__builtin_clzll (n_hi); +if (p < shift) +break ; + p -= shift; + n_hi <<= shift; + n_hi |= n_lo >> (64 - shift); + n_lo <<= shift; +if (carry || (n_hi >= c)) { + n_hi -= c; + res |=1ULL << p; + } + }while (n_hi); +/* The remainder value if needed would be n_hi << p */ + +return res; }EXPORT_SYMBOL (mul_u64_u64_div_u64);#endif
Signature · 1 line
2.45.2
Re: [PATCH v2 1/2] mul_u64_u64_div_u64: make it precise always
Hello Nico,
Quoted 53 lines · Nicolas Pitre
lib/math/div64.c +27
-17@@ -186,55 +186,92 @@ EXPORT_SYMBOL(iter_div_u64_rem);#ifndef mul_u64_u64_div_u64u64 mul_u64_u64_div_u64 (u64 a,u64 b,u64 c) { -u64 res =0 , div, rem; -int shift; +if (ilog2 (a) +ilog2 (b) <=62 ) +return div64_u64 (a * b, c); -/* can a * b overflow ? */ -if (ilog2 (a) +ilog2 (b) >62 ) { -/* -* Note that the algorithm after the if block below might lose -* some precision and the result is more exact for b > a. So -* exchange a and b if a is bigger than b. -* -* For example with a = 43980465100800, b = 100000000, c = 1000000000 -* the below calculation doesn't modify b at all because div == 0 -* and then shift becomes 45 + 26 - 62 = 9 and so the result -* becomes 4398035251080. However with a and b swapped the exact -* result is calculated (i.e. 4398046510080). -*/ -if (a > b) -swap (a, b); +#if defined(__SIZEOF_INT128__) + +/* native 64x64=128 bits multiplication */ +u128 prod = (u128 )a * b; +u64 n_lo = prod, n_hi = prod >>64 ; + +#else + +/* perform a 64x64=128 bits multiplication manually */ +union { +u64 v; +struct { +#if defined(CONFIG_CPU_LITTLE_ENDIAN ) +u32 l; +u32 h; +#elif defined(CONFIG_CPU_BIG_ENDIAN ) +u32 h; +u32 l; +#else +#error "unknown endianness" +#endif + }; + }A ,B ,X ,Y ,Z ; + +A .v = a;
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 226
Quoted 10 lines
lib/math/div64.c +10
-0+B .v = b; + +X .v = (u64 )A .l *B .l; +Y .v = (u64 )A .l *B .h +X .h; +Z .v = (u64 )A .h *B .h +Y .h; +Y .v = (u64 )A .h *B .l +Y .l; +X .h =Y .l; +Z .v +=Y .h; + +u64 n_lo =X .v, n_hi =Z .v;
I tried to understand your patch. This part could really benefit from some comments. With pen and paper I worked out your idea:
The goal is: A * B == Z << 64 + X With A = A.h << 32 + A.l and similar identities for B, we have: A * B = (A.h << 32 + A.l) * (B.h << 32 + B.l) = (A.h * B.h << 64 + (A.h * B.l + A.l * B.h) << 32 + A.l * B.l The operations done here are only 32 bit multiplications and additions, and with U32_MAX = 0xffffffff we have: U32_MAX * U32_MAX + U32_MAX = (U32_MAX + 1) * U32_MAX = 0xffffffff00000000 which fits into an u64. Even when adding another U32_MAX (which happens with Z.v += Y.h) it still fits into u64, and so the operations won't overflow.
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 228
Quoted 2 lines
lib/math/div64.c +2
-0+ +#endif
So starting here we have
n_hi << 64 + n_lo == a * b
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 233
Quoted 4 lines
lib/math/div64.c +4
-0+int shift =__builtin_ctzll (c); + +/* try reducing the fraction in case the dividend becomes <= 64 bits */ +if ((n_hi >> shift) ==0 ) {
The idea here is: c = c_ << shift, and so
a * b / c == (a * b) >> shift / c_
In this if-body we're handling (a * b) >> shift fitting into an u64.
Quoted 32 lines
lib/math/div64.c +6
-24+u64 n = (n_lo >> shift) | (n_hi << (64 - shift)); + +return div64_u64 (n, c >> shift);/* -* (b * a) / c is equal to -* -* (b / c) * a + -* (b % c) * a / c -* -* if nothing overflows. Can the 1st multiplication -* overflow? Yes, but we do not care: this can only -* happen if the end result can't fit in u64 anyway. -* -* So the code below does -* -* res = (b / c) * a; -* b = b % c; +* The remainder value if needed would be: +* res = div64_u64_rem(n, c >> shift, &rem); +* rem = (rem << shift) + (n_lo - (n << shift)); */ - div =div64_u64_rem (b, c, &rem); - res = div * a; - b = rem; - - shift =ilog2 (a) +ilog2 (b) -62 ; -if (shift >0 ) { -/* drop precision */ - b >>= shift; - c >>= shift; -if (!c) -return res;
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 249
Quoted 10 lines
lib/math/div64.c +6
-2- } } -return res +div64_u64 (a * b, c); +if (n_hi >= c) { +/* overflow: result is unrepresentable in a u64 */ +return -1 ; + } + +/* Do the full 128 by 64 bits division */
Here is the code location where I stop understanding your code :-)
Maybe stating the loop invariant in a comment would be helpful?
Quoted 12 lines
lib/math/div64.c +12
-0+ shift =__builtin_clzll (c); + c <<= shift; + +int p =64 + shift; +u64 res =0 ; +bool carry; + + do { + carry = n_hi >> 63; + shift = carry ? 1 : __builtin_clzll(n_hi); + if (p < shift) + break;
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 272
Quoted 10 lines
lib/math/div64.c +10
-0+ p -= shift; + n_hi <<= shift; + n_hi |= n_lo >> (64 - shift); + n_lo <<= shift; +if (carry || (n_hi >= c)) { + n_hi -= c; + res |=1ULL << p; + } + }while (n_hi); +/* The remainder value if needed would be n_hi << p */
I indeed need a variant of this function that rounds up. So maybe creating a function
u64 mul_u64_u64_div_u64_rem(u64 a, u64 b, u64 c, u64 *rem)
with the sophistication of your mul_u64_u64_div_u64 and then:
u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 c)
{
u64 rem, ret;
ret = mul_u64_u64_div_u64_rem(a, b, c, &rem);
return ret;
}(In the hope that the compiler optimizes out the calculation for the remainder) and:
u64 mul_u64_u64_div_u64_roundup(u64 a, u64 b, u64 c)
{
u64 rem, ret;
ret = mul_u64_u64_div_u64_rem(a, b, c, &rem);
if (rem)
ret += 1;
return ret;
}would be nice. (This could be done in a follow up patch though.)
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 277
Quoted 4 lines
lib/math/div64.c +1
-0+ return res; }EXPORT_SYMBOL (mul_u64_u64_div_u64);#endif
Best regards
Uwe
Re: [PATCH v2 1/2] mul_u64_u64_div_u64: make it precise always
Quoted 18 lines · Uwe Kleine-König
Hello Nico,
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 226
Quoted 11 lines · Nicolas Pitre
lib/math/div64.c +11
-0+A .v = a; +B .v = b; + +X .v = (u64 )A .l *B .l; +Y .v = (u64 )A .l *B .h +X .h; +Z .v = (u64 )A .h *B .h +Y .h; +Y .v = (u64 )A .h *B .l +Y .l; +X .h =Y .l; +Z .v +=Y .h; + +u64 n_lo =X .v, n_hi =Z .v;I tried to understand your patch. This part could really benefit from some comments. With pen and paper I worked out your idea:
Quoted 8 lines
The goal is: A * B == Z << 64 + X With A = A.h << 32 + A.l and similar identities for B, we have: A * B = (A.h << 32 + A.l) * (B.h << 32 + B.l) = (A.h * B.h << 64 + (A.h * B.l + A.l * B.h) << 32 + A.l * B.l
^ missing )
Quoted 6 lines
The operations done here are only 32 bit multiplications and additions, and with U32_MAX = 0xffffffff we have: U32_MAX * U32_MAX + U32_MAX = (U32_MAX + 1) * U32_MAX = 0xffffffff00000000 which fits into an u64. Even when adding another U32_MAX (which happens with Z.v += Y.h) it still fits into u64, and so the operations won't overflow.
Exact, that's the idea.
I was about to reproduce the code I wrote for a similar purpose about 18 years ago that currently lives in __arch_xprod_64() (include/asm-generic/div64.h). when I realized that, with some reordering, all the overflow handling could be avoided entirely.
So I'm about to submit some nice simplification for my old optimized __div64_const32() based on this realisation.
Quoted 3 lines
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 249
Quoted 1 line
lib/math/div64.c +1
-0+/* Do the full 128 by 64 bits division */ Here is the code location where I stop understanding your code :-)
Here's how it goes:
To do a binary division, you have to align the numbers, find how many times the
divisor fits and subtract, just like we learned in primary school. Except that we have binary numbers instead of base 10 numbers, making the "how many times" either 0 or 1.
To align numbers, let's simply move set bits to the top left bit.
Let's suppose a divisor c of 0x00ffffff00000000
shift = __builtin_clzll(c);
c <<= shift;so shift = 8 and c becomes 0xffffff0000000000
Also need to track the actual divisor power. Given that we start working on n_hi not n_lo, this means the power is initially 64. But we just shifted c which increased its power:
p = 64 + shift;
Then, remember that n_hi < original c. That's ensured by the overflow test earlier. So shifting n_hi leftwards will require a greater shift than the one we applied to c, meaning that p will become 63 or less during the first loop.
Let's suppose n_hi = 0x000ffffffff00000 and n_lo = 0
Then enter the loop:
carry = n_hi >> 63;
Top bit of n_hi is unset so no carry.
shift = carry ? 1 : __builtin_clzll(n_hi);
If n'hi's top bit was set we'd have a shift of 1 with a carry. But here there is no carry and aligning n_hi to the top left bit requires a shift of 12.
n_hi <<= shift;
n_hi |= n_lo >> (64 - shift);
n_lo <<= shift;So n_hi is now 0xffffffff00000000
p -= shift;
Shifting left the dividend reduces the divisor's power. So p is now 64 + 8 - 12 = 60
Then, the crux of the operation:
if (carry || (n_hi >= c)) {
n_hi -= c;
res |= 1ULL << p;
}So... if the divisor fits then we add a 1 to the result and subtract it. n_hi = 0xffffffff00000000 - 0xffffff0000000000 = 0x000000ff00000000 res |= 1 << 60
Let's loop again:
carry = n_hi >> 63;
shift = carry ? 1 : __builtin_clzll(n_hi);
...No carry, shift becomes 24, p becomes 60 - 24 = 36 and n_hi becomes 0xff00000000000000.
if (carry || (n_hi >= c)) { ...No carry and n_hi is smaller than c so loop again.
carry = n_hi >> 63;
shift = carry ? 1 : __builtin_clzll(n_hi);This time we have a carry as the top bit of n_hi is set and we're about to shift it by 1. p becomes 35 and n_hi becomes 0xfe00000000000000. In reality it is like having 0x1fe00000000000000 (a 65-bits value) which is obviously bigger than 0xffffff0000000000. So we can augment the result and subtract. Thanks to two's complement, we have:
n_hi = 0xfe00000000000000 - 0xffffff0000000000 = 0xfe00010000000000
and
res = 1 << 60 | 1 << 35
And so on until either n_hi becomes 0 or p would go negative, which might happen quite quickly in some cases.
Quoted 17 lines
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 272
Quoted 1 line
lib/math/div64.c +1
-0+/* The remainder value if needed would be n_hi << p */ I indeed need a variant of this function that rounds up. So maybe creating a function
u64 mul_u64_u64_div_u64_rem(u64 a, u64 b, u64 c, u64 *rem)with the sophistication of your
mul_u64_u64_div_u64and then:u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 c) { u64 rem, ret; ret = mul_u64_u64_div_u64_rem(a, b, c, &rem); return ret; }
Quoted 2 lines
(In the hope that the compiler optimizes out the calculation for the remainder)
It probably won't unless the core function is a static inline.
It might be more efficient to do this:
u64 mul_u64_u64_div_u64_rem(u64 a, u64 b, u64 c, u64 *rem)
{
u64 res = u64 mul_u64_u64_div_u64(a, b, c);
/* those multiplications will overflow but it doesn't matter */
*rem = a * b - c * res;
return res;
}This way the core code doesn't get duplicated.
Quoted 14 lines
and:
u64 mul_u64_u64_div_u64_roundup(u64 a, u64 b, u64 c) { u64 rem, ret; ret = mul_u64_u64_div_u64_rem(a, b, c, &rem); if (rem) ret += 1; return ret; }
Quoted 1 line
would be nice. (This could be done in a follow up patch though.)
You're welcome to it. ;-)
Nicolas
Re: [PATCH v2 1/2] mul_u64_u64_div_u64: make it precise always
Quoted 22 lines · Nicolas Pitre
Quoted 20 lines · Uwe Kleine-König
Hello Nico,
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 226
Quoted 11 lines · Nicolas Pitre
lib/math/div64.c +11
-0+A .v = a; +B .v = b; + +X .v = (u64 )A .l *B .l; +Y .v = (u64 )A .l *B .h +X .h; +Z .v = (u64 )A .h *B .h +Y .h; +Y .v = (u64 )A .h *B .l +Y .l; +X .h =Y .l; +Z .v +=Y .h; + +u64 n_lo =X .v, n_hi =Z .v;I tried to understand your patch. This part could really benefit from some comments. With pen and paper I worked out your idea:
The goal is:
Quoted 7 lines
Quoted 6 lines
A * B == Z << 64 + X With A = A.h << 32 + A.l and similar identities for B, we have: A * B = (A.h << 32 + A.l) * (B.h << 32 + B.l) = (A.h * B.h << 64 + (A.h * B.l + A.l * B.h) << 32 + A.l * B.l^ missing )
Ack, alternatively the opening ( can be dropped.
Quoted 107 lines
Quoted 6 lines
The operations done here are only 32 bit multiplications and additions, and with U32_MAX = 0xffffffff we have: U32_MAX * U32_MAX + U32_MAX = (U32_MAX + 1) * U32_MAX = 0xffffffff00000000 which fits into an u64. Even when adding another U32_MAX (which happens with Z.v += Y.h) it still fits into u64, and so the operations won't overflow.Exact, that's the idea.
I was about to reproduce the code I wrote for a similar purpose about 18 years ago that currently lives in
__arch_xprod_64()(include/asm-generic/div64.h). when I realized that, with some reordering, all the overflow handling could be avoided entirely.So I'm about to submit some nice simplification for my old optimized
__div64_const32()based on this realisation.Quoted 3 lines
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 249
Quoted 1 line
lib/math/div64.c +1
-0+/* Do the full 128 by 64 bits division */ Here is the code location where I stop understanding your code :-)
Here's how it goes:
To do a binary division, you have to align the numbers, find how many times the
divisor fits and subtract, just like we learned in primary school. Except that we have binary numbers instead of base 10 numbers, making the "how many times" either 0 or 1.To align numbers, let's simply move set bits to the top left bit.
Let's suppose a divisor c of
0x00ffffff00000000shift = __builtin_clzll(c); c <<= shift;so shift = 8 and c becomes
0xffffff0000000000Also need to track the actual divisor power. Given that we start working on
n_hinotn_lo, this means the power is initially 64. But we just shifted c which increased its power:p = 64 + shift;Then, remember that
n_hi< original c. That's ensured by the overflow test earlier. So shiftingn_hileftwards will require a greater shift than the one we applied to c, meaning that p will become 63 or less during the first loop.Let's suppose
n_hi=0x000ffffffff00000andn_lo= 0Then enter the loop:
carry = n_hi >> 63;Top bit of
n_hiis unset so no carry.shift = carry ? 1 : __builtin_clzll(n_hi);If n'hi's top bit was set we'd have a shift of 1 with a carry. But here there is no carry and aligning
n_hito the top left bit requires a shift of 12.n_hi <<= shift; n_hi |= n_lo >> (64 - shift); n_lo <<= shift;So
n_hiis now0xffffffff00000000p -= shift;Shifting left the dividend reduces the divisor's power. So p is now 64 + 8 - 12 = 60
Then, the crux of the operation:
if (carry || (n_hi >= c)) { n_hi -= c; res |= 1ULL << p; }So... if the divisor fits then we add a 1 to the result and subtract it.
n_hi=0xffffffff00000000-0xffffff0000000000=0x000000ff00000000res |= 1 << 60Let's loop again:
carry = n_hi >> 63; shift = carry ? 1 : __builtin_clzll(n_hi); ...No carry, shift becomes 24, p becomes 60 - 24 = 36 and
n_hibecomes0xff00000000000000.if (carry || (n_hi >= c)) { ...No carry and
n_hiis smaller than c so loop again.carry = n_hi >> 63; shift = carry ? 1 : __builtin_clzll(n_hi);This time we have a carry as the top bit of
n_hiis set and we're about to shift it by 1. p becomes 35 andn_hibecomes0xfe00000000000000. In reality it is like having0x1fe00000000000000(a 65-bits value) which is obviously bigger than0xffffff0000000000. So we can augment the result and subtract. Thanks to two's complement, we have:
Quoted 5 lines
n_hi=0xfe00000000000000-0xffffff0000000000=0xfe00010000000000and
res = 1 << 60 | 1 << 35
Oh wow, that part is clever. Before your mail I wondered for a while why the right thing happens if carry=1 but n_hi < c.
Quoted 2 lines
And so on until either
n_hibecomes 0 or p would go negative, which might happen quite quickly in some cases.
OK, so the loop invariant at the end of each iteration is:
final result = res + (n_hi#n_lo << p) / c
(with n_hi#n_lo = n_hi << 64 | n_lo), right?
Quoted 34 lines
Quoted 17 lines
lib/math/div64.c EXPORT_SYMBOL(iter_div_u64_rem); · line 272
Quoted 1 line
lib/math/div64.c +1
-0+/* The remainder value if needed would be n_hi << p */ I indeed need a variant of this function that rounds up. So maybe creating a function
u64 mul_u64_u64_div_u64_rem(u64 a, u64 b, u64 c, u64 *rem)with the sophistication of your
mul_u64_u64_div_u64and then:u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 c) { u64 rem, ret; ret = mul_u64_u64_div_u64_rem(a, b, c, &rem); return ret; }Quoted 2 lines
(In the hope that the compiler optimizes out the calculation for the remainder)
It probably won't unless the core function is a static inline.
It might be more efficient to do this:
u64
mul_u64_u64_div_u64_rem(u64 a, u64 b, u64 c, u64 *rem){ u64 res = u64 mul_u64_u64_div_u64(a, b, c); /* those multiplications will overflow but it doesn't matter */ *rem = a * b - c * res; return res; }
Quoted 1 line
This way the core code doesn't get duplicated.
Good idea. I'll check that after the discussion about this patch.
Best regards
Uwe
Re: [PATCH v2 1/2] mul_u64_u64_div_u64: make it precise always
Quoted 66 lines · Uwe Kleine-König
Quoted 56 lines · Nicolas Pitre
Then enter the loop:
carry = n_hi >> 63;Top bit of
n_hiis unset so no carry.shift = carry ? 1 : __builtin_clzll(n_hi);If n'hi's top bit was set we'd have a shift of 1 with a carry. But here there is no carry and aligning
n_hito the top left bit requires a shift of 12.n_hi <<= shift; n_hi |= n_lo >> (64 - shift); n_lo <<= shift;So
n_hiis now0xffffffff00000000p -= shift;Shifting left the dividend reduces the divisor's power. So p is now 64 + 8 - 12 = 60
Then, the crux of the operation:
if (carry || (n_hi >= c)) { n_hi -= c; res |= 1ULL << p; }So... if the divisor fits then we add a 1 to the result and subtract it.
n_hi=0xffffffff00000000-0xffffff0000000000=0x000000ff00000000res |= 1 << 60Let's loop again:
carry = n_hi >> 63; shift = carry ? 1 : __builtin_clzll(n_hi); ...No carry, shift becomes 24, p becomes 60 - 24 = 36 and
n_hibecomes0xff00000000000000.if (carry || (n_hi >= c)) { ...No carry and
n_hiis smaller than c so loop again.carry = n_hi >> 63; shift = carry ? 1 : __builtin_clzll(n_hi);This time we have a carry as the top bit of
n_hiis set and we're about to shift it by 1. p becomes 35 andn_hibecomes0xfe00000000000000. In reality it is like having0x1fe00000000000000(a 65-bits value) which is obviously bigger than0xffffff0000000000. So we can augment the result and subtract. Thanks to two's complement, we have:Quoted 5 lines
n_hi=0xfe00000000000000-0xffffff0000000000=0xfe00010000000000and
res = 1 << 60 | 1 << 35
Oh wow, that part is clever. Before your mail I wondered for a while why the right thing happens if carry=1 but
n_hi< c.
Quoted 8 lines
Quoted 2 lines
And so on until either
n_hibecomes 0 or p would go negative, which might happen quite quickly in some cases.OK, so the loop invariant at the end of each iteration is:
final result = res + (n_hi#n_lo << p) / c
(with n_hi#n_lo =
n_hi<< 64 |n_lo), right?
Hmmm maybe. I hardly think in such terms so I can't say for sure if this is right.
Nicolas
PATCH v2 2/2 mul_u64_u64_div_u64: basic sanity test
In reply to Nicolas PitreFrom: Nicolas Pitre <[email protected]>
Verify that edge cases produce proper results, and some more.
--- lib/Kconfig.debug | 10 +++ lib/math/Makefile | 1 + lib/math/test_mul_u64_u64_div_u64.c | 98 +++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 lib/math/test_mul_u64_u64_div_u64.c
lib/Kconfig.debug +10 -0
@@ -2278,6 +2278,16 @@ config TEST_DIV64 If unsure, say N. +config TEST_MULDIV64 + tristate "mul_u64_u64_div_u64() test" + depends on DEBUG_KERNEL || m + help + Enable this to turn on 'mul_u64_u64_div_u64()' function test. + This test is executed only once during system boot (so affects + only boot time), or at module load time. + + If unsure, say N. + config TEST_IOV_ITER tristate "Test iov_iter operation" if !KUNIT_ALL_TESTS depends on KUNIT
lib/math/Makefile +1 -0
@@ -6,4 +6,5 @@ obj-$(CONFIG_PRIME_NUMBERS) += prime_numbers.o obj-$(CONFIG_RATIONAL) += rational.o obj-$(CONFIG_TEST_DIV64) += test_div64.o +obj-$(CONFIG_TEST_MULDIV64) += test_mul_u64_u64_div_u64.o obj-$(CONFIG_RATIONAL_KUNIT_TEST) += rational-test.o
lib/math/test_mul_u64_u64_div_u64.c new file +98 -0
98 lines not on this page · raw message
Signature · 1 line
2.45.2
Andrew Morton
maintainerRe: [PATCH v2 2/2] mul_u64_u64_div_u64: basic sanity test
Quoted 1 line · On Tue, 2 Jul 2024 23:34:09 -0400 Nicolas Pitre <[email protected]> wrote:
Verify that edge cases produce proper results, and some more.
Awesome, thanks.
Do you know of any situations in which the present implementation causes issues?
Re: [PATCH v2 2/2] mul_u64_u64_div_u64: basic sanity test
Quoted 8 lines · Andrew Morton
Quoted 1 line · On Tue, 2 Jul 2024 23:34:09 -0400 Nicolas Pitre <[email protected]> wrote:
Verify that edge cases produce proper results, and some more.
Awesome, thanks.
Do you know of any situations in which the present implementation causes issues?
Uwe could probably elaborate further, but the example given in the first commit log is causing trouble for a driver he's working on.
Nicolas
Re: [PATCH v2 2/2] mul_u64_u64_div_u64: basic sanity test
Hello Andrew,
Quoted 6 lines · Nicolas Pitre
Quoted 4 lines · Andrew Morton
Quoted 1 line · On Tue, 2 Jul 2024 23:34:09 -0400 Nicolas Pitre <[email protected]> wrote:
Verify that edge cases produce proper results, and some more.
Quoted 7 lines
Quoted 4 lines
Awesome, thanks.
Do you know of any situations in which the present implementation causes issues?
Uwe could probably elaborate further, but the example given in the first commit log is causing trouble for a driver he's working on.
Actually the example was a constructed one. I became aware of mul_u64_u64_div_u64() being only an approximation while reviewing a pwm driver by Biju Das:
mul_u64_u64_div_u64 is used in various pwm drivers, but in practise the periods used are small enough to not be problematic for the status quo implementation since commit 8c86fb68ffcb ("mul_u64_u64_div_u64: increase precision by conditionally swapping a and b"). At least I think Biju (added to Cc:) only hit this problem during testing, and not in a real world application.
I intend to do a performance test of Nico's code. I hope I get to that tomorrow.
Best regards
Uwe
RE: [PATCH v2 2/2] mul_u64_u64_div_u64: basic sanity test
Hi All,
Quoted 28 lines
-----Original Message-----
From: Uwe Kleine-König <[email protected]>
Sent: Wednesday, July 3, 2024 10:36 PM
Subject: Re: [PATCH v2 2/2]mul_u64_u64_div_u64: basic sanity testHello Andrew,
Quoted 6 lines · Nicolas Pitre
Quoted 4 lines · Andrew Morton
Quoted 1 line · On Tue, 2 Jul 2024 23:34:09 -0400 Nicolas Pitre <[email protected]> wrote:
Verify that edge cases produce proper results, and some more.
Quoted 7 lines
Quoted 4 lines
Awesome, thanks.
Do you know of any situations in which the present implementation causes issues?
Uwe could probably elaborate further, but the example given in the first commit log is causing trouble for a driver he's working on.
Actually the example was a constructed one. I became aware of
mul_u64_u64_div_u64()being only an approximation while reviewing a pwm driver by Biju Das:https://lore.kernel.org/linux-
pwm/TYCPR01MB1126992DD51F714AEDADF0A4F868DA@TYCPR01MB11269.jpnprd01.prod.outlook.com
Quoted 6 lines
mul_u64_u64_div_u64is used in various pwm drivers, but in practise the periods used are small enough to not be problematic for the status quo implementation since commit8c86fb68ffcb("mul_u64_u64_div_u64: increase precision by conditionally swapping a and b"). At least I think Biju (added to Cc:) only hit this problem during testing, and not in a real world application.I intend to do a performance test of Nico's code. I hope I get to that tomorrow.
I should be able to test the new patch[1] with [2] as mul_u64_u64_div_u64() used in [2].
[1] https://lkml.org/lkml/2024/6/28/1130
[2] https://lore.kernel.org/linux-renesas-soc/[email protected]/
I will test and provide feedback soon.
Cheers,
Biju
Biju Das
Tested-byRE: [PATCH v2 2/2] mul_u64_u64_div_u64: basic sanity test
Hi All,
Quoted 43 lines
-----Original Message-----
From: Biju Das
Sent: Thursday, July 4, 2024 7:41 AM
Subject: RE: [PATCH v2 2/2]mul_u64_u64_div_u64: basic sanity testHi All,
Quoted 29 lines
-----Original Message-----
From: Uwe Kleine-König <[email protected]>
Sent: Wednesday, July 3, 2024 10:36 PM
Subject: Re: [PATCH v2 2/2]mul_u64_u64_div_u64: basic sanity testHello Andrew,
Quoted 6 lines · Nicolas Pitre
Quoted 4 lines · Andrew Morton
Quoted 1 line · On Tue, 2 Jul 2024 23:34:09 -0400 Nicolas Pitre <[email protected]> wrote:
Verify that edge cases produce proper results, and some more.
Quoted 7 lines
Quoted 4 lines
Awesome, thanks.
Do you know of any situations in which the present implementation causes issues?
Uwe could probably elaborate further, but the example given in the first commit log is causing trouble for a driver he's working on.
Actually the example was a constructed one. I became aware of
mul_u64_u64_div_u64()being only an approximation while reviewing a pwm driver by Biju Das:https://lore.kernel.org/linux-
pwm/TYCPR01MB1126992DD51F714AEDADF0A4F868DA@TYCPR01MB11269.jpnprd01.pr od.outlook.comQuoted 5 lines
mul_u64_u64_div_u64is used in various pwm drivers, but in practise
the periods used are small enough to not be problematic for the status
quo implementation since commit8c86fb68ffcb
("mul_u64_u64_div_u64: increase precision by conditionally swapping a
and b"). At least I think Biju (added to Cc:) only hit this problem during testing, and not in areal world application.
Quoted 1 line
Quoted 8 lines
Quoted 1 line
I intend to do a performance test of Nico's code. I hope I get to that tomorrow.
I should be able to test the new patch[1] with [2] as
mul_u64_u64_div_u64()used in [2].[1] https://lkml.org/lkml/2024/6/28/1130
[2] https://lore.kernel.org/linux-renesas-soc/[email protected]/I will test and provide feedback soon.
I tested the patch [1] with [2] (CONFIG_PWM_DEBUG=y) I don't see any idempotent issues. So,
Cheers,
Biju
Uwe Kleine-König
Tested-byRe: [PATCH v2 2/2] mul_u64_u64_div_u64: basic sanity test
In reply to Uwe Kleine-KönigHello,
Quoted 2 lines · Uwe Kleine-König
I intend to do a performance test of Nico's code. I hope I get to that tomorrow.
I'm really surprised, I expected a penalty for being more correct, but there doesn't seem to be one.
I tested on an stm32mp135f SoC (i.e. armv7) with:
time pwmtestperf -p 3 -P 1000000000 -S 1000
which configures the PWM 1000001 times, each configuration calls mul_u64_u64_div_u64() three times. And I got
real 0m 37.17s user 0m 0.69s sys 0m 36.40s
on 6.10.0-rc1 (+ various pwm related patches) and
real 0m 36.93s user 0m 0.58s sys 0m 36.26s
with Nico's patch applied on top.
Looking at the patch in detail, I always hit ilog2(a) + ilog2(b) <= 62, so on 2nd thought it's not surprising that the performance is similar.
Thanks!
Uwe