thermal/drivers/rcar_thermal: wait for IRQs before cancelling work
PATCH 1/1 thermal/drivers/rcar_thermal: wait for IRQs before cancelling work
rcar_thermal_remove() masks the interrupt sources and cancels the delayed work of each sensor. rcar_thermal_irq() reads INTMSK and STR under common->lock, drops the lock, and only then walks the sensors and queues priv->work for every sensor whose status changed.
A handler that sampled the status before the mask was written can therefore reach queue_delayed_work() after cancel_delayed_work_sync() has returned. The work stays pending past the end of ->remove(), devres then frees common, priv and the thermal zone, and rcar_thermal_work() runs 300 ms later on freed memory.
Waiting for the handler is not enough on its own: rcar_thermal_work() calls rcar_thermal_irq_enable() once it has updated the temperature, so a work that is still running when the removal starts re-enables its source and undoes the mask that ->remove() has just written.
Record the shutdown in rcar_thermal_common under common->lock and make _rcar_thermal_irq_ctrl() refuse to enable anything once that state is visible. The removal then publishes the shutdown, masks all sources, waits for the handlers with synchronize_irq() and only then cancels the work, so neither a source nor a work item can be brought back after it returns.
---
Prepared against v7.4-rc1-1969-g666539eecdf4.
AI assistance: the analysis, the change and its review notes were prepared with Claude (Anthropic) as a coding assistant. The author reviewed the reasoning and takes responsibility for the content.
Testing: compile tested only (arm64, gcc 11.4). No R-Car hardware was available, so the unbind race was not run.
drivers/thermal/renesas/rcar_thermal.c | 43 +++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-)
drivers/thermal/renesas/rcar_thermal.c +42 -1
@@ -39,11 +39,17 @@/* THSSR */ #define CTEMP 0x3f +/* .nirqs of every supported chip is at most this */ +#define RCAR_THERMAL_MAX_IRQ 2 +struct rcar_thermal_common {void __iomem *base;struct device *dev;struct list_head head;spinlock_t lock; +bool shutdown; +int irqs[RCAR_THERMAL_MAX_IRQ ]; +int nirqs; };struct rcar_thermal_chip {
@@ -301,6 +307,15 @@ static void _rcar_thermal_irq_ctrl(struct rcar_thermal_priv *priv, int enable)spin_lock_irqsave (&common->lock, flags); +/* +* rcar_thermal_work() re-enables its source when it finishes, so a +* work that was still running when the device went away would undo +* the mask that rcar_thermal_remove() writes. Once the shutdown +* state is visible nothing may enable the sources again. +*/ +if (common->shutdown) + enable =0 ; +rcar_thermal_common_bset (common,INTMSK , mask, enable ?0 : mask);spin_unlock_irqrestore (&common->lock, flags);
@@ -376,9 +391,33 @@ static void rcar_thermal_remove(struct platform_device *pdev)struct rcar_thermal_common *common =platform_get_drvdata (pdev);struct device *dev = &pdev->dev;struct rcar_thermal_priv *priv; +unsigned long flags; +int i; -rcar_thermal_for_each_priv (priv, common) { +/* +* Publish the shutdown state before anything else: a work that is +* still running re-enables its interrupt source on its way out, and +* has to be prevented from undoing the mask written below. +*/ +spin_lock_irqsave (&common->lock, flags); + common->shutdown = true; +spin_unlock_irqrestore (&common->lock, flags); + +/* +* Mask the sources, then wait for a handler that sampled the status +* before the mask was written. The handler drops common->lock +* before it queues the work, so without the wait it could queue +* priv->work after cancel_delayed_work_sync() has returned and leave +* the work running on a priv that devres frees once ->remove() has +* finished. +*/ +rcar_thermal_for_each_priv (priv, common)rcar_thermal_irq_disable (priv); + +for (i =0 ; i < common->nirqs; i++) +synchronize_irq (common->irqs[i]); + +rcar_thermal_for_each_priv (priv, common) {cancel_delayed_work_sync (&priv->work);if (priv->chip->use_of_thermal)thermal_remove_hwmon_sysfs (priv->zone);
@@ -449,6 +488,8 @@ static int rcar_thermal_probe(struct platform_device *pdev)if (ret) goto error_unregister; + common->irqs[common->nirqs++] = irq; +/* update ENR bits */ if (chip->irq_per_ch) enr_bits |=1 << i;
Signature · 1 line
2.34.1
Hi Yaohan,
Thanks for your work.
Quoted 81 lines · Yaohan Li
rcar_thermal_remove()masks the interrupt sources and cancels the delayed work of each sensor.rcar_thermal_irq()reads INTMSK and STR undercommon->lock, drops the lock, and only then walks the sensors and queuespriv->workfor every sensor whose status changed.A handler that sampled the status before the mask was written can therefore reach
queue_delayed_work()aftercancel_delayed_work_sync()has returned. The work stays pending past the end of ->remove(), devres then frees common, priv and the thermal zone, andrcar_thermal_work()runs 300 ms later on freed memory.Waiting for the handler is not enough on its own:
rcar_thermal_work()callsrcar_thermal_irq_enable()once it has updated the temperature, so a work that is still running when the removal starts re-enables its source and undoes the mask that ->remove() has just written.Record the shutdown in
rcar_thermal_commonundercommon->lockand make_rcar_thermal_irq_ctrl()refuse to enable anything once that state is visible. The removal then publishes the shutdown, masks all sources, waits for the handlers withsynchronize_irq()and only then cancels the work, so neither a source nor a work item can be brought back after it returns.Fixes 697ee786f15d ("thermal: rcar_thermal: Prevent doing work after unbind")Signed-off-by Yaohan Li <[email protected]>---
Prepared against v7.4-rc1-1969-g666539eecdf4.AI assistance: the analysis, the change and its review notes were prepared with Claude (Anthropic) as a coding assistant. The author reviewed the reasoning and takes responsibility for the content.
Testing: compile tested only (arm64, gcc 11.4). No R-Car hardware was available, so the unbind race was not run.
drivers/thermal/renesas/rcar_thermal.c | 43 +++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-)drivers/thermal/renesas/rcar_thermal.c +17
-0@@ -39,11 +39,17 @@/* THSSR */ #define CTEMP 0x3f +/* .nirqs of every supported chip is at most this */ +#define RCAR_THERMAL_MAX_IRQ 2 +struct rcar_thermal_common {void __iomem *base;struct device *dev;struct list_head head;spinlock_t lock; +bool shutdown; +int irqs[RCAR_THERMAL_MAX_IRQ ]; +int nirqs; };struct rcar_thermal_chip {@@ -301,6 +307,15 @@ static void _rcar_thermal_irq_ctrl(struct rcar_thermal_priv *priv, int enable)spin_lock_irqsave (&common->lock, flags); +/* +* rcar_thermal_work() re-enables its source when it finishes, so a +* work that was still running when the device went away would undo +* the mask that rcar_thermal_remove() writes. Once the shutdown +* state is visible nothing may enable the sources again. +*/ +if (common->shutdown) + enable =0 ; +rcar_thermal_common_bset (common,INTMSK , mask, enable ?0 : mask);spin_unlock_irqrestore (&common->lock, flags);@@ -376,9 +391,33 @@ static void rcar_thermal_remove(struct platform_device *pdev)struct rcar_thermal_common *common =platform_get_drvdata (pdev);struct device *dev = &pdev->dev;struct rcar_thermal_priv *priv; +unsigned long flags; +int i;
drivers/thermal/renesas/rcar_thermal.c static void rcar_thermal_remove(struct platform_device *pdev) · line 404
Quoted 10 lines
drivers/thermal/renesas/rcar_thermal.c +8
-1-rcar_thermal_for_each_priv (priv, common) { +/* +* Publish the shutdown state before anything else: a work that is +* still running re-enables its interrupt source on its way out, and +* has to be prevented from undoing the mask written below. +*/ +spin_lock_irqsave (&common->lock, flags); + common->shutdown = true; +spin_unlock_irqrestore (&common->lock, flags);
Adding a shutdown flag seems like a lot of complexity for somehting like this. Would not being more clever here avoid that? Maybe something like this,
/* No more work will be able to queued hence the irq can not rearm
* itself from the top half.
*/
disable_work_sync()
/* Disable any new interrupts in case they currently are enabled. */
rcar_thermal_irq_disable()
/* Wait for any bottom half interrupt to complete. */
synchronize_irq()
Now there can't be any races!For this flag,
Quoted 31 lines
drivers/thermal/renesas/rcar_thermal.c +17
-0+ +/* +* Mask the sources, then wait for a handler that sampled the status +* before the mask was written. The handler drops common->lock +* before it queues the work, so without the wait it could queue +* priv->work after cancel_delayed_work_sync() has returned and leave +* the work running on a priv that devres frees once ->remove() has +* finished. +*/ +rcar_thermal_for_each_priv (priv, common)rcar_thermal_irq_disable (priv); + +for (i =0 ; i < common->nirqs; i++) +synchronize_irq (common->irqs[i]); + +rcar_thermal_for_each_priv (priv, common) {cancel_delayed_work_sync (&priv->work);if (priv->chip->use_of_thermal)thermal_remove_hwmon_sysfs (priv->zone);@@ -449,6 +488,8 @@ static int rcar_thermal_probe(struct platform_device *pdev)if (ret) goto error_unregister; + common->irqs[common->nirqs++] = irq; +/* update ENR bits */ if (chip->irq_per_ch) enr_bits |=1 << i;Signature · 1 line
2.34.1
Signature · 2 lines
Kind Regards, Niklas Söderlund
PATCH v2 1/1 thermal/drivers/rcar_thermal: disable the work before masking the interrupt
In reply to Yaohan Lircar_thermal_remove() masks the interrupt sources and then cancels the delayed work of each sensor. rcar_thermal_irq() drops common->lock before it walks the sensors and queues priv->work for those whose status changed, so a handler that read the status before the mask was written can still queue the work after cancel_delayed_work_sync() has returned. The work then runs after ->remove() has finished and devres has freed common, priv and the thermal zone.
Waiting for the handler alone is not enough either: rcar_thermal_work() re-enables its interrupt source once it has updated the temperature, so a work that is still running when the removal starts undoes the mask that ->remove() has just written.
Disable the work before the source is masked. That makes the queue_delayed_work() calls in rcar_thermal_irq() no-ops and guarantees that the re-enable in rcar_thermal_work() has already happened, so the mask that follows cannot be undone.
The interrupt line is shared, so waiting for the handler once does not keep it from running again later; unregister it in ->remove() instead of only calling synchronize_irq(). devm_free_irq() waits for a handler that is running right now as well, and the slot is marked unused so that the probe failure path, which also ends here, cannot release it twice.
Every sensor that the removal walks has been through INIT_DELAYED_WORK() before it is linked into common->head, so no uninitialised work is touched. The interrupt numbers are recorded in an array whose unused slots stay negative, instead of being counted separately.
---
Prepared against v7.4-rc1-1969-g666539eecdf4.
Compile tested only: arm64, aarch64-linux-gnu-gcc 11.4, CONFIG_RCAR_THERMAL=y. No hardware was available, so the removal path was not exercised and no race injection was run.
AI assistance: prepared with Claude (Anthropic) as a coding assistant; the author reviewed the reasoning and takes responsibility for the content.
Changes in v2:
- Drop the shutdown flag and the separate IRQ count. Niklas asked for less state, so the removal now disables the delayed work before the source is masked and unregisters the shared IRQ instead of waiting for it once.
- Keep the interrupt numbers in an array whose unused slots stay negative.
--- drivers/thermal/renesas/rcar_thermal.c | 37 ++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-)
drivers/thermal/renesas/rcar_thermal.c +35 -2
@@ -39,11 +39,15 @@/* THSSR */ #define CTEMP 0x3f +/* .nirqs of every supported chip is at most this */ +#define RCAR_THERMAL_MAX_IRQ 2 +struct rcar_thermal_common {void __iomem *base;struct device *dev;struct list_head head;spinlock_t lock; +int irqs[RCAR_THERMAL_MAX_IRQ ]; };struct rcar_thermal_chip {
@@ -376,10 +380,34 @@ static void rcar_thermal_remove(struct platform_device *pdev)struct rcar_thermal_common *common =platform_get_drvdata (pdev);struct device *dev = &pdev->dev;struct rcar_thermal_priv *priv; +int i; -rcar_thermal_for_each_priv (priv, common) { +/* +* Stop the work from being queued again and wait for a running one to +* finish before the interrupt source is masked: rcar_thermal_work() +* re-enables its source when it is done, so it has to be gone before +* the source is disabled for good. +*/ +rcar_thermal_for_each_priv (priv, common) +disable_delayed_work_sync (&priv->work); + +rcar_thermal_for_each_priv (priv, common)rcar_thermal_irq_disable (priv); -cancel_delayed_work_sync (&priv->work); + +/* +* The handler is shared, so waiting for it once is not enough: another +* user of the line can invoke it again after that, when the zones and +* the sensors it walks are already gone. Unregister it here; that +* waits for a handler that is running right now as well. +*/ +for (i =0 ; i <RCAR_THERMAL_MAX_IRQ ; i++) { +if (common->irqs[i] <0 ) +continue ; +devm_free_irq (dev, common->irqs[i], common); + common->irqs[i] = -ENOENT ; + } + +rcar_thermal_for_each_priv (priv, common) {if (priv->chip->use_of_thermal)thermal_remove_hwmon_sysfs (priv->zone);else
@@ -413,6 +441,9 @@ static int rcar_thermal_probe(struct platform_device *pdev)spin_lock_init (&common->lock); common->dev = dev; +for (i =0 ; i <RCAR_THERMAL_MAX_IRQ ; i++) + common->irqs[i] = -ENOENT ; +pm_runtime_enable (dev);pm_runtime_get_sync (dev);
@@ -449,6 +480,8 @@ static int rcar_thermal_probe(struct platform_device *pdev)if (ret) goto error_unregister; + common->irqs[i] = irq; +/* update ENR bits */ if (chip->irq_per_ch) enr_bits |=1 << i;
Signature · 1 line
2.34.1
Niklas Söderlund
maintainerRe: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Yaohan,
Thanks for your work.
Quoted 32 lines · Yaohan Li
rcar_thermal_remove()masks the interrupt sources and then cancels the delayed work of each sensor.rcar_thermal_irq()dropscommon->lockbefore it walks the sensors and queuespriv->workfor those whose status changed, so a handler that read the status before the mask was written can still queue the work aftercancel_delayed_work_sync()has returned. The work then runs after ->remove() has finished and devres has freed common, priv and the thermal zone.Waiting for the handler alone is not enough either:
rcar_thermal_work()re-enables its interrupt source once it has updated the temperature, so a work that is still running when the removal starts undoes the mask that ->remove() has just written.Disable the work before the source is masked. That makes the
queue_delayed_work()calls inrcar_thermal_irq()no-ops and guarantees that the re-enable inrcar_thermal_work()has already happened, so the mask that follows cannot be undone.The interrupt line is shared, so waiting for the handler once does not keep it from running again later; unregister it in ->remove() instead of only calling
synchronize_irq().devm_free_irq()waits for a handler that is running right now as well, and the slot is marked unused so that the probe failure path, which also ends here, cannot release it twice.Every sensor that the removal walks has been through
INIT_DELAYED_WORK()before it is linked intocommon->head, so no uninitialised work is touched. The interrupt numbers are recorded in an array whose unused slots stay negative, instead of being counted separately.Fixes 697ee786f15d ("thermal: rcar_thermal: Prevent doing work after unbind")Signed-off-by Yaohan Li <[email protected]>
Quoted 6 lines
---
Prepared against v7.4-rc1-1969-g666539eecdf4.Compile tested only: arm64, aarch64-linux-gnu-gcc 11.4,
CONFIG_RCAR_THERMAL=y. No hardware was available, so the removal path was not exercised and no race injection was run.
Ohh, could you test this please. It's a rather large change and while it looks correct it could behave differently then expected.
Quoted 18 lines
AI assistance: prepared with Claude (Anthropic) as a coding assistant; the author reviewed the reasoning and takes responsibility for the content.
Changes in v2:
- Drop the shutdown flag and the separate IRQ count. Niklas asked for less state, so the removal now disables the delayed work before the source is masked and unregisters the shared IRQ instead of waiting for it once.
- Keep the interrupt numbers in an array whose unused slots stay negative.--- drivers/thermal/renesas/rcar_thermal.c | 37 ++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-)drivers/thermal/renesas/rcar_thermal.c +0
-0
drivers/thermal/renesas/rcar_thermal.c line 42
Quoted 4 lines
drivers/thermal/renesas/rcar_thermal.c +1
-0@@ -39,11 +39,15 @@/* THSSR */ #define CTEMP 0x3f +/* .nirqs of every supported chip is at most this */
.nirqs is not really needed here. Just say something along the line of max number of supported interrupts or some such.
Quoted 12 lines
drivers/thermal/renesas/rcar_thermal.c +3
-0+#define RCAR_THERMAL_MAX_IRQ 2 +struct rcar_thermal_common {void __iomem *base;struct device *dev;struct list_head head;spinlock_t lock; +int irqs[RCAR_THERMAL_MAX_IRQ ]; };struct rcar_thermal_chip {
drivers/thermal/renesas/rcar_thermal.c static void rcar_thermal_remove(struct platform_device *pdev) · line 383
Quoted 4 lines
drivers/thermal/renesas/rcar_thermal.c +1
-0@@ -376,10 +380,34 @@ static void rcar_thermal_remove(struct platform_device *pdev)struct rcar_thermal_common *common =platform_get_drvdata (pdev);struct device *dev = &pdev->dev;struct rcar_thermal_priv *priv; +int i;
unsigned.
drivers/thermal/renesas/rcar_thermal.c static void rcar_thermal_remove(struct platform_device *pdev) · line 389
Quoted 7 lines
drivers/thermal/renesas/rcar_thermal.c +5
-1-rcar_thermal_for_each_priv (priv, common) { +/* +* Stop the work from being queued again and wait for a running one to +* finish before the interrupt source is masked: rcar_thermal_work() +* re-enables its source when it is done, so it has to be gone before +* the source is disabled for good.
I think you can make this less verbose and more to the point.
drivers/thermal/renesas/rcar_thermal.c static void rcar_thermal_remove(struct platform_device *pdev) · line 399
Quoted 11 lines
drivers/thermal/renesas/rcar_thermal.c +9
-1+*/ +rcar_thermal_for_each_priv (priv, common) +disable_delayed_work_sync (&priv->work); + +rcar_thermal_for_each_priv (priv, common)rcar_thermal_irq_disable (priv); -cancel_delayed_work_sync (&priv->work); + +/* +* The handler is shared, so waiting for it once is not enough: another +* user of the line can invoke it again after that, when the zones and
line?
drivers/thermal/renesas/rcar_thermal.c static void rcar_thermal_remove(struct platform_device *pdev) · line 401
Quoted 2 lines
drivers/thermal/renesas/rcar_thermal.c +2
-0+* the sensors it walks are already gone. Unregister it here; that +* waits for a handler that is running right now as well.
I don't understand this.
drivers/thermal/renesas/rcar_thermal.c static void rcar_thermal_remove(struct platform_device *pdev) · line 402
Quoted 2 lines
drivers/thermal/renesas/rcar_thermal.c +2
-0+*/ +for (i =0 ; i <RCAR_THERMAL_MAX_IRQ ; i++) {
Please declare the loop variable in the for () statement to reduce scope.
Quoted 11 lines
drivers/thermal/renesas/rcar_thermal.c +7
-0+if (common->irqs[i] <0 ) +continue ; +devm_free_irq (dev, common->irqs[i], common); + common->irqs[i] = -ENOENT ; + } + +rcar_thermal_for_each_priv (priv, common) {if (priv->chip->use_of_thermal)thermal_remove_hwmon_sysfs (priv->zone);else
drivers/thermal/renesas/rcar_thermal.c static int rcar_thermal_probe(struct platform_device *pdev) · line 444
Quoted 4 lines
drivers/thermal/renesas/rcar_thermal.c +1
-0@@ -413,6 +441,9 @@ static int rcar_thermal_probe(struct platform_device *pdev)spin_lock_init (&common->lock); common->dev = dev; +for (i =0 ; i <RCAR_THERMAL_MAX_IRQ ; i++)
Here you can't declare the loop variable as the function already declares it at the function level. This is likely because this function pre-dates when it was OK to declare it directly in the loop definition.
No need to update old tested code en-mass, but lets use the better way in new code.
Quoted 17 lines
drivers/thermal/renesas/rcar_thermal.c +4
-0+ common->irqs[i] = -ENOENT ; +pm_runtime_enable (dev);pm_runtime_get_sync (dev);@@ -449,6 +480,8 @@ static int rcar_thermal_probe(struct platform_device *pdev)if (ret) goto error_unregister; + common->irqs[i] = irq; +/* update ENR bits */ if (chip->irq_per_ch) enr_bits |=1 << i;Signature · 1 line
2.34.1
Signature · 2 lines
Kind Regards, Niklas Söderlund
Re: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Niklas,
thanks for the review. The code changes you asked for are in my tree, and I would like to check the testing question with you before posting a v3.
The delayed work is now disabled before the interrupt source is masked, so the handler cannot queue new work after the cancellation, and a work that is already running cannot re-enable the source behind the mask. The shared interrupt is unregistered with devm_free_irq() rather than waited for with synchronize_irq(): the line stays registered for its other users, and they can raise it again after synchronize_irq() returns. The RCAR_THERMAL_MAX_IRQ comment, the loop variable and the two comments in rcar_thermal_remove() are as you suggested, and the shutdown flag is gone.
On testing: there is no R-Car hardware here, so what I have is a controlled ordering test on a KASAN kernel, 17 checks, all passing. It uses the real delayed work, workqueue, wait and signal machinery and a simulated interrupt line shared by two handlers. It shows that a work queued after cancel_delayed_work_sync() still runs while the same queue attempt after disable_delayed_work_sync() is rejected, that a running work undoes a mask written before the cancellation, and that after synchronize_irq() another user of the line can invoke our handler again while devm_free_irq() ends that.
What the test does not do is run rcar_thermal's own ->remove(). It re-implements the removal ordering, because exercising the driver would need a real platform device, MMIO and a thermal zone, so the behaviour of the interrupt status registers on real hardware remains unverified.
I can send the v3 with these changes if that is useful; if you would rather see a different shape for the removal sequence, I will rework that first.
Thanks,
Yaohan
Niklas Söderlund
maintainerRe: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Yaohan,
Thanks for your explanation.
Quoted 14 lines · Yaohan Li
Hi Niklas,
thanks for the review. The code changes you asked for are in my tree, and I would like to check the testing question with you before posting a v3.
The delayed work is now disabled before the interrupt source is masked, so the handler cannot queue new work after the cancellation, and a work that is already running cannot re-enable the source behind the mask. The shared interrupt is unregistered with
devm_free_irq()rather than waited for withsynchronize_irq(): the line stays registered for its other users, and they can raise it again aftersynchronize_irq()returns. TheRCAR_THERMAL_MAX_IRQcomment, the loop variable and the two comments inrcar_thermal_remove()are as you suggested, and the shutdown flag is gone.
Quoted 2 lines
On testing: there is no R-Car hardware here, so what I have is a controlled ordering test on a KASAN kernel, 17 checks, all passing.
Is it possible to share the test-cases? And are they relatively simple to run? I do have hardware to test on, and I would be happy to run some test and see stuff fail without this patch and that this work solves it.
Quoted 19 lines
It uses the real
delayed work, workqueue, wait and signal machinery and a simulated interrupt line shared by two handlers. It shows that a work queued aftercancel_delayed_work_sync()still runs while the same queue attempt afterdisable_delayed_work_sync()is rejected, that a running work undoes a mask written before the cancellation, and that aftersynchronize_irq()another user of the line can invoke our handler again whiledevm_free_irq()ends that.What the test does not do is run rcar_thermal's own ->remove(). It re-implements the removal ordering, because exercising the driver would need a real platform device, MMIO and a thermal zone, so the behaviour of the interrupt status registers on real hardware remains unverified.
I can send the v3 with these changes if that is useful; if you would rather see a different shape for the removal sequence, I will rework that first.
Thanks,
Yaohan
Signature · 2 lines
Kind Regards, Niklas Söderlund
Re: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Niklas,
yes, of course. It is one module, self-contained, and it needs no device tree or hardware setup - it builds against the tree you give it and runs on the board you load it on.
The module exercises the three primitives the removal ordering depends on:
- a work queued after cancel_delayed_work_sync() still runs, while the same queue attempt after disable_delayed_work_sync() is rejected and the work never runs;
- a work that is already running re-enables the source behind a mask that was written before the cancellation, and cannot do that when the work is disabled first;
- on a line shared with another handler, synchronize_irq() does not stop our handler from being invoked again (and from queueing the work), while devm_free_irq() does, without disturbing the other user.
To run it:
make KDIR=/path/to/linux
insmod irq_semantics.ko
dmesg | tail -n 25
It needs CONFIG_MODULES and CONFIG_IRQ_SIM (the latter is a hidden symbol, selected by CONFIG_GPIOLIB plus CONFIG_GPIO_SIM; GPIO_MOCKUP works too but is deprecated). The last two lines of the log should be
summary: 17 passed, 0 failed
RESULT: PASS
That result is 17 assertions about the workqueue and interrupt primitives, not about an R-Car unbind: a green run says the kernel behaves the way the patch assumes, it does not say that rcar_thermal_remove() was exercised on your board.
The tarball is attached; the README in it has the same instructions and a reference log. If the list strips the attachment, tell me and I will send it to you directly.
What the module does not do is run rcar_thermal's own ->remove(). That needs a real platform device, MMIO and a thermal zone, and the driver's removal would end up buried under the scaffolding. So it pins down the primitives, not what the interrupt status registers do on your board.
For that, what I would suggest on your side is to unbind and rebind the platform device in a loop while the zone is being read, on a KASAN kernel, and check that no work runs after rcar_thermal_remove() returned and that the source is not enabled again afterwards. To get real interrupts during the unbind the overheat source has to fire at least once; on this driver that happens when the temperature crosses the trip point it has programmed.
If you can tell me which SoC and board you have, and whether the thermal node in its DT has an interrupt and a critical trip point, I can work out what the smallest meaningful run is. I am also happy to reshape the module if you want it to reproduce something else.
Thanks,
Yaohan
Niklas Söderlund
maintainerRe: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Yaohan,
Thanks for sharing your test.
Quoted 28 lines · Yaohan Li
Hi Niklas,
yes, of course. It is one module, self-contained, and it needs no device tree or hardware setup - it builds against the tree you give it and runs on the board you load it on.
The module exercises the three primitives the removal ordering depends on:
- a work queued after
cancel_delayed_work_sync()still runs, while the same queue attempt afterdisable_delayed_work_sync()is rejected and the work never runs;
- a work that is already running re-enables the source behind a mask that was written before the cancellation, and cannot do that when the work is disabled first;
- on a line shared with another handler,synchronize_irq()does not stop our handler from being invoked again (and from queueing the work), whiledevm_free_irq()does, without disturbing the other user.To run it:
make KDIR=/path/to/linux
insmod irq_semantics.ko
dmesg | tail -n 25It needs
CONFIG_MODULESandCONFIG_IRQ_SIM(the latter is a hidden symbol, selected byCONFIG_GPIOLIBplusCONFIG_GPIO_SIM;GPIO_MOCKUPworks too but is deprecated). The last two lines of the log should be
Quoted 7 lines
summary: 17 passed, 0 failed
RESULT: PASSThat result is 17 assertions about the workqueue and interrupt primitives, not about an R-Car unbind: a green run says the kernel behaves the way the patch assumes, it does not say that
rcar_thermal_remove()was exercised on your board.
I agree your test-case is kewl and interesting but as you point out, it test something else then the code this patch touches. But I learnt some more about ktest reading it which was nice!
Quoted 10 lines
The tarball is attached; the README in it has the same instructions and a reference log. If the list strips the attachment, tell me and I will send it to you directly.
What the module does not do is run rcar_thermal's own ->remove(). That needs a real platform device, MMIO and a thermal zone, and the driver's removal would end up buried under the scaffolding. So it pins down the primitives, not what the interrupt status registers do on your board.
Quoted 6 lines
For that, what I would suggest on your side is to unbind and rebind the platform device in a loop while the zone is being read, on a KASAN kernel, and check that no work runs after
rcar_thermal_remove()returned and that the source is not enabled again afterwards. To get real interrupts during the unbind the overheat source has to fire at least once; on this driver that happens when the temperature crosses the trip point it has programmed.
Yes, I was wondering if you had something ready made for this test. Having something push the trip interrupt often enough so that bind/unbinding the driver from the device would provoke the condition within reasonable amount of loops.
I will see if I can make something up.
Quoted 5 lines
If you can tell me which SoC and board you have, and whether the thermal node in its DT has an interrupt and a critical trip point, I can work out what the smallest meaningful run is. I am also happy to reshape the module if you want it to reproduce something else.
I have access to a few boards. For this patch I intend to test on M2 (r8a7791-koelsch.dts) which have trip points. IIRC when adding interrupt support i had a critical trip at a low temperature and then used cpuburn to trigger it. Maybe a non-critical trip point around the running temp and enough iterations can trigger it.
Quoted 3 lines
Thanks,
Yaohan
Signature · 2 lines
Kind Regards, Niklas Söderlund
Re: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Niklas,
Thanks for offering to test this on Koelsch.
I went through the Gen2 thermal driver again. One detail worth clarifying is that rcar_thermal_update_temp() programs INTCTRL from the current ctemp and ctemp - 1, not from the critical trip in the device tree.
Gen2 reports the temperature in 5 C code steps. That does not mean the physical temperature has to move a full 5 C to trigger an interrupt: it depends on how close the sensor sits to a comparator boundary when the window is programmed.
The handler masks the sensor source and schedules the work 300 ms later; the work updates the comparator and re-enables the interrupt. So this path normally limits how often successive sensor events are handled. Reading the zone also goes through the same function and reprograms the comparator, so I would avoid tight temperature polling while trying to observe interrupts.
For the first step I would check the e61f0000 entry in /proc/interrupts. The line is shared and the handler reports it as handled either way, so the counter alone does not prove a thermal event. The driver has a dev_dbg() in rcar_thermal_had_changed() that prints rising/falling, so
echo 'file rcar_thermal.c +p' > /proc/dynamic_debug/control
should show whether it really saw an unmasked status change. That needs a kernel with dynamic debug enabled; if the file is not there but debugfs is mounted, the same control file is at /sys/kernel/debug/dynamic_debug/control.
If real sensor interrupts show up during a controlled temperature change, then a small number of bind/unbind cycles comparing the original and the patched kernel would be the next step. I would not keep a sustained CPU load running while the driver is unbound: with it unbound there is no thermal monitoring from this driver, and the trip is only a shutdown.
There is also a condition that may be easier to observe than the UAF: in the original code a work that is already running re-enables the source after ->remove() has masked it, because cancel_delayed_work_sync() waits for it. A test-only trace of the mask and enable in _rcar_thermal_irq_ctrl() would show that ordering:
original: remove: mask / work: enable / remove: done
patched: work: done / remove: mask / remove: done
If the natural race turns out to be too rare, I can prepare a separate debug-only instrumentation patch to make the interleaving easier to see.
Thanks again for offering the hardware,
Yaohan
Niklas Söderlund
maintainerRe: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Yaohan,
Quoted 3 lines · Yaohan Li
Hi Niklas,
Thanks for offering to test this on Koelsch.
No worries. I was mostly offering to run a test, not create one ;-)
I know how to try and trigger it, my point was this is a very hard issue to trigger and was wondering if you had anything already which do so. Ideally I would like run a test see the old code fail and then apply this fix and see it solved.
Triggering an interrupt by modifying the temperature, be it with cpuburn or a hairdryer at the exact same time that the driver is being unbound seems extremely tricky too me. Even if the bind/unbind operation is put in a loop. And I though since you where fix lot of drivers you had something from a hardware setup you had access too.
Quoted 48 lines
I went through the Gen2 thermal driver again. One detail worth clarifying is that
rcar_thermal_update_temp()programs INTCTRL from the current ctemp and ctemp - 1, not from the critical trip in the device tree.Gen2 reports the temperature in 5 C code steps. That does not mean the physical temperature has to move a full 5 C to trigger an interrupt: it depends on how close the sensor sits to a comparator boundary when the window is programmed.
The handler masks the sensor source and schedules the work 300 ms later; the work updates the comparator and re-enables the interrupt. So this path normally limits how often successive sensor events are handled. Reading the zone also goes through the same function and reprograms the comparator, so I would avoid tight temperature polling while trying to observe interrupts.
For the first step I would check the
e61f0000entry in/proc/interrupts. The line is shared and the handler reports it as handled either way, so the counter alone does not prove a thermal event. The driver has adev_dbg()inrcar_thermal_had_changed()that prints rising/falling, soecho 'file
rcar_thermal.c+p' >/proc/dynamic_debug/controlshould show whether it really saw an unmasked status change. That needs a kernel with dynamic debug enabled; if the file is not there but debugfs is mounted, the same control file is at
/sys/kernel/debug/dynamic_debug/control.If real sensor interrupts show up during a controlled temperature change, then a small number of bind/unbind cycles comparing the original and the patched kernel would be the next step. I would not keep a sustained CPU load running while the driver is unbound: with it unbound there is no thermal monitoring from this driver, and the trip is only a shutdown.
There is also a condition that may be easier to observe than the UAF: in the original code a work that is already running re-enables the source after ->remove() has masked it, because
cancel_delayed_work_sync()waits for it. A test-only trace of the mask and enable in_rcar_thermal_irq_ctrl()would show that ordering:original: remove: mask / work: enable / remove: done
patched: work: done / remove: mask / remove: doneIf the natural race turns out to be too rare, I can prepare a separate debug-only instrumentation patch to make the interleaving easier to see.
Thanks again for offering the hardware,
Yaohan
Signature · 2 lines
Kind Regards, Niklas Söderlund
Re: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Niklas,
You are right. I do not have a ready-made reproducer that exercises rcar_thermal_remove() on the actual driver. The 17-check test exercises workqueue and shared-IRQ primitives; it does not show the original driver failing or the patch fixing the race.
I should have made that distinction clearer, rather than suggesting more thermal-load experiments. I will keep v3 on hold. If I can put together a test-only instrumentation patch that forces the relevant interleaving in the driver's removal path, I will share that for review before asking you to run anything on your board.
Thanks again for offering to help test it.
Yaohan
Niklas Söderlund
maintainerRe: [PATCH v2] thermal/drivers/rcar_thermal: disable the work before masking the interrupt
Hi Yaohan,
Quoted 9 lines · Yaohan Li
Hi Niklas,
You are right. I do not have a ready-made reproducer that exercises
rcar_thermal_remove()on the actual driver. The 17-check test exercises workqueue and shared-IRQ primitives; it does not show the original driver failing or the patch fixing the race.I should have made that distinction clearer, rather than suggesting more thermal-load experiments. I will keep v3 on hold.
I think you can post v3 already, if you think it's ready. Once we can test it or it becomes trivial we can move forward.
Quoted 4 lines
If I can put together a
test-only instrumentation patch that forces the relevant interleaving in the driver's removal path, I will share that for review before asking you to run anything on your board.
Maybe the top half of the interrupt handler can requeue itself. It will be a infinite loop but as a hack patch to trigger the issue it would be ok I think.
Quoted 4 lines
Thanks again for offering to help test it.
Yaohan
Signature · 2 lines
Kind Regards, Niklas Söderlund
PATCH v3 1/1 thermal/drivers/rcar_thermal: disable the work before masking the interrupt
In reply to Yaohan Lircar_thermal_remove() masks the interrupt sources and then cancels the delayed work of each sensor. rcar_thermal_irq() drops common->lock before it walks the sensors and queues priv->work for those whose status changed, so a handler that read the status before the mask was written can still queue the work after cancel_delayed_work_sync() has returned. The work then runs after ->remove() has finished and devres has freed common, priv and the thermal zone.
Waiting for the handler alone is not enough either: rcar_thermal_work() re-enables its interrupt source once it has updated the temperature, so a work that is still running when the removal starts undoes the mask that ->remove() has just written.
Disable the work before the source is masked. That makes the queue_delayed_work() calls in rcar_thermal_irq() no-ops and guarantees that the re-enable in rcar_thermal_work() has already happened, so the mask that follows cannot be undone.
For the handler itself, synchronize_irq() is not enough on a shared line:
it waits for the invocation that is running, but the line stays registered and another user of it can take the interrupt again afterwards, which calls our handler once more - with the sensors and the zone already unregistered. devm_free_irq() removes the handler from the shared descriptor first and waits for the invocation that is in progress second, so after it returns neither a running nor a new invocation can touch the driver state.
Every sensor that the removal walks has been through INIT_DELAYED_WORK() before it is linked into common->head, so no uninitialised work is touched.
---
Prepared against v7.4-rc1-1969-g666539eecdf4.
Compile tested: arm64, aarch64-linux-gnu-gcc 11.4, CONFIG_RCAR_THERMAL=y.
The ordering was exercised by a controlled test on a KASAN kernel built from this tree (x86_64, QEMU/KVM; 17 checks, all passing). The test uses the real delayed work, workqueue, wait and signal machinery and a simulated interrupt line shared by two handlers (irq_sim):
- a work queued after cancel_delayed_work_sync() has returned is accepted and runs; the same queue attempt after disable_delayed_work_sync() is rejected and the work never runs;
- a work that is running when the mask is written re-enables its source afterwards, so the mask is undone; disabling the work first and masking afterwards leaves the mask in place;
- after synchronize_irq() returns, another user of the shared line raises it again, our handler is invoked and queues the work, which then runs; after devm_free_irq() the handler is not invoked again, while the other user still receives the line.
The test re-implements this removal ordering rather than compiling the driver, which would need a real platform device, MMIO and a thermal zone, so rcar_thermal's own removal path was not executed. No rcar hardware was available and no race injection beyond those constructed interleavings was run.
AI assistance: prepared with Claude (Anthropic) as a coding assistant; the author reviewed the reasoning and takes responsibility for the content.
Changes in v3:
- Reword the RCAR_THERMAL_MAX_IRQ comment without referring to .nirqs.
- Declare the loop index in the for statement and make it unsigned.
- Reduce both comments in rcar_thermal_remove() to one line each.
- Explain in the commit message why a shared line needs devm_free_irq() and not synchronize_irq(), and point at the test that exercises it.
Changes in v2:
- Drop the shutdown flag and the separate IRQ count. Niklas asked for less state, so the removal now disables the delayed work before the source is masked and unregisters the shared IRQ instead of waiting for it once.
- Keep the interrupt numbers in an array whose unused slots stay negative.
--- drivers/thermal/renesas/rcar_thermal.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-)
drivers/thermal/renesas/rcar_thermal.c +24 -2
@@ -39,11 +39,15 @@/* THSSR */ #define CTEMP 0x3f +/* Maximum number of interrupts supported by any of the chips */ +#define RCAR_THERMAL_MAX_IRQ 2 +struct rcar_thermal_common {void __iomem *base;struct device *dev;struct list_head head;spinlock_t lock; +int irqs[RCAR_THERMAL_MAX_IRQ ]; };struct rcar_thermal_chip {
@@ -377,9 +381,22 @@ static void rcar_thermal_remove(struct platform_device *pdev)struct device *dev = &pdev->dev;struct rcar_thermal_priv *priv; -rcar_thermal_for_each_priv (priv, common) { +/* Drain the work before masking the source it can re-enable. */ +rcar_thermal_for_each_priv (priv, common) +disable_delayed_work_sync (&priv->work); + +rcar_thermal_for_each_priv (priv, common)rcar_thermal_irq_disable (priv); -cancel_delayed_work_sync (&priv->work); + +/* Unregister shared IRQ handlers before releasing the zones. */ +for (unsigned int i =0 ; i <RCAR_THERMAL_MAX_IRQ ; i++) { +if (common->irqs[i] <0 ) +continue ; +devm_free_irq (dev, common->irqs[i], common); + common->irqs[i] = -ENOENT ; + } + +rcar_thermal_for_each_priv (priv, common) {if (priv->chip->use_of_thermal)thermal_remove_hwmon_sysfs (priv->zone);else
@@ -413,6 +430,9 @@ static int rcar_thermal_probe(struct platform_device *pdev)spin_lock_init (&common->lock); common->dev = dev; +for (i =0 ; i <RCAR_THERMAL_MAX_IRQ ; i++) + common->irqs[i] = -ENOENT ; +pm_runtime_enable (dev);pm_runtime_get_sync (dev);
@@ -449,6 +469,8 @@ static int rcar_thermal_probe(struct platform_device *pdev)if (ret) goto error_unregister; + common->irqs[i] = irq; +/* update ENR bits */ if (chip->irq_per_ch) enr_bits |=1 << i;
Signature · 1 line
2.34.1