[PATCH] ALSA: hwdep: do not free a still-open hwdep on single-device teardown

From: Hanxiang Xu

Date: Tue Dec 01 2026 - 22:10:42 EST


An independent teardown path calls snd_device_free(card, hwdep),
which runs snd_hwdep_free(): it kfrees the struct snd_hwdep without
waiting for hwdep->used to drop. Open descriptors keep
file->private_data pointing at the freed object with the real hwdep
f_ops, and their in-flight or later operations (ioctl/read/poll and
the final close) are use-after-frees. The card-wide path swaps
file->f_op for stub operations, but a single-device teardown never
runs it.

Refuse the free while hwdep->used is non-zero: __snd_device_free()
still unlinks the snd_device wrapper, so the card never revisits the
device, and the object stays valid for the open descriptors.

Cc: <stable@xxxxxxxxxxxxxxx>
Signed-off-by: Hanxiang Xu <xuhx@xxxxxxxxxxx>
---
sound/core/hwdep.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
index fb90348..0d22c30 100644
--- a/sound/core/hwdep.c
+++ b/sound/core/hwdep.c
@@ -337,14 +337,17 @@ static const struct file_operations snd_hwdep_f_ops = {
.mmap = snd_hwdep_mmap,
};

-static void snd_hwdep_free(struct snd_hwdep *hwdep)
+static int snd_hwdep_free(struct snd_hwdep *hwdep)
{
if (!hwdep)
- return;
+ return 0;
+ if (hwdep->used)
+ return -EBUSY;
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
kfree(hwdep);
+ return 0;
}

/**
@@ -412,8 +415,7 @@ EXPORT_SYMBOL(snd_hwdep_new);

static int snd_hwdep_dev_free(struct snd_device *device)
{
- snd_hwdep_free(device->device_data);
- return 0;
+ return snd_hwdep_free(device->device_data);
}

static int snd_hwdep_dev_register(struct snd_device *device)
--
2.43.0