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

From: Andy Shevchenko

Date: Tue Nov 17 2026 - 13:59:18 EST


On Tue, Nov 17, 2026 at 02:23:10AM +0530, Arnav Kapoor wrote:
> sx9324_read_thresh() reports a PROX_THRESH code r as r for r <= 1 and as
> r * r / 2 otherwise, but sx9324_write_thresh() converts back with
> int_sqrt(2 * val).

> For odd r the read value is (r * r - 1) / 2,

No, it's r²/2 but in integer arithmetics. That's why for odd number squares
it gives 1/2 that becomes 0.

> so writing back the value that was just read programs r - 1: setting the
> threshold to the value it already has lowers it, for 127 of the 256
> codes (3, 5, 7, ...).
>
> The int to unsigned int conversion also lets some negative values
> through: 2 * val wraps, so e.g. INT_MIN is written as 0 and values just
> above INT_MIN as small thresholds instead of being rejected.
>
> Reject negative values and use int_sqrt(2 * val + 1), which picks the
> largest code whose reported threshold does not exceed the requested
> value and makes read_thresh() and write_thresh() inverses of each
> other for all 256 codes.

So, for the read part

reg value
0 0
1 1
2 2
3 4
4 8
5 12
6 18
7 24
....

For the write part (the negative is problematic only on 32-bit case IIUC)

value reg
-INT_MIN 0
-INT_MIN + 1 1
-INT_MIN + 2 2
-INT_MIN + 3 2
...
0 0
1 1
2 2
3 2
4 2 // has to be 3
5 3
6 3
7 3
8 4
9 4
...
12 4 // has to be 5
13 5
...
18 6
...
24 6 // has to be 7
...

Yep, what we see is off-by-one for full squares. This is because division
by 2 in integer arithmetics makes it floor number. So, what you want
to have is a correction for all odd numbers.

...

> static int sx9324_write_thresh(struct sx_common_data *data,

> reg = SX9324_REG_PROX_CTRL6 + chan->channel / 2;

This one is not used in the conditionals, so the new check may well be done
before it.

> + if (_val < 0)

Checking _val after assigning val to it is confusing.

> + return -EINVAL;
> +
> + /* Inverse of read_thresh(), so that writing back a read value is a no-op */
> if (val >= 1)

First of all, I would drop the '=' here.

> - val = int_sqrt(2 * val);
> + val = int_sqrt(2 * val + 1);

And here I would rather use (val % 2) instead of 1. See above why.

> if (val > 0xff)
> return -EINVAL;

--
With Best Regards,
Andy Shevchenko