Linux Sound subsystem development
 help / color / mirror / Atom feed
* [PATCH] ALSA: pcm: free struct snd_pcm only after the last open file is closed
@ 2026-12-02  2:32 Hanxiang Xu
  2026-12-02  3:19 ` sashiko-bot
  0 siblings, 1 reply; 2+ messages in thread
From: Hanxiang Xu @ 2026-12-02  2:32 UTC (permalink / raw)
  To: Takashi Iwai, Jaroslav Kysela; +Cc: linux-sound, linux-kernel

When a sub-driver removes its pcm from a live card with
snd_device_free(), snd_pcm_dev_disconnect() does not wait for open
files and snd_pcm_free() immediately kfrees every substream and
struct snd_pcm itself.  Open files keep pcm_file->substream and
substream->pcm pointing at the freed memory, so an in-flight ioctl
dereferences it and the delayed close() runs snd_pcm_release() on it,
ending in snd_pcm_release_substream() -> substream->ops->close.

Give struct snd_pcm a kref: the card device entry holds the initial
reference (dropped by snd_pcm_free()), snd_pcm_attach_substream()
takes one per open and the tail of snd_pcm_release() (and the open
failure path) drops it.  The whole free body moves behind the kref
release, so a concurrent snd_device_free() can no longer free a pcm
that still has open files.

Cc: <stable@vger.kernel.org>
Signed-off-by: Hanxiang Xu <xuhx@hust.edu.cn>
---
 include/sound/pcm.h | 1 +
 sound/core/pcm.c | 17 +++++++++++++----
 sound/core/pcm_native.c | 2 ++
 3 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/include/sound/pcm.h b/include/sound/pcm.h
index 1cf511f8d880ea53e9309721ea7efaa625304b22..65cae3349d374bce0cf2d5269796c879753023af 100644
@@ -541,6 +541,7 @@
 	char id[64];
 	char name[80];
 	struct snd_pcm_str streams[2];
+	struct kref ref; /* freed once the device entry and all files are gone */
 	struct mutex open_mutex;
 	wait_queue_head_t open_wait;
 	void *private_data;
diff --git a/sound/core/pcm.c b/sound/core/pcm.c
index 6c8274414c226543e8044c348e90388e038beb05..c59c5e2fa34fa949e579021d2ffcf5ecb51be3f6 100644
@@ -723,6 +723,7 @@
 	pcm->card = card;
 	pcm->device = device;
 	pcm->internal = internal;
+	kref_init(&pcm->ref);
 	mutex_init(&pcm->open_mutex);
 	init_waitqueue_head(&pcm->open_wait);
 	INIT_LIST_HEAD(&pcm->list);
@@ -857,10 +858,10 @@ static void snd_pcm_free_stream(struct snd_pcm_str * pstr)
 #define pcm_call_notify(pcm, call) do {} while (0)
 #endif
 
-static int snd_pcm_free(struct snd_pcm *pcm)
-{
-	if (!pcm)
-		return 0;
+static void snd_pcm_free_up(struct kref *ref)
+{
+	struct snd_pcm *pcm = container_of(ref, struct snd_pcm, ref);
+
 	if (!pcm->internal) {
 		scoped_guard(mutex, &register_mutex)
 			pcm_call_notify(pcm, n_unregister);
@@ -871,6 +872,13 @@ static int snd_pcm_free(struct snd_pcm *pcm)
 	snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK]);
 	snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_CAPTURE]);
 	kfree(pcm);
+}
+
+static int snd_pcm_free(struct snd_pcm *pcm)
+{
+	if (!pcm)
+		return 0;
+	kref_put(&pcm->ref, snd_pcm_free_up);
 	return 0;
 }
 
@@ -981,6 +989,7 @@ static int snd_pcm_dev_free(struct snd_device *device)
 	substream->f_flags = file->f_flags;
 	substream->pid = get_pid(task_pid(current));
 	pstr->substream_opened++;
+	kref_get(&pcm->ref);
 	*rsubstream = substream;
 #ifdef CONFIG_SND_PCM_XRUN_DEBUG
 	substream->xrun_counter = 0;
diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c
index 897975e43a9bd634fb11e2a086378a4142a90f64..4fef3020328fb706a4e2328ea4ad6b7df4e0e7f0 100644
@@ -3037,6 +3037,7 @@
 
       __error:
 	module_put(pcm->card->module);
+	kref_put(&pcm->ref, snd_pcm_free_up);
       __error2:
       	snd_card_file_remove(pcm->card, file);
       __error1:
@@ -3065,6 +3066,7 @@ static int snd_pcm_release(struct inode *inode, struct file *file)
 	wake_up(&pcm->open_wait);
 	module_put(pcm->card->module);
 	snd_card_file_remove(pcm->card, file);
+	kref_put(&pcm->ref, snd_pcm_free_up);
 	return 0;
 }
 
-- 
2.43.0


^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: [PATCH] ALSA: pcm: free struct snd_pcm only after the last open file is closed
  2026-12-02  2:32 [PATCH] ALSA: pcm: free struct snd_pcm only after the last open file is closed Hanxiang Xu
@ 2026-12-02  3:19 ` sashiko-bot
  0 siblings, 0 replies; 2+ messages in thread
From: sashiko-bot @ 2026-12-02  3:19 UTC (permalink / raw)
  To: Hanxiang Xu; +Cc: linux-sound

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [Critical] ALSA: pcm: unbalanced kref_put() and pcm->card UAF in
  snd_pcm_open()
- [Critical] ALSA: pcm: missing kref_get() on O_APPEND path in
  snd_pcm_attach_substream()
- [High] ALSA: pcm: static snd_pcm_free_up() undeclared in
  sound/core/pcm_native.c
- [High] ALSA: pcm: leaked pcm->ref in snd_pcm_detach_substream() and
  OSS emulation
- [High] ALSA: pcm: struct snd_card UAF in snd_pcm_free_up() from
  snd_pcm_release()
- [High] ALSA: pcm: unreferenced struct snd_pcm in snd_pcm_open() races
  with free
- [High] ALSA: pcm: deferred snd_pcm_free_up() races with sub-driver
  teardown
--

commit ee4fa7452126fcba1071f25254147a73508e58cb
Author: Hanxiang Xu <xuhx@hust.edu.cn>

ALSA: pcm: free struct snd_pcm only after the last open file is closed

This commit adds a kref to struct snd_pcm so that snd_pcm_free() defers
teardown and freeing of the PCM instance until both the device entry and
all open files have dropped their references.

> diff --git a/sound/core/pcm.c b/sound/core/pcm.c
> index 6c8274414c226..c59c5e2fa34fa 100644
> --- a/sound/core/pcm.c
> +++ b/sound/core/pcm.c
> @@ -857,10 +858,10 @@ static void snd_pcm_free_stream(struct snd_pcm_str * pstr)
>  #define pcm_call_notify(pcm, call) do {} while (0)
>  #endif
>  
> -static int snd_pcm_free(struct snd_pcm *pcm)
> +static void snd_pcm_free_up(struct kref *ref)
>  {
> -	if (!pcm)
> -		return 0;
> +	struct snd_pcm *pcm = container_of(ref, struct snd_pcm, ref);
> +

[Severity: High]
Does sound/core/pcm_native.c fail to compile because snd_pcm_free_up() is
defined static here in sound/core/pcm.c without a declaration in
sound/core/pcm_local.h?  Both snd_pcm_open() and snd_pcm_release() in
sound/core/pcm_native.c pass snd_pcm_free_up to kref_put().

>  	if (!pcm->internal) {
>  		scoped_guard(mutex, &register_mutex)
>  			pcm_call_notify(pcm, n_unregister);
> @@ -871,6 +872,13 @@ static int snd_pcm_free(struct snd_pcm *pcm)
>  	snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK]);
>  	snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_CAPTURE]);
>  	kfree(pcm);
> +}
> +
> +static int snd_pcm_free(struct snd_pcm *pcm)
> +{
> +	if (!pcm)
> +		return 0;
> +	kref_put(&pcm->ref, snd_pcm_free_up);
>  	return 0;
>  }

[Severity: High]
Can deferring snd_pcm_free_up() and substream close callbacks past
snd_device_free() cause a use-after-free in sub-drivers that free the
driver structures backing pcm->private_data and substream->ops as soon as
snd_device_free() returns?

CPU0                                  CPU1
codec_release_pcms()
  snd_device_free(card, pcm->pcm)
    ...
      snd_pcm_free()
        kref_put(&pcm->ref, ...)
  kfree(pcm) /* frees apcm->info */
                                      snd_pcm_release()
                                        ...
                                        kref_put(&pcm->ref, snd_pcm_free_up)
                                          snd_pcm_free_up()
                                            azx_pcm_free()
                                              apcm->info->pcm = NULL;
                                                <-- use-after-free

Similarly, snd_emu8000_remove() calls snd_device_free(dev->card, hw->pcm)
and immediately frees hw->emu and hw->memhdr, so a later
snd_pcm_release() -> snd_pcm_release_substream() -> emu8k_pcm_hw_free()
passes a NULL rec->emu->memhdr and an already-freed rec->block to
snd_util_mem_free().

> @@ -981,6 +989,7 @@ int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream,
>  	substream->f_flags = file->f_flags;
>  	substream->pid = get_pid(task_pid(current));
>  	pstr->substream_opened++;
> +	kref_get(&pcm->ref);
>  	*rsubstream = substream;
>  #ifdef CONFIG_SND_PCM_XRUN_DEBUG
>  	substream->xrun_counter = 0;

[Severity: Critical]
Does the O_APPEND path in snd_pcm_attach_substream() return 0 without
calling kref_get(&pcm->ref)?

sound/core/pcm.c:snd_pcm_attach_substream() {
    ...
	if (file->f_flags & O_APPEND) {
		...
		substream->ref_count++;
		*rsubstream = substream;
		return 0;
	}
    ...
}

When a file opened with O_APPEND is later closed, snd_pcm_release() still
calls kref_put(&pcm->ref, snd_pcm_free_up), dropping an unacquired
reference and freeing struct snd_pcm while the primary file descriptor is
still using it.

[Severity: High]
Does taking pcm->ref in snd_pcm_attach_substream() without a matching
kref_put() in snd_pcm_detach_substream() leak pcm->ref on every OSS PCM
open?

snd_pcm_oss_open_file() opens playback and capture substreams via
snd_pcm_open_substream() -> snd_pcm_attach_substream(), acquiring up to
two references on pcm->ref, but snd_pcm_oss_release_file() releases them
via snd_pcm_release_substream() -> snd_pcm_detach_substream() without
ever calling kref_put(&pcm->ref, snd_pcm_free_up).  As a result, pcm->ref
never reaches zero and struct snd_pcm and its preallocated DMA buffers
are leaked.

> diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c
> index 897975e43a9bd..4fef3020328fb 100644
> --- a/sound/core/pcm_native.c
> +++ b/sound/core/pcm_native.c
> @@ -3037,6 +3037,7 @@ static int snd_pcm_open(struct file *file, struct snd_pcm *pcm, int stream)
>  
>        __error:
>  	module_put(pcm->card->module);
> +	kref_put(&pcm->ref, snd_pcm_free_up);
>        __error2:
>        	snd_card_file_remove(pcm->card, file);
>        __error1:

[Severity: Critical]
Can jumping to __error in snd_pcm_open() drop pcm->ref when
kref_get(&pcm->ref) was never called, and then dereference pcm->card
after pcm is freed?

If snd_pcm_open_file() fails before the end of snd_pcm_attach_substream()
(for instance with -EAGAIN when a substream is busy under O_NONBLOCK, or
when the wait loop aborts with -ERESTARTSYS on a signal), kref_get() has
not been called, so kref_put(&pcm->ref, snd_pcm_free_up) drops the device
entry's reference and frees pcm.  Immediately afterwards, __error2 and
the caller snd_pcm_playback_open() / snd_pcm_capture_open() dereference
pcm->card in snd_card_file_remove(pcm->card, file) and
snd_card_unref(pcm->card).

Conversely, if snd_pcm_attach_substream() succeeds (calling kref_get())
and substream->ops->open() then returns -EAGAIN on a blocking open,
snd_pcm_open_substream() calls snd_pcm_release_substream() without
dropping pcm->ref and the wait loop retries snd_pcm_open_file(), leaking
one reference on every retry.

[Severity: High]
Can snd_device_free(card, pcm) free struct snd_pcm before snd_pcm_open()
takes a reference on pcm->ref?

snd_lookup_minor_data() in snd_pcm_playback_open() and
snd_pcm_capture_open() returns a raw struct snd_pcm pointer after
dropping sound_mutex, and pcm->ref is not incremented until
snd_pcm_attach_substream() succeeds.

CPU0                                  CPU1
snd_pcm_playback_open()
  pcm = snd_lookup_minor_data(...)
  snd_pcm_open(file, pcm, ...)
    ...
    /* substream busy: -EAGAIN */
    mutex_unlock(&pcm->open_mutex)
                                      /* active file closes */
                                      snd_device_free(card, pcm)
                                        snd_pcm_dev_disconnect()
                                        snd_pcm_dev_free()
                                          snd_pcm_free(pcm)
                                            kref_put(..., snd_pcm_free_up)
                                              kfree(pcm)
    schedule()
    mutex_lock(&pcm->open_mutex)  <-- use-after-free

Even if pcm is still alive on wakeup, snd_device_free() on a single PCM
device leaves pcm->card->shutdown as 0, so a waiter woken by
snd_pcm_dev_disconnect() passes the pcm->card->shutdown check and can
open a substream on an already-disconnected PCM.

> @@ -3065,6 +3066,7 @@ static int snd_pcm_release(struct inode *inode, struct file *file)
>  	wake_up(&pcm->open_wait);
>  	module_put(pcm->card->module);
>  	snd_card_file_remove(pcm->card, file);
> +	kref_put(&pcm->ref, snd_pcm_free_up);
>  	return 0;
>  }

[Severity: High]
When the last open PCM file is closed after card disconnect, does
snd_card_file_remove() free struct snd_card before kref_put() runs
snd_pcm_free_up()?

After snd_card_free_when_closed(), the open file holds the last reference
on card->card_dev and one reference on pcm->ref.  In snd_pcm_release(),
snd_card_file_remove(pcm->card, file) calls put_device(&card->card_dev)
-> snd_card_do_free(card):

  snd_card_do_free(card)
    snd_device_free_all(card)
      snd_pcm_dev_free()
        snd_pcm_free(pcm)
          kref_put(&pcm->ref, snd_pcm_free_up) /* 2 -> 1, deferred */
    snd_info_card_free(card) /* frees card->proc_root and pstr->proc_root */
    kfree(card)

When snd_pcm_release() then executes kref_put(&pcm->ref, snd_pcm_free_up)
on the next line, snd_pcm_free_up() runs after module_put() and after
card has been freed: snd_pcm_lib_preallocate_free_for_all() ->
decrease_allocated_size() locks card->memory_mutex on the freed struct
snd_card, snd_pcm_free_stream() -> snd_pcm_stream_proc_done() double
frees pstr->proc_root, and snd_pcm_timer_done() accesses card->devices on
the freed card.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261202103200.3-1-xuhx@hust.edu.cn?part=1

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-12-02  3:19 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02  2:32 [PATCH] ALSA: pcm: free struct snd_pcm only after the last open file is closed Hanxiang Xu
2026-12-02  3:19 ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox