[PATCH -mm] kstrtox: delete division from inner parsing loop
From: Alexey Dobriyan
Date: Fri Jul 03 2026 - 06:23:38 EST
Overflow conditions can be checked on the fly resulting in at most
2 very predictable branches and zero division instructions:
_parse_integer_limit:
...
mov rax, rdx
mul rsi
seto bl
add rax, rcx
mov rdx, rax
setb al
...
Signed-off-by: Alexey Dobriyan <adobriyan@xxxxxxxxx>
---
lib/kstrtox.c | 14 +++++---------
1 file changed, 5 insertions(+), 9 deletions(-)
diff --git a/lib/kstrtox.c b/lib/kstrtox.c
index 97be2a39f537..efd55db0533a 100644
--- a/lib/kstrtox.c
+++ b/lib/kstrtox.c
@@ -71,15 +71,11 @@ unsigned int _parse_integer_limit(const char *s, unsigned int base, unsigned lon
if (val >= base)
break;
- /*
- * Check for overflow only if we are within range of
- * it in the max base we support (16)
- */
- if (unlikely(res & (~0ull << 60))) {
- if (res > div_u64(ULLONG_MAX - val, base))
- rv |= KSTRTOX_OVERFLOW;
- }
- res = res * base + val;
+
+ if (check_mul_overflow(res, base, &res))
+ rv |= KSTRTOX_OVERFLOW;
+ if (check_add_overflow(res, val, &res))
+ rv |= KSTRTOX_OVERFLOW;
rv++;
s++;
}
--
2.54.0