[PATCH v2 2/6] iio: proximity: sx9324: fix proximity threshold writes
From: Arnav Kapoor
Date: Sun Nov 22 2026 - 02:47:14 EST
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.
Fixes: 4c18a890dff8 ("iio:proximity:sx9324: Add SX9324 support")
Signed-off-by: Arnav Kapoor <kapoorarnav43@xxxxxxxxx>
---
drivers/iio/proximity/sx9324.c | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
diff --git a/drivers/iio/proximity/sx9324.c b/drivers/iio/proximity/sx9324.c
index 93f9577bbda7..57fe78089167 100644
--- a/drivers/iio/proximity/sx9324.c
+++ b/drivers/iio/proximity/sx9324.c
@@ -613,12 +613,17 @@ static int sx9324_read_event_val(struct iio_dev *indio_dev,
static int sx9324_write_thresh(struct sx_common_data *data,
const struct iio_chan_spec *chan, int _val)
{
- unsigned int reg, val = _val;
+ unsigned int reg, val;
+
+ if (_val < 0)
+ return -EINVAL;
reg = SX9324_REG_PROX_CTRL6 + chan->channel / 2;
+ val = _val;
- if (val >= 1)
- val = int_sqrt(2 * val);
+ /* Inverse of read_thresh(), so that writing back a read value is a no-op */
+ if (val > 1)
+ val = int_sqrt(2 * val + 1);
if (val > 0xff)
return -EINVAL;
--
2.53.0