Re: [PATCH 1/2] iio: proximity: sx9310: reject unsupported hardware gain values

From: Jonathan Cameron

Date: Sat Nov 07 2026 - 14:06:59 EST


On Sat, 7 Nov 2026 16:47:03 +0530
Arnav Kapoor <kapoorarnav43@xxxxxxxxx> wrote:

> sx9310_write_gain() passes any value from userspace to ilog2() and then
> FIELD_PREP() into the 2-bit gain field without checking it. Only gains
> of 1, 2, 4 and 8 are supported (and listed in hardwaregain_available),
> but other values are not rejected; they are silently changed:
>
> - 3, 5, 6, 7 are rounded down to the next power of two;

There is nothing in the ABI rules that says a driver should not round these
values. So whilst I don't mind a specific driver not doing that I'm not
sure we should modify the ABI of a driver to start rejecting them after
it has been out there for a while. The only key thing is that value
read back after a write reflects the true scaling.

> - 16 and larger wrap around in the 2-bit field, e.g. 16 sets a gain
> of 1 and 32 a gain of 2;
> - 0 and negative values set the maximum gain of 8, because ilog2(0)
> is -1 and a negative int becomes a large unsigned value.

These two improvements are good and unlike rounding behaviour setting (including
reasonable rounding down to 32 - so anything that would not otherwise be 64) an
out of range scale or 0 / negative are not things correct userspace should
be doing.


>
> The write returns success in every case, so userspace cannot tell that
> the gain it asked for was not applied.
>
> Return -EINVAL for anything other than 1, 2, 4 or 8.
>
> Fixes: 227c83faa2f8 ("iio: sx9310: Support hardware gain factor")
> Signed-off-by: Arnav Kapoor <kapoorarnav43@xxxxxxxxx>
> ---
> drivers/iio/proximity/sx9310.c | 3 +++
> 1 file changed, 3 insertions(+)
>
> diff --git a/drivers/iio/proximity/sx9310.c b/drivers/iio/proximity/sx9310.c
> index 2585b9c6fb69..27b5d604a409 100644
> --- a/drivers/iio/proximity/sx9310.c
> +++ b/drivers/iio/proximity/sx9310.c
> @@ -665,6 +665,9 @@ static int sx9310_write_gain(struct sx_common_data *data,
> {
> unsigned int gain, mask;
>
> + if (val <= 0 || val > 8 || !is_power_of_2(val))
Upshot of above is check for <= 0 here.
> + return -EINVAL;
> +
> gain = ilog2(val);
and check this fits in the field. FIELD_FIT() will link that
explicitly to where it is being written. That only works here
because all the values that fit are valid (I think!)

Jonathan

>
> switch (chan->channel) {