Re: [PATCH 1/5] iio: proximity: hx9023s: fix division by zero in set_samp_freq
From: Andy Shevchenko
Date: Mon Nov 23 2026 - 14:14:47 EST
On Mon, Nov 23, 2026 at 10:22:47PM +0530, Arnav Kapoor wrote:
> hx9023s_set_samp_freq() passes val * MEGA + val2 to div_u64(), whose
> divisor is a u32, so the sum is truncated to 32 bits. MEGA is an
> unsigned long, so on 64-bit the product itself does not overflow, but
> the truncation does, and on 32-bit the product already wraps. Either
> way, any value for which val * MEGA + val2 is a multiple of 2^32 gives a
> zero divisor, e.g.
>
> echo 67108864 > sampling_frequency
>
> (67108864 * 10^6 = 15625 * 2^32) triggers a divide error, on both 32-bit
> and 64-bit architectures. Negative values wrap the same way (-67108864
> also gives 0), which the check added by commit a318cfc08537 ("iio:
> proximity: hx9023s: Protect against division by zero in set_samp_freq")
> does not catch, as it only rejects val == 0 && val2 == 0.
>
> Reject negative values and do the division in 64 bits with div64_u64().
...
> - if (!val && !val2)
> + if (val < 0 || val2 < 0 || (!val && !val2))
I think in this case the
if (val < 0 || val2 < 0 || (val == 0 && val2 == 0))
is slightly better as the consistent style in the same expression is used.
> return -EINVAL;
...
> - period_ms = div_u64(NANO, (val * MEGA + val2));
> + period_ms = div64_u64(NANO, (u64)val * MEGA + val2);
LOL! Why is this 64-bit division?! Anything more than NANO will give 0, no?
And NANO is 32-bit value.
--
With Best Regards,
Andy Shevchenko