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

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

The macro FAN_FROM_REG evaluates its 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 macro to a static function. 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/
Signed-off-by: Gui-Dong Han <hanguidong02@gmail.com>
Link: https://lore.kernel.org/r/20251126113542.9968-1-hanguidong02@gmail.com
Signed-off-by: Guenter Roeck <linux@roeck-us.net>

authored by

Gui-Dong Han and committed by
Guenter Roeck
be89cf78 fe5dbe31

+11 -5
+11 -5
drivers/hwmon/lm87.c
··· 116 116 (((val) < 0 ? (val) - 500 : \ 117 117 (val) + 500) / 1000)) 118 118 119 - #define FAN_FROM_REG(reg, div) ((reg) == 255 || (reg) == 0 ? 0 : \ 120 - (1350000 + (reg)*(div) / 2) / ((reg) * (div))) 119 + static int fan_from_reg(int reg, int div) 120 + { 121 + if (reg == 255 || reg == 0) 122 + return 0; 123 + 124 + return (1350000 + reg * div / 2) / (reg * div); 125 + } 126 + 121 127 #define FAN_TO_REG(val, div) ((val) * (div) * 255 <= 1350000 ? 255 : \ 122 128 (1350000 + (val)*(div) / 2) / ((val) * (div))) 123 129 ··· 471 465 struct lm87_data *data = lm87_update_device(dev); 472 466 int nr = to_sensor_dev_attr(attr)->index; 473 467 474 - return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr], 468 + return sprintf(buf, "%d\n", fan_from_reg(data->fan[nr], 475 469 FAN_DIV_FROM_REG(data->fan_div[nr]))); 476 470 } 477 471 ··· 481 475 struct lm87_data *data = lm87_update_device(dev); 482 476 int nr = to_sensor_dev_attr(attr)->index; 483 477 484 - return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan_min[nr], 478 + return sprintf(buf, "%d\n", fan_from_reg(data->fan_min[nr], 485 479 FAN_DIV_FROM_REG(data->fan_div[nr]))); 486 480 } 487 481 ··· 540 534 return err; 541 535 542 536 mutex_lock(&data->update_lock); 543 - min = FAN_FROM_REG(data->fan_min[nr], 537 + min = fan_from_reg(data->fan_min[nr], 544 538 FAN_DIV_FROM_REG(data->fan_div[nr])); 545 539 546 540 switch (val) {