[PATCH v2 5/6] iio: proximity: sx9360: fix proximity threshold writes
From: Arnav Kapoor
Date: Sun Nov 22 2026 - 02:47:32 EST
sx9360_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. sx9360_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: 1cdb4c47f7f5 ("iio:proximity:sx9360: Add sx9360 support")
Signed-off-by: Arnav Kapoor <kapoorarnav43@xxxxxxxxx>
---
drivers/iio/proximity/sx9360.c | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/drivers/iio/proximity/sx9360.c b/drivers/iio/proximity/sx9360.c
index 9ba967a33c98..9a2796f67949 100644
--- a/drivers/iio/proximity/sx9360.c
+++ b/drivers/iio/proximity/sx9360.c
@@ -508,10 +508,16 @@ static int sx9360_read_event_val(struct iio_dev *indio_dev,
static int sx9360_write_thresh(struct sx_common_data *data, int _val)
{
- unsigned int val = _val;
+ unsigned int val;
+
+ if (_val < 0)
+ return -EINVAL;
+
+ 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