[PATCH 5/6] iio: proximity: sx9360: fix proximity threshold writes

From: Arnav Kapoor

Date: Mon Nov 16 2026 - 15:55:13 EST


sx9360_read_thresh() reports a PROX_THRESH code r as r for r <= 1 and as
r * r / 2 otherwise, but sx9360_write_thresh() converts back with
int_sqrt(2 * val). For odd r the read value is (r * r - 1) / 2, 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.

Fixes: 1cdb4c47f7f5 ("iio:proximity:sx9360: Add sx9360 support")
Signed-off-by: Arnav Kapoor <kapoorarnav43@xxxxxxxxx>
---
drivers/iio/proximity/sx9360.c | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/drivers/iio/proximity/sx9360.c b/drivers/iio/proximity/sx9360.c
index 9ba967a33c98..26190f9c6c1f 100644
--- a/drivers/iio/proximity/sx9360.c
+++ b/drivers/iio/proximity/sx9360.c
@@ -510,8 +510,12 @@ static int sx9360_write_thresh(struct sx_common_data *data, int _val)
{
unsigned int val = _val;

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

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