Re: [PATCH v2 next 2/4] lib: mul_u64_u64_div_u64() Use BUG_ON() for divide by zero
From: Uwe Kleine-König
Date: Mon May 19 2025 - 02:11:17 EST
On Sun, May 18, 2025 at 02:38:46PM +0100, David Laight wrote:
> Do an explicit BUG_ON(!divisor) instead of hoping the 'undefined
> behaviour' the compiler generated for a compile-time 1/0 is in any
> way useful.
>
> It may be better to define the function to return ~(u64)0 for
> divide by zero.
>
> Signed-off-by: David Laight <david.laight.linux@xxxxxxxxx>
> ---
>
> A new change for v2 of the patchset.
> Whereas gcc inserts (IIRC) 'ud2' clang is likely to let the code
> continue and generate 'random' results for any 'undefined bahaviour'.
>
> lib/math/div64.c | 10 +++-------
> 1 file changed, 3 insertions(+), 7 deletions(-)
>
> diff --git a/lib/math/div64.c b/lib/math/div64.c
> index a5c966a36836..c426fa0660bc 100644
> --- a/lib/math/div64.c
> +++ b/lib/math/div64.c
> @@ -186,6 +186,9 @@ EXPORT_SYMBOL(iter_div_u64_rem);
> #ifndef mul_u64_u64_div_u64
> u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 d)
> {
> + /* Trigger exception if divisor is zero */
> + BUG_ON(!d);
> +
I'm unsure if I should like the BUG_ON better than return 1/0. My gut
feeling is that mul_u64_u64_div_u64() should behave in the same way as
e.g. div64_u64 (which is just `return dividend / divisor;` for 64bit
archs and thus triggers the same exception as `return 1/0;`.
If BUG_ON should be it, I'd prefer
BUG_ON(unlikely(d == 0));
which keeps the unlikely() that is already in the check removed below
and is more explicit that checking for !d.
> if (ilog2(a) + ilog2(b) <= 62)
> return div64_u64(a * b, d);
>
> @@ -212,13 +215,6 @@ u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 d)
>
> #endif
>
> - /* make sure d is not zero, trigger exception otherwise */
> -#pragma GCC diagnostic push
> -#pragma GCC diagnostic ignored "-Wdiv-by-zero"
> - if (unlikely(d == 0))
> - return 1/0;
> -#pragma GCC diagnostic pop
> -
> int shift = __builtin_ctzll(d);
>
> /* try reducing the fraction in case the dividend becomes <= 64 bits */
Best regards
Uwe
Attachment:
signature.asc
Description: PGP signature