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

From: Arnav Kapoor

Date: Mon Nov 16 2026 - 15:54:11 EST


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, 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: 4c18a890dff8 ("iio:proximity:sx9324: Add SX9324 support")
Signed-off-by: Arnav Kapoor <kapoorarnav43@xxxxxxxxx>
---
drivers/iio/proximity/sx9324.c | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/drivers/iio/proximity/sx9324.c b/drivers/iio/proximity/sx9324.c
index 93f9577bbda7..39760c92552b 100644
--- a/drivers/iio/proximity/sx9324.c
+++ b/drivers/iio/proximity/sx9324.c
@@ -617,8 +617,12 @@ static int sx9324_write_thresh(struct sx_common_data *data,

reg = SX9324_REG_PROX_CTRL6 + chan->channel / 2;

+ 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