[PATCH v4] iio: temperature: mcp9600: Avoid overflow when scaling thresholds

From: Zhu Jun

Date: Fri Nov 13 2026 - 03:22:25 EST


mcp9600_write_thresh() scales the integer part by 1000000 in int
arithmetic before clamping to the supported temperature range. The
multiplication can overflow, so a request such as 3000 degrees can
select the lower threshold instead of the upper threshold.

Cast MICRO to s64 before multiplying so that scaling and the fractional
addition or subtraction use signed 64-bit arithmetic. Let the existing
per-junction bounds clamp the result. Use MICRO consistently and use
div_s64() for the final conversion to support 32-bit architectures.

Fixes: dea750f8015b ("iio: temperature: mcp9600: add threshold events support")
Signed-off-by: Zhu Jun <zhujun2@xxxxxxxxxxxxxxxxxxxx>
---
Changes in v4:
- Use signed 64-bit arithmetic instead of clamping the integer part before
scaling, as suggested by Jonathan Cameron.
- Use MICRO for both scaling and conversion back to the register value,
with div_s64() for the final signed division on 32-bit architectures.

Changes in v3:
- Use clamp() instead of clamp_val(); all operands are int (Andy Shevchenko).

Changes in v2:
- Use MICRO from <linux/units.h>, cast to int to preserve
signed division for the negative temperature limit (Andy Shevchenko).

drivers/iio/temperature/mcp9600.c | 11 +++++++----
1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/drivers/iio/temperature/mcp9600.c b/drivers/iio/temperature/mcp9600.c
index b0ff0c7b4891..a7a37687bccc 100644
--- a/drivers/iio/temperature/mcp9600.c
+++ b/drivers/iio/temperature/mcp9600.c
@@ -15,8 +15,10 @@
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/math.h>
+#include <linux/math64.h>
#include <linux/minmax.h>
#include <linux/module.h>
+#include <linux/units.h>

#include <linux/iio/events.h>
#include <linux/iio/iio.h>
@@ -319,7 +321,8 @@ static int mcp9600_write_thresh(struct iio_dev *indio_dev,
{
struct mcp9600_data *data = iio_priv(indio_dev);
struct i2c_client *client = data->client;
- int s_val, i;
+ s64 s_val;
+ int i;
s16 thresh;
u8 hyst;

@@ -327,8 +330,8 @@ static int mcp9600_write_thresh(struct iio_dev *indio_dev,
switch (info) {
case IIO_EV_INFO_VALUE:
/* Scale value to include decimal part into calculations */
- s_val = (val < 0) ? ((val * 1000000) - val2) :
- ((val * 1000000) + val2);
+ s_val = (val < 0) ? ((val * (s64)MICRO) - val2) :
+ ((val * (s64)MICRO) + val2);
if (chan->channel2 == IIO_MOD_TEMP_AMBIENT) {
s_val = max(s_val, MCP9600_MIN_TEMP_COLD_JUNCTION_MICRO);
s_val = min(s_val, MCP9600_MAX_TEMP_COLD_JUNCTION_MICRO);
@@ -341,7 +344,7 @@ static int mcp9600_write_thresh(struct iio_dev *indio_dev,
* Shift length 4 bits = 2(15:2) + 2(0.25 LSB), temperature is
* stored in two’s complement format.
*/
- thresh = (s16)(s_val / (1000000 >> 4));
+ thresh = (s16)div_s64(s_val, MICRO >> 4);
return i2c_smbus_write_word_swapped(client,
MCP9600_ALERT_LIMIT(i + 1),
thresh);
--
2.51.0