[PATCH 2/2] hwmon: (cros_ec) Handle temperature conversion overflows
Thomas Weißschuh <[email protected]> Tue, 30 Jun 2026 22:57:52 +0200
| Newsgroups | dev.linux.lists.chrome-platform,org.kernel.vger.linux-hwmon,org.kernel.vger.linux-kernel |
|---|---|
| Message-ID | <[email protected]> |
The calculations converting between the different temperature units can overflow, resulting in incorrect data. Detect these overflows and report them. Signed-off-by: Thomas Weißschuh <[email protected]> --- drivers/hwmon/cros_ec_hwmon.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/drivers/hwmon/cros_ec_hwmon.c b/drivers/hwmon/cros_ec_hwmon.c index 44291799dd8e..4b402142b46f 100644 --- a/drivers/hwmon/cros_ec_hwmon.c +++ b/drivers/hwmon/cros_ec_hwmon.c @@ -5,11 +5,13 @@ * Copyright (C) 2024 Thomas Weißschuh <[email protected]> */ +#include <linux/build_bug.h> #include <linux/device.h> #include <linux/hwmon.h> #include <linux/math.h> #include <linux/mod_devicetable.h> #include <linux/module.h> +#include <linux/overflow.h> #include <linux/platform_device.h> #include <linux/platform_data/cros_ec_commands.h> #include <linux/platform_data/cros_ec_proto.h> @@ -150,14 +152,28 @@ static bool cros_ec_hwmon_is_error_temp(u8 temp) /* This differs slightly from the variant in units.h to avoid rounding inconsistencies. */ #define CROS_EC_HWMON_ABSOLUTE_ZERO_MILLICELSIUS (-273000) -static long cros_ec_hwmon_kelvin_to_millicelsius(long t) +static bool cros_ec_hwmon_kelvin_to_millicelsius_overflow(long t, long *ret) { - return t * MILLIDEGREE_PER_DEGREE + CROS_EC_HWMON_ABSOLUTE_ZERO_MILLICELSIUS; + if (check_mul_overflow(t, MILLIDEGREE_PER_DEGREE, ret)) + return true; + + if (check_add_overflow(*ret, CROS_EC_HWMON_ABSOLUTE_ZERO_MILLICELSIUS, ret)) + return true; + + return false; } -static long cros_ec_hwmon_temp_to_millicelsius(u8 temp) +static long __flatten cros_ec_hwmon_temp_to_millicelsius(u8 temp) { - return cros_ec_hwmon_kelvin_to_millicelsius((((long)temp) + EC_TEMP_SENSOR_OFFSET)); + long ret; + + if (check_add_overflow(temp, EC_TEMP_SENSOR_OFFSET, &ret)) + BUILD_BUG(); + + if (cros_ec_hwmon_kelvin_to_millicelsius_overflow(ret, &ret)) + BUILD_BUG(); + + return ret; } static bool cros_ec_hwmon_attr_is_temp_threshold(u32 attr) @@ -235,8 +251,10 @@ static int cros_ec_hwmon_read(struct device *dev, enum hwmon_sensor_types type, ret = cros_ec_hwmon_read_temp_threshold(priv->cros_ec, channel, cros_ec_hwmon_attr_to_thres(attr), &threshold); - if (ret == 0) - *val = cros_ec_hwmon_kelvin_to_millicelsius(threshold); + if (ret == 0) { + if (cros_ec_hwmon_kelvin_to_millicelsius_overflow(threshold, val)) + *val = LONG_MAX; + } } } -- 2.55.0