Re: [PATCH 2/6] iio: proximity: sx9324: fix proximity threshold writes

From: Andy Shevchenko

Date: Thu Nov 19 2026 - 05:17:15 EST


On Wed, Nov 18, 2026 at 03:36:05PM +0530, Arnav Kapoor wrote:
> On Wed, Nov 18, 2026 at 09:01:11AM +0200, Andy Shevchenko wrote:
> > For the sake of the correctness the whole set of 64k has to be checked. And in
> > most cases the + 1 there will be wrong. The only correction we need is on the
> > edges of the full squares, id est when val == r² - 1.
>
> I ran the v2 logic (reject val < 0, int_sqrt(2 * val + 1) for val > 1,
> reject results above 0xff) over every val from 0 to 65535. Values up to
> 32767 are accepted, and for each of them, apart from val == 0:
>
> code = largest r such that r * r / 2 <= val
>
> val == 0 stays at code 0, which reads back as 0 like code 1 does.
>
> The + 1 only changes the result where you say the correction is needed.
> int_sqrt(2 * val + 1) differs from int_sqrt(2 * val) for 127 values of
> val, and those are exactly the ones with 2 * val == r² - 1 for an odd r
> (val = 4, 12, 24, ..., 32512). For every other val both give the same
> code, so the + 1 has no effect there.
>
> The reason is that, in integer arithmetic:
>
> r * r / 2 <= val <=> r * r < 2 * val + 2 <=> r * r <= 2 * val + 1

Yes, for r > 1.

> > At bare minimum the commit message needs to be corrected and explained
> > these aspects that while the + 1 gives wrong result for most of the cases,
> > it's still okay to use as we work only in integer arithmetics. Also the formula
> > (r² - 1) / 2 has to be dropped as it's incorrect from mathematics point of
> > view. The floor() happens on / 2 and has nothing to do with (- 1) correction.
>
> Agreed on dropping the formula. For v2 I plan to replace that part of
> the commit message with:
>
> read_thresh() reports code r as r * r / 2, and the division rounds
> down for odd r. write_thresh() inverts that with int_sqrt(2 * val),
> which is one code too low when 2 * val == r * r - 1, so writing back
> the value read from an odd code lowers the code by one.
>
> Use int_sqrt(2 * val + 1), which gives the largest code whose
> threshold does not exceed val: 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.

s/code/value/g ?

> The same goes for 5/6. Does that cover what you had in mind?

Yes. This is much clearer, thanks!

--
With Best Regards,
Andy Shevchenko