[PATCH] hwmon: (ltc2991) Fix mixed signed/unsigned in DIV_ROUND_CLOSEST

From: David Lechner
Date: Wed Jan 15 2025 - 15:48:44 EST


Fix use of DIV_ROUND_CLOSEST where a possibly negative value is divided
by an unsigned type by casting the unsigned type to the signed type of
the same size (st->r_sense_uohm[channel] has type of u32).

The docs on the DIV_ROUND_CLOSEST macro explain that dividing a negative
value by an unsigned type is undefined behavior. The actual behavior is
that it converts both values to unsigned before doing the division, for
example:

int ret = DIV_ROUND_CLOSEST(-100, 3U);

results in ret == 1431655732 instead of -33.

Fixes: 2b9ea4262ae9 ("hwmon: Add driver for ltc2991")
Signed-off-by: David Lechner <dlechner@xxxxxxxxxxxx>
---
drivers/hwmon/ltc2991.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/hwmon/ltc2991.c b/drivers/hwmon/ltc2991.c
index 7ca139e4b6aff0b6c3024183e19970b36f927f6e..6d5d4cb846daf3025e55d43cfe311f38bb353621 100644
--- a/drivers/hwmon/ltc2991.c
+++ b/drivers/hwmon/ltc2991.c
@@ -125,7 +125,7 @@ static int ltc2991_get_curr(struct ltc2991_state *st, u32 reg, int channel,

/* Vx-Vy, 19.075uV/LSB */
*val = DIV_ROUND_CLOSEST(sign_extend32(reg_val, 14) * 19075,
- st->r_sense_uohm[channel]);
+ (s32)st->r_sense_uohm[channel]);

return 0;
}

---
base-commit: dab2734f8e9ecba609d66d1dd087a392a7774c04
change-id: 20250115-hwmon-ltc2991-fix-div-round-closest-c65c05afb881

Best regards,
--
David Lechner <dlechner@xxxxxxxxxxxx>