Re: [PATCH][V2] x86/lib: Fix overflow of variable m when val >= 1410065408

From: Su Hui
Date: Thu Nov 02 2023 - 22:09:04 EST


On 2023/11/3 01:49, Colin Ian King wrote:
There is an overflow in variable m in function num_digits when val
is >= 1410065408 which leads to the digit calculation loop to
iterate more times than required. This results in either more
digits being counted or in some cases (for example where val is
1932683193) the value of m eventually overflows to zero and the
while loop spins forever).

Currently the function num_digits is currently only being used for
small values of val in the SMP boot stage for digit counting on the
number of cpus and NUMA nodes, so the overflow is never encountered.
However it is useful to fix the overflow issue in case the function
is used for other purposes in the future. (The issue was discovered
while investigating the digit counting performance in various
kernel helper functions rather than any real-world use-case).

The simplest fix is to make m a long long, the overhead in
multiplication speed for a long long is very minor for small values
of val less than 10000 on modern processors. The alternative
fix is to replace the multiplication with a constant division
by 10 loop (this compiles down to an multiplication and shift)
without needing to make m a long long, but this is slightly slower
than the fix in this commit when measured on a range of x86
processors).

Fixes: 646e29a1789a ("x86: Improve the printout of the SMP bootup CPU table")
Signed-off-by: Colin Ian King <colin.i.king@xxxxxxxxx>
---

V2: Make m long long instead of long to fix issue for i386 as well as
x86-64
---
arch/x86/lib/misc.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/arch/x86/lib/misc.c b/arch/x86/lib/misc.c
index 92cd8ecc3a2c..41e26e246d8f 100644
--- a/arch/x86/lib/misc.c
+++ b/arch/x86/lib/misc.c
@@ -8,7 +8,7 @@
*/
int num_digits(int val)

Hi,

num_digits() still has a problem when val = INT_MIN.
14 if (val < 0) {
15 d++;
16 val = -val;
^^^^^^^^^^^
When val = INT_MIN, -val still equal to INT_MIN.
Make 'val' long long instead of int to fix this issue.

Su Hui


{
- int m = 10;
+ long long m = 10;
int d = 1;
if (val < 0) {