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

From: Andy Shevchenko

Date: Fri Nov 13 2026 - 09:47:32 EST


On Fri, Nov 13, 2026 at 04:04:56PM +0800, Zhu Jun wrote:
> 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.

...

> #include <linux/interrupt.h>
> #include <linux/irq.h>

> #include <linux/math.h>

This can be dropped now as it's implied by math64.h.

> +#include <linux/math64.h>
> #include <linux/minmax.h>
> #include <linux/module.h>
> +#include <linux/units.h>

...

> struct mcp9600_data *data = iio_priv(indio_dev);
> struct i2c_client *client = data->client;
> - int s_val, i;
> + s64 s_val;
> + int i;

Please, keep the reversed xmas tree order.

> s16 thresh;
> u8 hyst;

...

> /* 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);

I think we can avoid casting by doing

s_val = val < 0 ? -((val * MICRO) + val2) : ((val * 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);

This is also clamping.

...

> - thresh = (s16)(s_val / (1000000 >> 4));
> + thresh = (s16)div_s64(s_val, MICRO >> 4);

Do you need casting here?

> return i2c_smbus_write_word_swapped(client,
> MCP9600_ALERT_LIMIT(i + 1),
> thresh);

--
With Best Regards,
Andy Shevchenko