iio: core: Fix IIO_VAL_FRACTIONAL calculation for negative values
authorAnand Ashok Dumbre <anand.ashok.dumbre@xilinx.com>
Mon, 5 Oct 2020 15:05:16 +0000 (08:05 -0700)
committerJonathan Cameron <Jonathan.Cameron@huawei.com>
Sat, 10 Oct 2020 16:52:34 +0000 (17:52 +0100)
Fixes IIO_VAL_FRACTIONAL for case when the result is negative and
exponent is 0.

example: if the result is -0.75, tmp0 will be 0 and tmp1 = 75
This causes the output to lose sign because of %d in snprintf
which works for tmp0 <= -1.

Reported-by: kernel test robot <lkp@intel.com> #error: uninitialized symbol tmp
Reported-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Anand Ashok Dumbre <anand.ashok.dumbre@xilinx.com>
Link: https://lore.kernel.org/r/1601910316-24111-1-git-send-email-anand.ashok.dumbre@xilinx.com
Signed-off-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>
drivers/iio/industrialio-core.c

index 261d3b17edc9a9da82066a31d155b8194471c802..9955672fc16ae85990bf3830a6063bc2ee7b8338 100644 (file)
@@ -594,6 +594,7 @@ static ssize_t __iio_format_value(char *buf, size_t len, unsigned int type,
 {
        unsigned long long tmp;
        int tmp0, tmp1;
+       s64 tmp2;
        bool scale_db = false;
 
        switch (type) {
@@ -616,10 +617,13 @@ static ssize_t __iio_format_value(char *buf, size_t len, unsigned int type,
                else
                        return scnprintf(buf, len, "%d.%09u", vals[0], vals[1]);
        case IIO_VAL_FRACTIONAL:
-               tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
+               tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
                tmp1 = vals[1];
-               tmp0 = (int)div_s64_rem(tmp, 1000000000, &tmp1);
-               return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
+               tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
+               if ((tmp2 < 0) && (tmp0 == 0))
+                       return snprintf(buf, len, "-0.%09u", abs(tmp1));
+               else
+                       return snprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
        case IIO_VAL_FRACTIONAL_LOG2:
                tmp = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
                tmp0 = (int)div_s64_rem(tmp, 1000000000LL, &tmp1);