[PATCH] ALSA: rawmidi: do not free a rawmidi with open substreams on single-device teardown

From: Hanxiang Xu

Date: Tue Dec 01 2026 - 22:11:14 EST


An independent teardown path calls snd_device_free(card, rmidi),
which runs snd_rawmidi_free(): kfree(substream) for every substream,
rmidi->private_free() (which frees the virmidi device data), and
kfree(rmidi) -- none of which waits for the open file descriptors on
/dev/snd/midiC*D*, and the virmidi output work queued on the global
workqueue keeps dereferencing the freed substream and device data.

Refuse the free while any substream is opened: __snd_device_free()
unlinks the snd_device wrapper but leaves the object tree alive for
the open descriptors and the in-flight work. Additionally never kfree
a substream whose ->opened flag is still set.

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

diff --git a/sound/core/rawmidi.c b/sound/core/rawmidi.c
index 630d9fc..851509e 100644
--- a/sound/core/rawmidi.c
+++ b/sound/core/rawmidi.c
@@ -1969,6 +1969,8 @@ static void snd_rawmidi_free_substreams(struct snd_rawmidi_str *stream)
while (!list_empty(&stream->substreams)) {
substream = list_entry(stream->substreams.next, struct snd_rawmidi_substream, list);
list_del(&substream->list);
+ if (substream->opened)
+ continue;
kfree(substream);
}
}
@@ -1978,6 +1980,9 @@ int snd_rawmidi_free(struct snd_rawmidi *rmidi)
{
if (!rmidi)
return 0;
+ if (rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substream_opened ||
+ rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substream_opened)
+ return -EBUSY;

snd_info_free_entry(rmidi->proc_entry);
rmidi->proc_entry = NULL;
--
2.43.0