Skip to contentSkip to conversation

PM: Avoid TOCTOU race in pm_wakeup_irq_show()

PATCH In review ankun 2 participants 2 messages Jun 11 – Jul 22

Subsystems (2)
lore
Share & tools
lore

ankun

author
#0 lore raw

PATCH 1/1 PM: Avoid TOCTOU race in pm_wakeup_irq_show()

pm_wakeup_irq_show() reads the global pm_wakeup_irq variable twice:
first to check if it is zero (returning -ENODATA if so), and then again to format the value for sysfs output. Between these two calls, the wakeup IRQ could be cleared (e.g. by writing 0 to the same sysfs file), leading to a time-of-check-to-time-of-use race. The result may be a printed value of 0 despite the check having passed, or other inconsistencies.

Cache the value in a local variable after a single read, and use that for both the check and the output. This closes the race window and makes the operation atomic from the caller's perspective.

---
 kernel/power/main.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/power/main.c +4 -2
index 5429e9f19b65..08a25117e38c 100644
@@ -683,10 +683,12 @@ static ssize_t pm_wakeup_irq_show(struct kobject *kobj,
 					struct kobj_attribute *attr,
 					char *buf)
 {
-	if (!pm_wakeup_irq())
+	unsigned int irq = pm_wakeup_irq();
+
+	if (!irq)
 		return -ENODATA;
 
-	return sysfs_emit(buf, "%u\n", pm_wakeup_irq());
+	return sysfs_emit(buf, "%u\n", irq);
 }
 
 power_attr_ro(pm_wakeup_irq);

--
2.20.1

#1 lore raw
Quoted 28 lines · ankun

pm_wakeup_irq_show() reads the global pm_wakeup_irq variable twice:
first to check if it is zero (returning -ENODATA if so), and then again to format the value for sysfs output. Between these two calls, the wakeup IRQ could be cleared (e.g. by writing 0 to the same sysfs file), leading to a time-of-check-to-time-of-use race. The result may be a printed value of 0 despite the check having passed, or other inconsistencies.

Cache the value in a local variable after a single read, and use that for both the check and the output. This closes the race window and makes the operation atomic from the caller's perspective.

---
 kernel/power/main.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/power/main.c +1 -1
index 5429e9f19b65..08a25117e38c 100644
@@ -683,10 +683,12 @@ static ssize_t pm_wakeup_irq_show(struct kobject *kobj,
                                        struct kobj_attribute *attr,
                                        char *buf)
 {
-       if (!pm_wakeup_irq())
+       unsigned int irq = pm_wakeup_irq();

kernel/power/main.c static ssize_t pm_wakeup_irq_show(struct kobject *kobj,

Quoted 10 lines
kernel/power/main.c +3 -2
+
+       if (!irq)
                return -ENODATA;
 
-       return sysfs_emit(buf, "%u\n", pm_wakeup_irq());
+       return sysfs_emit(buf, "%u\n", irq);
 }
 
 power_attr_ro(pm_wakeup_irq);
--

After the change though a stale pm_wakeup_irq() value may be printed (if it is updated in the meantime), so why bother?