Re: [PATCH] comedi: fix device lifecycle handling in comedi_dev_kref_release()

From: Ian Abbott

Date: Mon Feb 02 2026 - 07:48:42 EST


On 30/01/2026 22:35, Salah Triki wrote:
`comedi_dev_kref_release()` calls `put_device()` on `dev->class_dev` and
then immediately frees the `comedi_device` structure with `kfree()`.
If the device reference count reaches zero, the device model release
callback may be invoked, potentially accessing or freeing parts of
the structure. Calling `kfree()` directly after `put_device()` can
cause a use-after-free or double-free.

After `device_initialize()` and once the struct device is in the device
model, all cleanup must go through `put_device()` and the release
callback. The kref release should not free the structure directly,
ensuring that `comedi_device` lifetime is properly managed through
device reference counting and preventing potential memory corruption.

Fixes: 5b13ed94a7d24 ("staging: comedi: add a kref to comedi device")

Signed-off-by: Salah Triki <salah.triki@xxxxxxxxx>
---
drivers/comedi/comedi_fops.c | 1 -
1 file changed, 1 deletion(-)

diff --git a/drivers/comedi/comedi_fops.c b/drivers/comedi/comedi_fops.c
index 2c3eb9e89571..24bb06fe6b45 100644
--- a/drivers/comedi/comedi_fops.c
+++ b/drivers/comedi/comedi_fops.c
@@ -118,7 +118,6 @@ static void comedi_dev_kref_release(struct kref *kref)
mutex_destroy(&dev->mutex);
put_device(dev->class_dev);
- kfree(dev);
}
/**

NAK

This isn't freeing the `struct device`, it is freeing the `struct comedi_device`. The `struct device` will be freed by `device_create_release()` in "drivers/base/core.c".

--
-=( Ian Abbott <abbotti@xxxxxxxxx> || MEV Ltd. is a company )=-
-=( registered in England & Wales. Regd. number: 02862268. )=-
-=( Regd. addr.: S11 & 12 Building 67, Europa Business Park, )=-
-=( Bird Hall Lane, STOCKPORT, SK3 0XA, UK. || www.mev.co.uk )=-