[PATCH] ALSA: hwdep: keep struct snd_hwdep alive until the last open file is closed
From: Hanxiang Xu
Date: Tue Dec 01 2026 - 22:04:31 EST
When a sub-driver removes its hwdep device from a live card with
snd_device_free(), snd_hwdep_dev_disconnect() does not wait for open
files and snd_hwdep_free() immediately kfree()s struct snd_hwdep.
Open files keep file->private_data pointing at the freed object, so
an in-flight ioctl dereferences hw->ops and the delayed close() runs
snd_hwdep_release() on the freed memory (hw->card->module,
hw->open_mutex, hw->used).
Anchor the lifetime of struct snd_hwdep on its embedded device: the
release callback now performs the kfree(), opening the device takes a
reference and every close/error path drops it again. snd_hwdep_free()
only releases the registry reference.
Cc: <stable@xxxxxxxxxxxxxxx>
Signed-off-by: Hanxiang Xu <xuhx@xxxxxxxxxxx>
---
sound/core/hwdep.c | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)
diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
index fb9034897c561b2df01c655728afad550f010c85..bddd74ee1014e7117c51c7592d6960cc3b5729b0 100644
@@ -84,8 +84,10 @@
return -ENXIO;
if (hw == NULL)
return -ENODEV;
+ get_device(hw->dev);
if (!try_module_get(hw->card->module)) {
+ put_device(hw->dev);
snd_card_unref(hw->card);
return -ENODEV;
}
@@ -137,8 +139,10 @@ static int snd_hwdep_open(struct inode *inode, struct file * file)
}
}
mutex_unlock(&hw->open_mutex);
- if (err < 0)
+ if (err < 0) {
module_put(hw->card->module);
+ put_device(hw->dev);
+ }
snd_card_unref(hw->card);
return err;
}
@@ -159,6 +163,7 @@ static int snd_hwdep_release(struct inode *inode, struct file * file)
snd_card_file_remove(hw->card, file);
module_put(mod);
+ put_device(hw->dev);
return err;
}
@@ -337,6 +342,13 @@ static int snd_hwdep_mmap(struct file * file, struct vm_area_struc...
.mmap = snd_hwdep_mmap,
};
+static void snd_hwdep_dev_release(struct device *dev)
+{
+ struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
+
+ kfree(hwdep);
+}
+
static void snd_hwdep_free(struct snd_hwdep *hwdep)
{
if (!hwdep)
@@ -344,7 +356,6 @@ static void snd_hwdep_free(struct snd_hwdep *hwdep)
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
- kfree(hwdep);
}
/**
@@ -392,6 +403,7 @@ static void snd_hwdep_free(struct snd_hwdep *hwdep)
snd_hwdep_free(hwdep);
return err;
}
+ hwdep->dev->release = snd_hwdep_dev_release;
dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
#ifdef CONFIG_SND_OSSEMUL
--
2.43.0