Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

hwmon: (w83l786ng) Convert macros to functions to avoid TOCTOU

The macros FAN_FROM_REG and TEMP_FROM_REG evaluate their arguments
multiple times. When used in lockless contexts involving shared driver
data, this causes Time-of-Check to Time-of-Use (TOCTOU) race
conditions.

Convert the macros to static functions. This guarantees that arguments
are evaluated only once (pass-by-value), preventing the race
conditions.

Adhere to the principle of minimal changes by only converting macros
that evaluate arguments multiple times and are used in lockless
contexts.

Link: https://lore.kernel.org/all/CALbr=LYJ_ehtp53HXEVkSpYoub+XYSTU8Rg=o1xxMJ8=5z8B-g@mail.gmail.com/
Fixes: 85f03bccd6e0 ("hwmon: Add support for Winbond W83L786NG/NR")
Cc: stable@vger.kernel.org
Signed-off-by: Gui-Dong Han <hanguidong02@gmail.com>
Link: https://lore.kernel.org/r/20251128123816.3670-1-hanguidong02@gmail.com
Signed-off-by: Guenter Roeck <linux@roeck-us.net>

authored by

Gui-Dong Han and committed by
Guenter Roeck
07272e88 02f0ad8e

+18 -8
+18 -8
drivers/hwmon/w83l786ng.c
··· 76 76 return clamp_val((1350000 + rpm * div / 2) / (rpm * div), 1, 254); 77 77 } 78 78 79 - #define FAN_FROM_REG(val, div) ((val) == 0 ? -1 : \ 80 - ((val) == 255 ? 0 : \ 81 - 1350000 / ((val) * (div)))) 79 + static int fan_from_reg(int val, int div) 80 + { 81 + if (val == 0) 82 + return -1; 83 + if (val == 255) 84 + return 0; 85 + return 1350000 / (val * div); 86 + } 82 87 83 88 /* for temp */ 84 89 #define TEMP_TO_REG(val) (clamp_val(((val) < 0 ? (val) + 0x100 * 1000 \ 85 90 : (val)) / 1000, 0, 0xff)) 86 - #define TEMP_FROM_REG(val) (((val) & 0x80 ? \ 87 - (val) - 0x100 : (val)) * 1000) 91 + 92 + static int temp_from_reg(int val) 93 + { 94 + if (val & 0x80) 95 + return (val - 0x100) * 1000; 96 + return val * 1000; 97 + } 88 98 89 99 /* 90 100 * The analog voltage inputs have 8mV LSB. Since the sysfs output is ··· 290 280 int nr = to_sensor_dev_attr(attr)->index; \ 291 281 struct w83l786ng_data *data = w83l786ng_update_device(dev); \ 292 282 return sprintf(buf, "%d\n", \ 293 - FAN_FROM_REG(data->reg[nr], DIV_FROM_REG(data->fan_div[nr]))); \ 283 + fan_from_reg(data->reg[nr], DIV_FROM_REG(data->fan_div[nr]))); \ 294 284 } 295 285 296 286 show_fan_reg(fan); ··· 357 347 358 348 /* Save fan_min */ 359 349 mutex_lock(&data->update_lock); 360 - min = FAN_FROM_REG(data->fan_min[nr], DIV_FROM_REG(data->fan_div[nr])); 350 + min = fan_from_reg(data->fan_min[nr], DIV_FROM_REG(data->fan_div[nr])); 361 351 362 352 data->fan_div[nr] = DIV_TO_REG(val); 363 353 ··· 419 409 int nr = sensor_attr->nr; 420 410 int index = sensor_attr->index; 421 411 struct w83l786ng_data *data = w83l786ng_update_device(dev); 422 - return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[nr][index])); 412 + return sprintf(buf, "%d\n", temp_from_reg(data->temp[nr][index])); 423 413 } 424 414 425 415 static ssize_t