Re: [PATCH v3] iio: temperature: mcp9600: Bound thresholds before scaling
From: Jonathan Cameron
Date: Thu Nov 12 2026 - 23:23:24 EST
On Thu, 12 Nov 2026 09:57:38 +0800
Zhu Jun <zhujun2@xxxxxxxxxxxxxxxxxxxx> wrote:
> mcp9600_write_thresh() multiplies the integer part by 1000000 before
> clamping to the supported temperature range. The multiplication can
> overflow int, so a request such as 3000 degrees can select the lower
> threshold instead of the upper threshold.
>
> Clamp the integer part to the hot-junction range before scaling. Keep
> the existing final clamp for fractional values and the narrower cold-
> junction range.
>
> Fixes: dea750f8015b ("iio: temperature: mcp9600: add threshold events support")
> Signed-off-by: Zhu Jun <zhujun2@xxxxxxxxxxxxxxxxxxxx>
> ---
> 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 | 3 +++
> 1 file changed, 3 insertions(+)
>
> diff --git a/drivers/iio/temperature/mcp9600.c b/drivers/iio/temperature/mcp9600.c
> index b0ff0c7b4891..00f1acb348a5 100644
> --- a/drivers/iio/temperature/mcp9600.c
> +++ b/drivers/iio/temperature/mcp9600.c
> @@ -17,6 +17,7 @@
> #include <linux/math.h>
> #include <linux/minmax.h>
> #include <linux/module.h>
> +#include <linux/units.h>
>
> #include <linux/iio/events.h>
> #include <linux/iio/iio.h>
> @@ -326,6 +327,8 @@ static int mcp9600_write_thresh(struct iio_dev *indio_dev,
> i = mcp9600_get_alert_index(chan->channel2, dir);
> switch (info) {
> case IIO_EV_INFO_VALUE:
> + val = clamp(val, MCP9600_MIN_TEMP_HOT_JUNCTION_MICRO / (int)MICRO,
> + MCP9600_MAX_TEMP_HOT_JUNCTION_MICRO / (int)MICRO);
Using micro here.
> /* Scale value to include decimal part into calculations */
> s_val = (val < 0) ? ((val * 1000000) - val2) :
> ((val * 1000000) + val2);
and not in these is less than obvious.
I also don't like the follow up of then clamping s_val to either similar bounds, or
tighter ones. Whilst I understand the inclination to keep to the
current behavior of clamping, that is really for things that are just
outside the range allowed due to numerical errors or similar. But doing it twice
is less than ideal
Two options here.
1. Just use a bigger type so we don't overflow. Then let the clamping that follows
do the work of dragging the massive value back down to sensible one.
2. Use the overflow checked add and mul from overflow.h Probably overkill.
Thanks,
Jonathan