Skip to content

Commit be89cf7

Browse files
2045castorgroeck
authored andcommitted
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>
1 parent fe5dbe3 commit be89cf7

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

drivers/hwmon/lm87.c

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,14 @@ static u8 LM87_REG_TEMP_LOW[3] = { 0x3A, 0x38, 0x2C };
116116
(((val) < 0 ? (val) - 500 : \
117117
(val) + 500) / 1000))
118118

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+
121127
#define FAN_TO_REG(val, div) ((val) * (div) * 255 <= 1350000 ? 255 : \
122128
(1350000 + (val)*(div) / 2) / ((val) * (div)))
123129

@@ -465,7 +471,7 @@ static ssize_t fan_input_show(struct device *dev,
465471
struct lm87_data *data = lm87_update_device(dev);
466472
int nr = to_sensor_dev_attr(attr)->index;
467473

468-
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr],
474+
return sprintf(buf, "%d\n", fan_from_reg(data->fan[nr],
469475
FAN_DIV_FROM_REG(data->fan_div[nr])));
470476
}
471477

@@ -475,7 +481,7 @@ static ssize_t fan_min_show(struct device *dev, struct device_attribute *attr,
475481
struct lm87_data *data = lm87_update_device(dev);
476482
int nr = to_sensor_dev_attr(attr)->index;
477483

478-
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan_min[nr],
484+
return sprintf(buf, "%d\n", fan_from_reg(data->fan_min[nr],
479485
FAN_DIV_FROM_REG(data->fan_div[nr])));
480486
}
481487

@@ -534,7 +540,7 @@ static ssize_t fan_div_store(struct device *dev,
534540
return err;
535541

536542
mutex_lock(&data->update_lock);
537-
min = FAN_FROM_REG(data->fan_min[nr],
543+
min = fan_from_reg(data->fan_min[nr],
538544
FAN_DIV_FROM_REG(data->fan_div[nr]));
539545

540546
switch (val) {

0 commit comments

Comments
 (0)