[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <20211222034646.222189-10-liambeguin@gmail.com>
Date: Tue, 21 Dec 2021 22:46:40 -0500
From: Liam Beguin <liambeguin@...il.com>
To: liambeguin@...il.com, peda@...ntia.se, jic23@...nel.org,
andy.shevchenko@...il.com, lars@...afoo.de
Cc: linux-kernel@...r.kernel.org, linux-iio@...r.kernel.org,
devicetree@...r.kernel.org, robh+dt@...nel.org
Subject: [PATCH v11 09/15] iio: afe: rescale: reduce risk of integer overflow
From: Liam Beguin <lvb@...hos.com>
Reduce the risk of integer overflow by doing the scale calculation on
a 64-bit integer. Since the rescaling is only performed on *val, reuse
the IIO_VAL_FRACTIONAL_LOG2 case.
Signed-off-by: Liam Beguin <lvb@...hos.com>
Reviewed-by: Peter Rosin <peda@...ntia.se>
---
drivers/iio/afe/iio-rescale.c | 23 ++++++++++++++++++-----
1 file changed, 18 insertions(+), 5 deletions(-)
diff --git a/drivers/iio/afe/iio-rescale.c b/drivers/iio/afe/iio-rescale.c
index ca8fd69bfe46..0000a58bab9d 100644
--- a/drivers/iio/afe/iio-rescale.c
+++ b/drivers/iio/afe/iio-rescale.c
@@ -23,21 +23,31 @@ int rescale_process_scale(struct rescale *rescale, int scale_type,
int *val, int *val2)
{
s64 tmp;
+ int _val, _val2;
s32 rem, rem2;
u32 mult;
u32 neg;
switch (scale_type) {
- case IIO_VAL_FRACTIONAL:
- *val *= rescale->numerator;
- *val2 *= rescale->denominator;
- return scale_type;
case IIO_VAL_INT:
*val *= rescale->numerator;
if (rescale->denominator == 1)
return scale_type;
*val2 = rescale->denominator;
return IIO_VAL_FRACTIONAL;
+ case IIO_VAL_FRACTIONAL:
+ /*
+ * When the product of both scales doesn't overflow, avoid
+ * potential accuracy loss (for in kernel consumers) by
+ * keeping a fractional representation.
+ */
+ if (!check_mul_overflow(*val, rescale->numerator, &_val) &&
+ !check_mul_overflow(*val2, rescale->denominator, &_val2)) {
+ *val = _val;
+ *val2 = _val2;
+ return IIO_VAL_FRACTIONAL;
+ }
+ fallthrough;
case IIO_VAL_FRACTIONAL_LOG2:
tmp = (s64)*val * 1000000000LL;
tmp = div_s64(tmp, rescale->denominator);
@@ -49,7 +59,10 @@ int rescale_process_scale(struct rescale *rescale, int scale_type,
if (!rem)
return scale_type;
- tmp = 1 << *val2;
+ if (scale_type == IIO_VAL_FRACTIONAL)
+ tmp = *val2;
+ else
+ tmp = 1 << *val2;
rem2 = *val % (int)tmp;
*val = *val / (int)tmp;
--
2.34.0
Powered by blists - more mailing lists