[PATCH v2 4/6] iio: proximity: hx9023s: reject out-of-range threshold values
From: Arnav Kapoor
Date: Thu Nov 26 2026 - 16:38:41 EST
The proximity thresholds are 10-bit register fields in units of 32.
hx9023s_set_thres_near() and hx9023s_set_thres_far() mask val / 32 with
GENMASK(9, 0) instead of checking it, so a value out of range is
silently written as a different threshold: 32768 becomes 0, the most
sensitive threshold, and -32 becomes 1023 * 32 = 32736, the least
sensitive one.
Return -EINVAL for negative values and values above 32767, the largest
value that still maps to the field. val >= BIT(15) catches both, as
BIT() is an unsigned long. The low 5 bits are still dropped, since the
field is in units of 32; add a comment saying so.
Fixes: 60df548277b7 ("iio: proximity: Add driver support for TYHX's HX9023S capacitive proximity sensor")
Signed-off-by: Arnav Kapoor <kapoorarnav43@xxxxxxxxx>
---
drivers/iio/proximity/hx9023s.c | 18 ++++++++++++++----
1 file changed, 14 insertions(+), 4 deletions(-)
diff --git a/drivers/iio/proximity/hx9023s.c b/drivers/iio/proximity/hx9023s.c
index d509de6e265b..2d2774398259 100644
--- a/drivers/iio/proximity/hx9023s.c
+++ b/drivers/iio/proximity/hx9023s.c
@@ -441,10 +441,15 @@ static int hx9023s_get_thres_far(struct hx9023s_data *data, u8 ch, int *val)
static int hx9023s_set_thres_near(struct hx9023s_data *data, u8 ch, int val)
{
- __le16 val_le16 = cpu_to_le16((val / 32) & GENMASK(9, 0));
+ __le16 val_le16;
unsigned int reg;
- data->ch_data[ch].thres.near = ((val / 32) & GENMASK(9, 0)) * 32;
+ if (val >= BIT(15))
+ return -EINVAL;
+
+ /* The field is in units of 32, so the low 5 bits are dropped */
+ val_le16 = cpu_to_le16(val / 32);
+ data->ch_data[ch].thres.near = val & ~GENMASK(4, 0);
reg = (ch == 4) ? HX9023S_PROX_HIGH_DIFF_CFG_CH4_0 :
HX9023S_PROX_HIGH_DIFF_CFG_CH0_0 + (ch * 2);
@@ -453,10 +458,15 @@ static int hx9023s_set_thres_near(struct hx9023s_data *data, u8 ch, int val)
static int hx9023s_set_thres_far(struct hx9023s_data *data, u8 ch, int val)
{
- __le16 val_le16 = cpu_to_le16((val / 32) & GENMASK(9, 0));
+ __le16 val_le16;
unsigned int reg;
- data->ch_data[ch].thres.far = ((val / 32) & GENMASK(9, 0)) * 32;
+ if (val >= BIT(15))
+ return -EINVAL;
+
+ /* The field is in units of 32, so the low 5 bits are dropped */
+ val_le16 = cpu_to_le16(val / 32);
+ data->ch_data[ch].thres.far = val & ~GENMASK(4, 0);
reg = (ch == 4) ? HX9023S_PROX_LOW_DIFF_CFG_CH4_0 :
HX9023S_PROX_LOW_DIFF_CFG_CH0_0 + (ch * 2);
--
2.53.0