Re: [PATCH v2 2/6] iio: proximity: sx9324: fix proximity threshold writes

From: Andy Shevchenko

Date: Mon Nov 23 2026 - 06:11:21 EST


On Sun, Nov 22, 2026 at 01:16:42PM +0530, Arnav Kapoor wrote:
> sx9324_read_thresh() reports a PROX_THRESH register value r as r for
> r <= 1 and as r * r / 2 otherwise, and the division rounds down for
> odd r. sx9324_write_thresh() inverts that with int_sqrt(2 * val), which
> is one register value too low when 2 * val == r * r - 1, so writing
> back the threshold read from an odd register value lowers it by one:
> setting the threshold to the value it already has changes it, for 127
> of the 256 register values (3, 5, 7, ...).
>
> Use int_sqrt(2 * val + 1), which gives the largest register value whose
> threshold does not exceed val: for r > 1, in integer arithmetic,
> r * r / 2 <= val is the same as r * r <= 2 * val + 1. The result only
> differs from int_sqrt(2 * val) on those edges. Checked for every val
> from 0 to 65535.
>
> Also reject negative values. They are converted to unsigned int, and
> 2 * val wraps at 32 bits on both 32-bit and 64-bit architectures, so
> e.g. INT_MIN is written as 0 and values just above INT_MIN as small
> thresholds instead of being rejected.

...

> {
> - unsigned int reg, val = _val;
> + unsigned int reg, val;
> +
> + if (_val < 0)
> + return -EINVAL;
>
> reg = SX9324_REG_PROX_CTRL6 + chan->channel / 2;
> + val = _val;


Why not simply

val = _val;
if (val < 0)
return -EINVAL;
...
reg = SX9324_REG_PROX_CTRL6 + chan->channel / 2;

Note, reg might still be not used, we have more validations and with your
approach the reg assignment is in the middle, confusing...

--
With Best Regards,
Andy Shevchenko