]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
lib: mul_u64_u64_div_u64(): combine overflow and divide by zero checks
authorDavid Laight <david.laight.linux@gmail.com>
Wed, 5 Nov 2025 20:10:28 +0000 (20:10 +0000)
committerAndrew Morton <akpm@linux-foundation.org>
Thu, 20 Nov 2025 22:03:41 +0000 (14:03 -0800)
Since the overflow check always triggers when the divisor is zero
move the check for divide by zero inside the overflow check.
This means there is only one test in the normal path.

Link: https://lkml.kernel.org/r/20251105201035.64043-3-david.laight.linux@gmail.com
Signed-off-by: David Laight <david.laight.linux@gmail.com>
Reviewed-by: Nicolas Pitre <npitre@baylibre.com>
Cc: Biju Das <biju.das.jz@bp.renesas.com>
Cc: Borislav Betkov <bp@alien8.de>
Cc: "H. Peter Anvin" <hpa@zytor.com>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: Jens Axboe <axboe@kernel.dk>
Cc: Li RongQing <lirongqing@baidu.com>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Thomas Gleinxer <tglx@linutronix.de>
Cc: Uwe Kleine-König <u.kleine-koenig@baylibre.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
lib/math/div64.c

index 0ebff850fd4dd0877b8a9b38d7adacbb220b46d1..1092f41e878e51e38dcb4925d429bf8bc9bd80fd 100644 (file)
@@ -212,12 +212,16 @@ u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 d)
 
 #endif
 
-       /* make sure d is not zero, trigger runtime exception otherwise */
-       if (unlikely(d == 0)) {
-               unsigned long zero = 0;
+       if (unlikely(n_hi >= d)) {
+               /* trigger runtime exception if divisor is zero */
+               if (d == 0) {
+                       unsigned long zero = 0;
 
-               OPTIMIZER_HIDE_VAR(zero);
-               return ~0UL/zero;
+                       OPTIMIZER_HIDE_VAR(zero);
+                       return ~0UL/zero;
+               }
+               /* overflow: result is unrepresentable in a u64 */
+               return ~0ULL;
        }
 
        int shift = __builtin_ctzll(d);
@@ -234,11 +238,6 @@ u64 mul_u64_u64_div_u64(u64 a, u64 b, u64 d)
                 */
        }
 
-       if (n_hi >= d) {
-               /* overflow: result is unrepresentable in a u64 */
-               return -1;
-       }
-
        /* Do the full 128 by 64 bits division */
 
        shift = __builtin_clzll(d);