* ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
[not found] ` <2026102727-data-sequel-ce41@gregkh>
@ 2026-11-13 11:58 ` 徐晗翔
2026-11-13 16:30 ` Takashi Iwai
2026-11-13 12:03 ` ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF) 徐晗翔
` (12 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 11:58 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
`ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
still be executing, or can start after `snd_card_disconnect()` has already done
its single `synchronize_irq()`. A handler that has passed the non-atomic
`hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
`atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
`destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
or wedge the device during PCI removal/unbind.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree under review. This report is source-level only: no
ctxfi hardware was available and QEMU has no ctxfi device model, so no
driver-specific reproducer was run. The source paths/line numbers below are
from 7.3.
* Mechanism
`ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
timer callback by default when `!use_system_timer && hw->set_timer_irq`:
hw->irq_callback_data = atimer;
hw->irq_callback = ct_timer_interrupt;
The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
`ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
if (hw->irq_callback)
hw->irq_callback(hw->irq_callback_data, status);
`ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
`timer->ops->interrupt` and calls it with `timer`. Neither the check nor
the two loads is atomic.
`ct_timer_free()` (`cttimer.c:414-421`) does:
struct hw *hw = atimer->atc->hw;
hw->irq_callback = NULL;
if (atimer->ops->free_global)
atimer->ops->free_global(atimer);
kfree(atimer);
`ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
It does not wait for an in-flight IRQ handler.
`ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
`kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
`free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
not the freed object in this window; `atimer` is freed before `free_irq()`.
* Why the existing synchronization does not close the window
ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
`synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
before `ct_timer_free()`, only waits handlers that are running at that
instant, and does not disable the IRQ line. A new handler can enter after
the one-time sync and before `free_irq()`.
The `hw->irq_callback = NULL` store does not close the race either: a
handler that loaded the callback pointer before the store can still call it.
* Trigger model
Open a ctxfi device (native timer path, the default), then remove/unbind the
PCI device while an interrupt is pending or arrives during teardown. The
window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
control-flow corruption.
* Suggested direction
After clearing `hw->irq_callback` and calling `free_global()`, but before
`kfree(atimer)`, do:
if (hw->irq >= 0)
synchronize_irq(hw->irq);
Alternatively, move `free_irq()` earlier so it precedes the timer free.
Keep the existing `hw->irq == -1` initialization contract.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-13 11:58 ` ALSA: ctxfi: free atimer only after the timer IRQ is quiesced 徐晗翔
@ 2026-11-13 16:30 ` Takashi Iwai
2026-11-25 12:51 ` [PATCH] Re: " 徐晗翔
0 siblings, 1 reply; 41+ messages in thread
From: Takashi Iwai @ 2026-11-13 16:30 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Fri, 13 Nov 2026 12:58:51 +0100,
徐晗翔 wrote:
>
> `ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
> still be executing, or can start after `snd_card_disconnect()` has already done
> its single `synchronize_irq()`. A handler that has passed the non-atomic
> `hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
> `atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
> `destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
> or wedge the device during PCI removal/unbind.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree under review. This report is source-level only: no
> ctxfi hardware was available and QEMU has no ctxfi device model, so no
> driver-specific reproducer was run. The source paths/line numbers below are
> from 7.3.
>
> * Mechanism
>
> `ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
> timer callback by default when `!use_system_timer && hw->set_timer_irq`:
>
> hw->irq_callback_data = atimer;
> hw->irq_callback = ct_timer_interrupt;
>
> The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
> `ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
>
> if (hw->irq_callback)
> hw->irq_callback(hw->irq_callback_data, status);
>
> `ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
> `timer->ops->interrupt` and calls it with `timer`. Neither the check nor
> the two loads is atomic.
>
> `ct_timer_free()` (`cttimer.c:414-421`) does:
>
> struct hw *hw = atimer->atc->hw;
> hw->irq_callback = NULL;
> if (atimer->ops->free_global)
> atimer->ops->free_global(atimer);
> kfree(atimer);
>
> `ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
> stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
> It does not wait for an in-flight IRQ handler.
>
> `ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
> 1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
> `kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
> `free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
> not the freed object in this window; `atimer` is freed before `free_irq()`.
>
> * Why the existing synchronization does not close the window
>
> ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
> and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
> `synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
> before `ct_timer_free()`, only waits handlers that are running at that
> instant, and does not disable the IRQ line. A new handler can enter after
> the one-time sync and before `free_irq()`.
>
> The `hw->irq_callback = NULL` store does not close the race either: a
> handler that loaded the callback pointer before the store can still call it.
>
> * Trigger model
>
> Open a ctxfi device (native timer path, the default), then remove/unbind the
> PCI device while an interrupt is pending or arrives during teardown. The
> window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
> of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
> control-flow corruption.
>
> * Suggested direction
>
> After clearing `hw->irq_callback` and calling `free_global()`, but before
> `kfree(atimer)`, do:
>
> if (hw->irq >= 0)
> synchronize_irq(hw->irq);
>
> Alternatively, move `free_irq()` earlier so it precedes the timer free.
> Keep the existing `hw->irq == -1` initialization contract.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
Could you rather submit a fix patch (with a proper patch description)
for each your reported issue? You can put Link: tag to pointing to
the earlier reports.
thanks,
Takashi
^ permalink raw reply [flat|nested] 41+ messages in thread
* [PATCH] Re: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-13 16:30 ` Takashi Iwai
@ 2026-11-25 12:51 ` 徐晗翔
2026-11-25 13:00 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:51 UTC (permalink / raw)
To: Takashi Iwai; +Cc: perex, tiwai, linux-sound, linux-kernel
ct_timer_free() cleared hw->irq_callback, stopped the hardware timer
and kfree()d the ct_timer while the PCI IRQ handler could still be
running or start later: a handler that loaded hw->irq_callback
before the NULL store calls ct_timer_interrupt() with the freed
atimer, and the single synchronize_irq() in snd_card_disconnect()
only covers handlers that were running at that instant -- free_irq()
happens later, in ct_atc_destroy() -> destroy_hw_obj().
synchronize_irq(hw->irq) after clearing the callback and stopping
the hardware, before the kfree(). The hw->irq == -1 initialization
contract is kept (the sync only runs for an installed IRQ).
---
sound/pci/ctxfi/cttimer.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
--- a/sound/pci/ctxfi/cttimer.c
+++ b/sound/pci/ctxfi/cttimer.c
@@ -417,6 +417,14 @@
hw->irq_callback = NULL;
if (atimer->ops->free_global)
atimer->ops->free_global(atimer);
+ /* Wait for an in-flight IRQ handler before the timer object goes
+ * away. A handler that already loaded hw->irq_callback can still
+ * call ct_timer_interrupt() with the freed atimer, and the single
+ * synchronize_irq() in snd_card_disconnect() only covers handlers
+ * that were running at that instant -- free_irq() happens later,
+ * in ct_atc_destroy() -> destroy_hw_obj(). */
+ if (hw->irq >= 0)
+ synchronize_irq(hw->irq);
kfree(atimer);
}
> -----原始邮件-----
> 发件人: "Takashi Iwai" <tiwai@suse.de>
> 发送时间:2026-11-14 00:30:54 (星期六)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> 抄送: perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
>
> On Fri, 13 Nov 2026 12:58:51 +0100,
> 徐晗翔 wrote:
> >
> > `ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
> > still be executing, or can start after `snd_card_disconnect()` has already done
> > its single `synchronize_irq()`. A handler that has passed the non-atomic
> > `hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
> > `atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
> > `destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
> > or wedge the device during PCI removal/unbind.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source tree under review. This report is source-level only: no
> > ctxfi hardware was available and QEMU has no ctxfi device model, so no
> > driver-specific reproducer was run. The source paths/line numbers below are
> > from 7.3.
> >
> > * Mechanism
> >
> > `ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
> > timer callback by default when `!use_system_timer && hw->set_timer_irq`:
> >
> > hw->irq_callback_data = atimer;
> > hw->irq_callback = ct_timer_interrupt;
> >
> > The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
> > `ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
> >
> > if (hw->irq_callback)
> > hw->irq_callback(hw->irq_callback_data, status);
> >
> > `ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
> > `timer->ops->interrupt` and calls it with `timer`. Neither the check nor
> > the two loads is atomic.
> >
> > `ct_timer_free()` (`cttimer.c:414-421`) does:
> >
> > struct hw *hw = atimer->atc->hw;
> > hw->irq_callback = NULL;
> > if (atimer->ops->free_global)
> > atimer->ops->free_global(atimer);
> > kfree(atimer);
> >
> > `ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
> > stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
> > It does not wait for an in-flight IRQ handler.
> >
> > `ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
> > 1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
> > `kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
> > `free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
> > not the freed object in this window; `atimer` is freed before `free_irq()`.
> >
> > * Why the existing synchronization does not close the window
> >
> > ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
> > and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
> > `synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
> > before `ct_timer_free()`, only waits handlers that are running at that
> > instant, and does not disable the IRQ line. A new handler can enter after
> > the one-time sync and before `free_irq()`.
> >
> > The `hw->irq_callback = NULL` store does not close the race either: a
> > handler that loaded the callback pointer before the store can still call it.
> >
> > * Trigger model
> >
> > Open a ctxfi device (native timer path, the default), then remove/unbind the
> > PCI device while an interrupt is pending or arrives during teardown. The
> > window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
> > of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
> > control-flow corruption.
> >
> > * Suggested direction
> >
> > After clearing `hw->irq_callback` and calling `free_global()`, but before
> > `kfree(atimer)`, do:
> >
> > if (hw->irq >= 0)
> > synchronize_irq(hw->irq);
> >
> > Alternatively, move `free_irq()` earlier so it precedes the timer free.
> > Keep the existing `hw->irq == -1` initialization contract.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
>
> Could you rather submit a fix patch (with a proper patch description)
> for each your reported issue? You can put Link: tag to pointing to
> the earlier reports.
>
>
> thanks,
>
> Takashi
^ permalink raw reply [flat|nested] 41+ messages in thread
* Re: [PATCH] Re: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-25 12:51 ` [PATCH] Re: " 徐晗翔
@ 2026-11-25 13:00 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:00 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] ALSA: ctxfi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: ctxfi: unlocked free_global() in ct_timer_free() before
IRQ sync
- [Low] ALSA: ctxfi: missing Fixes trailer in commit message
--
commit 642fa23b6f7a078e46a39ad1f3b28c30762061f3
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
>
> ct_timer_free() cleared hw->irq_callback, stopped the hardware timer
> and kfree()d the ct_timer while the PCI IRQ handler could still be
> running or start later: a handler that loaded hw->irq_callback
> before the NULL store calls ct_timer_interrupt() with the freed
> atimer, and the single synchronize_irq() in snd_card_disconnect()
> only covers handlers that were running at that instant -- free_irq()
> happens later, in ct_atc_destroy() -> destroy_hw_obj().
>
> synchronize_irq(hw->irq) after clearing the callback and stopping
> the hardware, before the kfree(). The hw->irq == -1 initialization
> contract is kept (the sync only runs for an installed IRQ).
[Severity: High]
The commit message is missing a Signed-off-by: trailer, which is required
under Documentation/process/submitting-patches.rst.
[Severity: Low]
Since this fixes the IRQ teardown race present since the native timer
interrupt support was added, should the commit message include:
Fixes: b7bbf876087e ("ALSA: ctxfi - Use native timer interrupt on emu20k1")
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> index 9d6f5df2bc7ef..e986f56c09fbe 100644
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -417,6 +417,14 @@ void ct_timer_free(struct ct_timer *atimer)
> hw->irq_callback = NULL;
> if (atimer->ops->free_global)
> atimer->ops->free_global(atimer);
> + /* Wait for an in-flight IRQ handler before the timer object goes
> + * away. A handler that already loaded hw->irq_callback can still
> + * call ct_timer_interrupt() with the freed atimer, and the single
> + * synchronize_irq() in snd_card_disconnect() only covers handlers
> + * that were running at that instant -- free_irq() happens later,
> + * in ct_atc_destroy() -> destroy_hw_obj(). */
> + if (hw->irq >= 0)
> + synchronize_irq(hw->irq);
> kfree(atimer);
> }
[Severity: Medium]
Can atimer->ops->free_global(atimer) race with an in-flight
ct_xfitimer_callback() when called unlocked before synchronize_irq()?
When the last substream is freed while ct_xfitimer_callback() is inside
its unlocked ct_xfitimer_check_period() window, ct_xfitimer_stop() ->
ct_xfitimer_update() sees atimer->irq_handling == 1, sets
atimer->reprogram = 1, and returns without stopping the hardware timer:
CPU0 CPU1 (<hardirq>)
ct_timer_interrupt()
ct_xfitimer_callback()
spin_lock(&atimer->lock)
atimer->irq_handling = 1
...
spin_unlock(&atimer->lock)
ct_xfitimer_check_period()
ct_timer_instance_free()
ct_xfitimer_stop()
ct_xfitimer_update()
/* irq_handling == 1: defers stop */
atimer->reprogram = 1
ct_timer_free()
hw->irq_callback = NULL
ct_xfitimer_free_global()
ct_xfitimer_irq_stop()
hw->set_timer_irq(hw, 0)
hw->set_timer_tick(hw, 0)
atimer->running = 0 <-- data race on bitfield word & MMIO
spin_lock(&atimer->lock)
ct_xfitimer_reprogram()
ct_xfitimer_irq_stop()
atimer->irq_handling = 0
spin_unlock(&atimer->lock)
synchronize_irq(hw->irq)
In struct ct_timer, irq_handling, reprogram, and running are 1-bit
bitfields sharing the same storage word, and every other caller of
ct_xfitimer_irq_stop() holds atimer->lock:
sound/pci/ctxfi/cttimer.c:struct ct_timer {
...
unsigned int irq_handling:1; /* in IRQ handling */
unsigned int reprogram:1; /* need to reprogram the internval */
unsigned int running:1; /* global timer running */
};
Running ct_xfitimer_free_global() without atimer->lock before
synchronize_irq() causes concurrent unsynchronized MMIO writes to the
timer registers and an unlocked read-modify-write on the shared bitfield
word that can clobber atimer->reprogram or atimer->irq_handling in
ct_xfitimer_callback(). Calling synchronize_irq() before
atimer->ops->free_global(atimer), or taking atimer->lock in
ct_xfitimer_free_global(), would avoid this race.
--
Sashiko AI review · https://sashiko.dev/#/patchset/48749068.582.1a212c2b537.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
2026-11-13 11:58 ` ALSA: ctxfi: free atimer only after the timer IRQ is quiesced 徐晗翔
@ 2026-11-13 12:03 ` 徐晗翔
2026-11-25 12:51 ` [PATCH] " 徐晗翔
2026-11-13 12:04 ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
` (11 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:03 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 4108 bytes --]
`ct_systimer_prepare()` is used as both the prepare callback and the
`free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
return value; `-1` means the timer callback is running on another CPU and the
timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
and `kfree()`s it while `ct_systimer_callback()` can still dereference
`ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
the timer instance, the PCM runtime, and the driver's private PCM object.
The detailed description:
* Test environment / affected version
Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
The reproducer uses the real exported `timer_delete_sync_try()` and a timer
callback; it does not call the static ctxfi functions or emulate ctxfi
hardware.
* Mechanism
`ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
`ti->substream`, `substream->runtime`, `ti->apcm`,
`substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
`ti->lock` only near the end and may re-arm the timer.
`ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
`ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
(`cttimer.c:112-116`) then does:
ct_systimer_stop(ti);
timer_delete_sync_try(&ti->timer);
`#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
function the `free_instance` callback, and `ct_systimer_ops.free_instance`
is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
`atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
`list_lock`, then `kfree(ti)`.
`timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
timer was not pending, 1 if it was pending and deactivated, and -1 if the
callback is running on another CPU. It never waits. The return value is
ignored here.
The PCM close path is `snd_pcm_release_substream()`
(`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
`snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
`runtime->private_free` is `ct_atc_pcm_free_substream()`
(`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
`ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
callback running on another CPU can use `ti`, `ti->substream->runtime`, and
`apcm` after they are freed.
* Why the fix cannot simply sleep in ct_systimer_prepare()
The same callback is also `ct_timer_ops.prepare`, called from
`ct_timer_prepare()` while `snd_pcm_prepare()` holds
`pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
The prepare path must keep a non-sleeping delete/try; the close/free path
needs a separate method.
* Trigger model
`use_system_timer=1` (module parameter; default is false), open/prepare a
PCM, let the system timer callback run, then close the PCM while the
callback is still active on another CPU. SMP/preemption required.
Consequence: UAF in timer softirq; crash or memory corruption.
* Dynamic evidence
`sndpci_race.c`, mode `v3`, runs the real
`timer_delete_sync_try()`; when it returns -1 the test frees the object while
the callback is in `mdelay()`. Show 16 KASAN reports:
sndpci_race: v3 iter=0 delete_sync_try=-1
BUG: KASAN: slab-use-after-free in v3_callback
...
Allocated by task 86: v3_thread
Freed by task 86: kfree -> v3_thread
* Suggested direction
Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
prepare path, and add a separate `ct_systimer_free()` for close/free that
first clears the callback/running state and then calls
`timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
instance list removal and `kfree(ti)`. Do not call the sleeping helper from
the PCM prepare path.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndpci_race.c --]
[-- Type: text/plain, Size: 9729 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sndpci_race.c - minimal ALSA/kernel lifetime-race reproducers for the
* sound/pci manual-review cases V3/V4/V5.
*
* The module deliberately reproduces the *lifetime patterns* used by
* ctxfi/asihpi, using only exported ALSA core and timer APIs. It is not a
* ctxfi/asihpi emulator: those drivers need hardware that this QEMU does not
* provide. The purpose is to test whether the core/API windows identified in
* the report are real on an instrumented KASAN kernel.
*
* modes:
* v3 - timer_delete_sync_try() returns -1 while the callback runs on
* another CPU; free the object anyway (ctxfi system-timer pattern).
* pcm - create a fake ALSA card with two playback substreams. The guest
* program pcmtest then exercises close (V4) or link+close (V5).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/cpumask.h>
#include <linux/sched.h>
#include <linux/container_of.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndpci_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "v3 or pcm");
/* ------------------------------------------------------------------ */
/* V3: timer_delete_sync_try() ignored -1 */
/* ------------------------------------------------------------------ */
struct v3_obj {
struct timer_list timer;
u64 cookie;
struct task_struct *thread;
};
static void v3_callback(struct timer_list *t)
{
struct v3_obj *v = container_of(t, struct v3_obj, timer);
/* Keep the callback alive long enough for the freeing CPU to run. */
mdelay(20);
pr_info(DRV ": v3 callback cookie=%#llx\n", v->cookie);
/* Second read after the delay: the object may already be freed. */
if (v->cookie == COOKIE)
pr_info(DRV ": v3 callback read-after-free survived\n");
}
static int v3_thread(void *arg)
{
struct v3_obj *v;
int i, ret;
for (i = 0; i < 8; i++) {
v = kzalloc(sizeof(*v), GFP_KERNEL);
if (!v)
return -ENOMEM;
v->cookie = COOKIE;
timer_setup(&v->timer, v3_callback, 0);
/* Pin the callback to CPU0; this thread runs on CPU1. */
add_timer_on(&v->timer, 0);
usleep_range(2000, 3000);
ret = timer_delete_sync_try(&v->timer);
pr_info(DRV ": v3 iter=%d delete_sync_try=%d\n", i, ret);
if (ret == -1) {
/* BUG: callback is running on CPU0; free it anyway. */
if (safe)
timer_delete_sync(&v->timer);
kfree(v);
} else {
timer_delete_sync(&v->timer);
kfree(v);
}
usleep_range(60000, 70000);
}
pr_info(DRV ": v3 done\n");
return 0;
}
/* ------------------------------------------------------------------ */
/* V4/V5: fake ALSA PCM with a driver-private dpcm and a timer */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct timer_list timer;
struct snd_pcm_substream *substream;
u64 cookie;
bool respawn;
bool active;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_timer(struct timer_list *t)
{
struct race_pcm *dpcm = container_of(t, struct race_pcm, timer);
struct snd_pcm_substream *s;
struct snd_pcm_runtime *victim_rt = NULL;
u64 cookie;
if (!dpcm->active)
return;
pr_info(DRV ": timer start dpcm=%px\n", dpcm);
/*
* V5 pattern: walk the link group without the group lock and read
* each member's runtime/private_data. V4 uses the same callback for
* the current stream; the delay widens the close/free window.
*/
cookie = dpcm->cookie;
if (cookie == COOKIE && dpcm->substream && dpcm->substream->runtime) {
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_pcm_runtime *rt = READ_ONCE(s->runtime);
struct race_pcm *d = NULL;
if (rt)
d = READ_ONCE(rt->private_data);
if (d && d->cookie == COOKIE) {
/* Force the compiler to keep the load. */
barrier();
}
if (rt) {
(void)READ_ONCE(rt->dma_area);
if (s != dpcm->substream && !victim_rt)
victim_rt = rt;
}
/* A real driver also reports elapsed periods. */
if (rt)
snd_pcm_period_elapsed(s);
}
}
/* Widen the window between the callback's load and the free. */
mdelay(20);
if (victim_rt) {
struct race_pcm *d = READ_ONCE(victim_rt->private_data);
pr_info(DRV ": victim use rt=%px d=%px\n", victim_rt, d);
(void)READ_ONCE(victim_rt->dma_area);
}
pr_info(DRV ": timer end dpcm=%px\n", dpcm);
if (dpcm->respawn) {
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
}
}
static void race_pcm_free(struct snd_pcm_runtime *runtime)
{
struct race_pcm *dpcm = runtime->private_data;
pr_info(DRV ": pcm private_free dpcm=%px\n", dpcm);
if (safe)
timer_shutdown_sync(&dpcm->timer);
kfree(dpcm);
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
dpcm->substream = substream;
dpcm->cookie = COOKIE;
timer_setup(&dpcm->timer, race_pcm_timer, 0);
runtime->private_data = dpcm;
runtime->private_free = race_pcm_free;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": pcm open sub=%px dpcm=%px\n", substream, dpcm);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
pr_info(DRV ": pcm .close sub=%px\n", substream);
return 0;
}
static int race_pcm_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
pr_info(DRV ": pcm ioctl cmd=%u\n", cmd);
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_info(DRV ": hw_params rate=%u ch=%u fmt=%u period_bytes=%u buffer_bytes=%u\n",
params_rate(params), params_channels(params), params_format(params),
params_period_bytes(params), params_buffer_bytes(params));
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct race_pcm *dpcm = substream->runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream != race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
break;
dpcm->active = true;
dpcm->respawn = true;
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dpcm->active = false;
dpcm->respawn = false;
/* Deliberately not timer_delete_sync(): mirrors asihpi. */
timer_delete(&dpcm->timer);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.ioctl = race_pcm_ioctl,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int __init sndpci_init(void)
{
struct task_struct *t;
int ret;
pr_info(DRV ": init mode=%s\n", mode);
if (!strcmp(mode, "v3")) {
t = kthread_create(v3_thread, NULL, "sndpci_v3");
if (IS_ERR(t))
return PTR_ERR(t);
kthread_bind(t, 1);
wake_up_process(t);
return 0;
}
race_pdev = platform_device_register_simple("sndpci_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndPciRace", THIS_MODULE, 0, &race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndPciRace", 0, 0, 2, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE,
&race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev, SNDRV_DMA_TYPE_CONTINUOUS,
NULL, 64 * 1024, 64 * 1024);
ret = 0;
pr_info(DRV ": managed_buffer ret=%d dma_type=%d area=%px bytes=%zu\n", ret,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.dev.type,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.area,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.bytes);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered\n");
return 0;
}
static void __exit sndpci_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndpci_init);
module_exit(sndpci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/pci lifetime-race reproducer (V3/V4/V5)");
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-13 12:03 ` ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF) 徐晗翔
@ 2026-11-25 12:51 ` 徐晗翔
2026-11-25 13:05 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:51 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
ct_systimer_prepare() served as both the prepare callback and the
free_instance callback and ignored the -1 return of
timer_delete_sync_try() (-1 means the callback is running on
another CPU and was NOT deleted); ct_timer_instance_free() then
kfree()d the instance while ct_systimer_callback() still
dereferenced ti->substream, substream->runtime, ti->apcm and
ti->position -- a UAF on a normal PCM close with use_system_timer=1.
Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
lock, where a sleeping wait would be 'scheduling while atomic'), and
give the free path its own ct_systimer_free() that calls
timer_shutdown_sync() before the instance is removed and kfree()d.
---
sound/pci/ctxfi/cttimer.c | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
--- a/sound/pci/ctxfi/cttimer.c
+++ b/sound/pci/ctxfi/cttimer.c
@@ -111,11 +111,24 @@
static void ct_systimer_prepare(struct ct_timer_instance *ti)
{
+ /* keep the try variant here: this callback also runs from
+ * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
+ * a sleeping wait would be a "scheduling while atomic" */
ct_systimer_stop(ti);
timer_delete_sync_try(&ti->timer);
}
-#define ct_systimer_free ct_systimer_prepare
+static void ct_systimer_free(struct ct_timer_instance *ti)
+{
+ /* the close/free path runs in process context and must wait for a
+ * callback that is already running on another CPU before the
+ * instance (and the PCM runtime / apcm it dereferences) is removed
+ * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
+ * case without waiting, so a UAF followed. Use the full shutdown
+ * sync here, but do NOT route prepare through it. */
+ ct_systimer_stop(ti);
+ timer_shutdown_sync(&ti->timer);
+}
static const struct ct_timer_ops ct_systimer_ops = {
.init = ct_systimer_init,
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:03:25 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
>
> `ct_systimer_prepare()` is used as both the prepare callback and the
> `free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
> return value; `-1` means the timer callback is running on another CPU and the
> timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
> and `kfree()`s it while `ct_systimer_callback()` can still dereference
> `ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
> A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
> the timer instance, the PCM runtime, and the driver's private PCM object.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
> The reproducer uses the real exported `timer_delete_sync_try()` and a timer
> callback; it does not call the static ctxfi functions or emulate ctxfi
> hardware.
>
> * Mechanism
>
> `ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
> `ti->substream`, `substream->runtime`, `ti->apcm`,
> `substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
> `ti->lock` only near the end and may re-arm the timer.
>
> `ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
> `ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
> (`cttimer.c:112-116`) then does:
>
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
>
> `#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
> function the `free_instance` callback, and `ct_systimer_ops.free_instance`
> is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
> `atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
> `list_lock`, then `kfree(ti)`.
>
> `timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
> timer was not pending, 1 if it was pending and deactivated, and -1 if the
> callback is running on another CPU. It never waits. The return value is
> ignored here.
>
> The PCM close path is `snd_pcm_release_substream()`
> (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
> `snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
> `runtime->private_free` is `ct_atc_pcm_free_substream()`
> (`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
> `ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
> callback running on another CPU can use `ti`, `ti->substream->runtime`, and
> `apcm` after they are freed.
>
> * Why the fix cannot simply sleep in ct_systimer_prepare()
>
> The same callback is also `ct_timer_ops.prepare`, called from
> `ct_timer_prepare()` while `snd_pcm_prepare()` holds
> `pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
> sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
> The prepare path must keep a non-sleeping delete/try; the close/free path
> needs a separate method.
>
> * Trigger model
>
> `use_system_timer=1` (module parameter; default is false), open/prepare a
> PCM, let the system timer callback run, then close the PCM while the
> callback is still active on another CPU. SMP/preemption required.
> Consequence: UAF in timer softirq; crash or memory corruption.
>
> * Dynamic evidence
>
> `sndpci_race.c`, mode `v3`, runs the real
> `timer_delete_sync_try()`; when it returns -1 the test frees the object while
> the callback is in `mdelay()`. Show 16 KASAN reports:
>
> sndpci_race: v3 iter=0 delete_sync_try=-1
> BUG: KASAN: slab-use-after-free in v3_callback
> ...
> Allocated by task 86: v3_thread
> Freed by task 86: kfree -> v3_thread
>
>
>
> * Suggested direction
>
> Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
> prepare path, and add a separate `ct_systimer_free()` for close/free that
> first clears the callback/running state and then calls
> `timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
> instance list removal and `kfree(ti)`. Do not call the sleeping helper from
> the PCM prepare path.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-25 12:51 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:05 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:05 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] ALSA: ctxfi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: ctxfi: ct_systimer_prepare() skips timer sync on false
lock claim
- [Low] ALSA: ctxfi: missing Fixes trailer in commit message
--
commit e750bb6cd03b9a9826e84cf3cb74558902482fe7
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
>
> ct_systimer_prepare() served as both the prepare callback and the
> free_instance callback and ignored the -1 return of
> timer_delete_sync_try() (-1 means the callback is running on
> another CPU and was NOT deleted); ct_timer_instance_free() then
> kfree()d the instance while ct_systimer_callback() still
> dereferenced ti->substream, substream->runtime, ti->apcm and
> ti->position -- a UAF on a normal PCM close with use_system_timer=1.
>
> Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
> also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
> lock, where a sleeping wait would be 'scheduling while atomic'), and
> give the free path its own ct_systimer_free() that calls
> timer_shutdown_sync() before the instance is removed and kfree()d.
[Severity: High]
The commit message is missing a Signed-off-by: trailer.
[Severity: Low]
Since this fixes a bug, should the commit message include a Fixes: tag?
Fixes: b7bbf876087e ("ALSA: ctxfi - Use native timer interrupt on emu20k1")
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> index 9d6f5df2bc7ef..ad463321cac2e 100644
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -111,11 +111,24 @@ static void ct_systimer_stop(struct ct_timer_instance *ti)
>
> static void ct_systimer_prepare(struct ct_timer_instance *ti)
> {
> + /* keep the try variant here: this callback also runs from
> + * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
> + * a sleeping wait would be a "scheduling while atomic" */
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
> }
>
> -#define ct_systimer_free ct_systimer_prepare
> +static void ct_systimer_free(struct ct_timer_instance *ti)
> +{
> + /* the close/free path runs in process context and must wait for a
> + * callback that is already running on another CPU before the
> + * instance (and the PCM runtime / apcm it dereferences) is removed
> + * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
> + * case without waiting, so a UAF followed. Use the full shutdown
> + * sync here, but do NOT route prepare through it. */
> + ct_systimer_stop(ti);
> + timer_shutdown_sync(&ti->timer);
> +}
[Severity: Medium]
Should ct_systimer_prepare() use timer_delete_sync() instead of
timer_delete_sync_try()?
snd_pcm_prepare() drops the stream lock before invoking the .prepare
callback via snd_pcm_action_nonatomic():
sound/core/pcm_native.c:snd_pcm_prepare() {
scoped_guard(pcm_stream_lock_irq, substream) {
...
}
return snd_pcm_action_nonatomic(&snd_pcm_action_prepare,
substream,
(snd_pcm_state_t)f_flags);
}
All three callers of ct_timer_prepare() in sound/pci/ctxfi/ctatc.c
(atc_pcm_playback_prepare(), atc_pcm_capture_prepare() and
spdif_passthru_playback_prepare()) already run in sleepable process
context and take atc->atc_mutex right before calling ct_timer_prepare().
With timer_delete_sync_try(&ti->timer) ignoring a -1 return when
ct_systimer_callback() is running on another CPU, ct_timer_prepare() and
a following ct_timer_start() can race with the in-flight callback:
CPU0 CPU1
ct_timer_prepare(ti) ct_systimer_callback()
ct_systimer_prepare(ti) ...
ct_systimer_stop(ti)
timer_delete_sync_try() -> -1
ti->position = 0;
ti->running = 0;
ct_timer_start(ti)
ct_systimer_start(ti)
ti->running = 1;
mod_timer(&ti->timer, ...)
apcm->interrupt(apcm);
ti->position = position;
<-- clobbers reset position
if (ti->running)
mod_timer(&ti->timer, ...)
<-- re-arms with stale interval
Calling timer_delete_sync(&ti->timer) in ct_systimer_prepare() waits for
any running callback while still allowing the timer to be re-armed on the
next start.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20f42cfd.589.1a212c337be.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
2026-11-13 11:58 ` ALSA: ctxfi: free atimer only after the timer IRQ is quiesced 徐晗翔
2026-11-13 12:03 ` ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF) 徐晗翔
@ 2026-11-13 12:04 ` 徐晗翔
2026-11-25 12:50 ` [PATCH] " 徐晗翔
2026-11-13 12:06 ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
` (10 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:04 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
`snd_asihpi_remove()` frees the ALSA card and then sends HPI_ADAPTER_DELETE
(which frees the HPI6205 `phw`) before `free_irq()`. Both the primary IRQ
handler and the threaded handler can therefore run against freed memory:
the primary handler dereferences `phw->prHSR` through
`adapter_irq_query_and_clear()`, and the threaded callback dereferences
`a->snd_card->private_data` after the card private area has been freed.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree. Affected hardware path: ASI6205/HPI6205 in
interrupt mode (`low_latency_mode && irq_supported`, `interrupt_mode=1`).
HPI6000 does not set `irq_query_and_clear` and is polled, so it is not part
of this report.
* Mechanism
`snd_asihpi_remove()` (`sound/pci/asihpi/asihpi.c:2919-2933`):
hpi->interrupt_callback = NULL; /* if interrupt_mode */
... send HPI IRQ rate 0 ...
snd_card_free(hpi->snd_card); /* line 2930 */
hpi->snd_card = NULL; /* line 2931 */
asihpi_adapter_remove(pci_dev); /* line 2932 */
`asihpi_adapter_remove()` (`hpioctl.c:520-555`) then sends IRQ rate 0,
sends `HPI_ADAPTER_DELETE` (537-540), and only afterwards calls
`free_irq(pa->irq, pa)` (542-543).
HPI6205 `adapter_delete()` (`hpi6205.c:491-510`) -> `delete_adapter_obj()`
(`hpi6205.c:675-704`) does `kfree(phw)` at 703 without clearing
`pao->priv`, then `hpi_delete_adapter()` (`hpicmn.c:96-108`) memsets the
registry object at 106. The primary handler `asihpi_isr()`
(`hpioctl.c:311-335`) checks `a->adapter->irq_query_and_clear` and calls
it; HPI6205 installs that handler at `hpi6205.c:662`, and
`adapter_irq_query_and_clear()` (`hpi6205.c:708-722`) does
`ioread32(phw->prHSR)` at 714.
Window A (phw UAF): the handler loads the function pointer before
`delete_adapter_obj()` frees `phw`, and executes after the free.
Window B (NULL deref): the handler executes after `hpi_delete_adapter()`
memsets the registry, so `pao->priv` is NULL and `phw->prHSR` is a NULL
dereference.
Window C (card private UAF): `asihpi_isr_thread()` (`hpioctl.c:337-344`)
calls `a->interrupt_callback(a)`; `snd_card_asihpi_isr()`
(`asihpi.c:898-907`) reads `a->snd_card->private_data` and
`asihpi->llmode_streampriv`. The card private area is allocated by
`snd_card_new(..., sizeof(struct snd_card_asihpi), ...)`
(`asihpi.c:2794-2799`) and freed by `snd_card_do_free()`
(`sound/core/init.c:584-611`, `kfree(card)` at 610). After
`hpi->snd_card = NULL`, the same callback can also return NULL from the
`snd_card` load and hit the WARN_ON/NULL path.
* Why existing synchronization does not close the window
asihpi never sets `card->sync_irq`, so `snd_card_disconnect()` does not call
`synchronize_irq()`. `snd_card_free()` waits for open files and the card
release completion, not for the IRQ handler/thread. `free_irq()` is the
first operation that quiesces the IRQ, and it happens after `snd_card_free()`
and after HPI_ADAPTER_DELETE has freed `phw`.
* Trigger model
HPI6205 device in IRQ mode; remove/unbind the PCI device. Root is needed
for unbind/remove. Consequence: UAF/NULL deref in hard IRQ or threaded IRQ
context; crash or memory corruption. The report does not claim a
concurrent user ioctl path: the card file drain prevents that, and only the
single remove path sends HPI_ADAPTER_DELETE.
* Suggested direction
Free/quiesce the IRQ before `snd_card_free()` and before sending
HPI_ADAPTER_DELETE:
if (hpi->irq) {
free_irq(hpi->irq, hpi);
hpi->irq = 0;
}
snd_card_free(hpi->snd_card);
Keep the existing `if (pa->irq)` guard in `asihpi_adapter_remove()` to avoid
a double free. Alternatively set `card->sync_irq` and perform an explicit
`synchronize_irq()` before releasing the card private data, but freeing the
IRQ first is simpler and also covers the `phw` window.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
2026-11-13 12:04 ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
@ 2026-11-25 12:50 ` 徐晗翔
2026-11-25 13:03 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:50 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_asihpi_remove() freed the ALSA card and then sent
HPI_ADAPTER_DELETE (kfree()ing the HPI6205 phw) BEFORE free_irq():
both the primary handler (adapter_irq_query_and_clear() reads
phw->prHSR) and the threaded handler (snd_card_asihpi_isr() reads
a->snd_card->private_data) could run against freed memory.
free_irq() -- the first operation that waits for the in-flight
primary and threaded handlers -- now runs before snd_card_free()
and before HPI_ADAPTER_DELETE, with hpi->irq cleared so the existing
if (pa->irq) guard in asihpi_adapter_remove() does not double-free
---
sound/pci/asihpi/asihpi.c | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
--- a/sound/pci/asihpi/asihpi.c
+++ b/sound/pci/asihpi/asihpi.c
@@ -2927,6 +2927,20 @@
HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
}
+ /* Free/quiesce the IRQ before the card and the HPI adapter objects
+ * go away: free_irq() is the first (and only) operation that waits
+ * for the in-flight primary and threaded handlers. Afterwards
+ * snd_card_free() releases the card private area (read by
+ * snd_card_asihpi_isr() through a->snd_card->private_data) and
+ * asihpi_adapter_remove() sends HPI_ADAPTER_DELETE, which kfree()s
+ * the phw whose prHSR the primary handler dereferences through
+ * adapter_irq_query_and_clear(). asihpi_adapter_remove() keeps its
+ * if (pa->irq) guard, so this is not a double free_irq(). */
+ if (hpi->irq) {
+ free_irq(hpi->irq, hpi);
+ hpi->irq = 0;
+ }
+
snd_card_free(hpi->snd_card);
hpi->snd_card = NULL;
asihpi_adapter_remove(pci_dev);
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:04:48 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
>
> `snd_asihpi_remove()` frees the ALSA card and then sends HPI_ADAPTER_DELETE
> (which frees the HPI6205 `phw`) before `free_irq()`. Both the primary IRQ
> handler and the threaded handler can therefore run against freed memory:
> the primary handler dereferences `phw->prHSR` through
> `adapter_irq_query_and_clear()`, and the threaded callback dereferences
> `a->snd_card->private_data` after the card private area has been freed.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree. Affected hardware path: ASI6205/HPI6205 in
> interrupt mode (`low_latency_mode && irq_supported`, `interrupt_mode=1`).
> HPI6000 does not set `irq_query_and_clear` and is polled, so it is not part
> of this report.
>
> * Mechanism
>
> `snd_asihpi_remove()` (`sound/pci/asihpi/asihpi.c:2919-2933`):
>
> hpi->interrupt_callback = NULL; /* if interrupt_mode */
> ... send HPI IRQ rate 0 ...
> snd_card_free(hpi->snd_card); /* line 2930 */
> hpi->snd_card = NULL; /* line 2931 */
> asihpi_adapter_remove(pci_dev); /* line 2932 */
>
> `asihpi_adapter_remove()` (`hpioctl.c:520-555`) then sends IRQ rate 0,
> sends `HPI_ADAPTER_DELETE` (537-540), and only afterwards calls
> `free_irq(pa->irq, pa)` (542-543).
>
> HPI6205 `adapter_delete()` (`hpi6205.c:491-510`) -> `delete_adapter_obj()`
> (`hpi6205.c:675-704`) does `kfree(phw)` at 703 without clearing
> `pao->priv`, then `hpi_delete_adapter()` (`hpicmn.c:96-108`) memsets the
> registry object at 106. The primary handler `asihpi_isr()`
> (`hpioctl.c:311-335`) checks `a->adapter->irq_query_and_clear` and calls
> it; HPI6205 installs that handler at `hpi6205.c:662`, and
> `adapter_irq_query_and_clear()` (`hpi6205.c:708-722`) does
> `ioread32(phw->prHSR)` at 714.
>
> Window A (phw UAF): the handler loads the function pointer before
> `delete_adapter_obj()` frees `phw`, and executes after the free.
>
> Window B (NULL deref): the handler executes after `hpi_delete_adapter()`
> memsets the registry, so `pao->priv` is NULL and `phw->prHSR` is a NULL
> dereference.
>
> Window C (card private UAF): `asihpi_isr_thread()` (`hpioctl.c:337-344`)
> calls `a->interrupt_callback(a)`; `snd_card_asihpi_isr()`
> (`asihpi.c:898-907`) reads `a->snd_card->private_data` and
> `asihpi->llmode_streampriv`. The card private area is allocated by
> `snd_card_new(..., sizeof(struct snd_card_asihpi), ...)`
> (`asihpi.c:2794-2799`) and freed by `snd_card_do_free()`
> (`sound/core/init.c:584-611`, `kfree(card)` at 610). After
> `hpi->snd_card = NULL`, the same callback can also return NULL from the
> `snd_card` load and hit the WARN_ON/NULL path.
>
> * Why existing synchronization does not close the window
>
> asihpi never sets `card->sync_irq`, so `snd_card_disconnect()` does not call
> `synchronize_irq()`. `snd_card_free()` waits for open files and the card
> release completion, not for the IRQ handler/thread. `free_irq()` is the
> first operation that quiesces the IRQ, and it happens after `snd_card_free()`
> and after HPI_ADAPTER_DELETE has freed `phw`.
>
> * Trigger model
>
> HPI6205 device in IRQ mode; remove/unbind the PCI device. Root is needed
> for unbind/remove. Consequence: UAF/NULL deref in hard IRQ or threaded IRQ
> context; crash or memory corruption. The report does not claim a
> concurrent user ioctl path: the card file drain prevents that, and only the
> single remove path sends HPI_ADAPTER_DELETE.
>
> * Suggested direction
>
> Free/quiesce the IRQ before `snd_card_free()` and before sending
> HPI_ADAPTER_DELETE:
>
> if (hpi->irq) {
> free_irq(hpi->irq, hpi);
> hpi->irq = 0;
> }
> snd_card_free(hpi->snd_card);
>
> Keep the existing `if (pa->irq)` guard in `asihpi_adapter_remove()` to avoid
> a double free. Alternatively set `card->sync_irq` and perform an explicit
> `synchronize_irq()` before releasing the card private data, but freeing the
> IRQ first is simpler and also covers the `phw` window.
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
2026-11-25 12:50 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:03 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:03 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] ALSA: asihpi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: asihpi: free_irq() before snd_card_disconnect() in
snd_asihpi_remove()
- [Low] ALSA: asihpi: missing Fixes trailer in bug-fix commit message
- [Low] ALSA: asihpi: free_irq() remains after HPI_ADAPTER_DELETE in
asihpi_adapter_remove()
--
commit 66e65e67203827236524ee91f5a02759ca055bf4
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
>
> snd_asihpi_remove() freed the ALSA card and then sent
> HPI_ADAPTER_DELETE (kfree()ing the HPI6205 phw) BEFORE free_irq():
> both the primary handler (adapter_irq_query_and_clear() reads
> phw->prHSR) and the threaded handler (snd_card_asihpi_isr() reads
> a->snd_card->private_data) could run against freed memory.
>
> free_irq() -- the first operation that waits for the in-flight
> primary and threaded handlers -- now runs before snd_card_free()
> and before HPI_ADAPTER_DELETE, with hpi->irq cleared so the existing
> if (pa->irq) guard in asihpi_adapter_remove() does not double-free
[Severity: High]
The commit message is missing a Signed-off-by: trailer, which is required by
the Developer's Certificate of Origin (Documentation/process/submitting-patches.rst).
[Severity: Low]
Since this fixes a use-after-free bug on device removal, should the commit
message include a Fixes: trailer (and a closing period on the last sentence):
Fixes: f9a376c3f6d7 ("ALSA: asihpi: Add support for stream interrupt.")
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> index b78e96caef9d0..e3d863c4bdc88 100644
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -2927,6 +2927,20 @@ static void snd_asihpi_remove(struct pci_dev *pci_dev)
> HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
> }
>
> + /* Free/quiesce the IRQ before the card and the HPI adapter objects
> + * go away: free_irq() is the first (and only) operation that waits
> + * for the in-flight primary and threaded handlers. Afterwards
> + * snd_card_free() releases the card private area (read by
> + * snd_card_asihpi_isr() through a->snd_card->private_data) and
> + * asihpi_adapter_remove() sends HPI_ADAPTER_DELETE, which kfree()s
> + * the phw whose prHSR the primary handler dereferences through
> + * adapter_irq_query_and_clear(). asihpi_adapter_remove() keeps its
> + * if (pa->irq) guard, so this is not a double free_irq(). */
> + if (hpi->irq) {
> + free_irq(hpi->irq, hpi);
> + hpi->irq = 0;
> + }
> +
> snd_card_free(hpi->snd_card);
> hpi->snd_card = NULL;
> asihpi_adapter_remove(pci_dev);
[Severity: Medium]
Can a concurrent PCM trigger re-enable DSP interrupts on HPI6205 before
snd_card_free() disconnects the card, leaving the shared PCI INTx line
asserted after free_irq() removes asihpi_isr()?
CPU0 CPU1
snd_asihpi_remove()
hpi_adapter_set_property(...,
HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0)
snd_card_asihpi_trigger()
snd_card_asihpi_pcm_int_start()
hpi_adapter_set_property(...,
HPI_ADAPTER_PROPERTY_IRQ_RATE,
card->update_interval_frames, 0)
free_irq(hpi->irq, hpi)
snd_card_free(hpi->snd_card)
snd_card_free_when_closed()
snd_card_disconnect()
wait_for_completion(&released) <-- DSP asserts C6205_HSR_INTSRC with
no handler to clear phw->prHSR
ALSA file operations remain active until snd_card_disconnect() runs inside
snd_card_free(). If a concurrent PCM start or pause-release trigger (or an
HPI_ADAPTER_SET_PROPERTY hwdep ioctl) sets HPI_ADAPTER_PROPERTY_IRQ_RATE back
to a non-zero value before snd_card_disconnect(), the DSP can assert the
shared level-triggered interrupt after free_irq() has unregistered
asihpi_isr(). Even after snd_card_disconnect() stops the stream by zeroing
HPI_ADAPTER_PROPERTY_IRQ_RATE, nothing clears C6205_HSR_INTSRC in phw->prHSR
while snd_card_free() waits for open descriptors to close, causing an
unhandled interrupt storm. Calling snd_card_disconnect(hpi->snd_card) before
disabling HPI_ADAPTER_PROPERTY_IRQ_RATE and calling free_irq() would stop
active streams and block new userspace operations while keeping
hpi->snd_card allocated until snd_card_free().
[Severity: Low]
Does clearing hpi->irq here leave the free_irq() call in
asihpi_adapter_remove() as dead code while keeping the broken teardown order
in asihpi_adapter_remove() itself?
sound/pci/asihpi/hpioctl.c:asihpi_adapter_remove() {
...
hpi_init_message_response(&hm, &hr, HPI_OBJ_ADAPTER,
HPI_ADAPTER_DELETE);
hm.adapter_index = pa->adapter->index;
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
if (pa->irq)
free_irq(pa->irq, pa);
...
}
asihpi_adapter_probe() requests the IRQ, and asihpi_adapter_remove() is its
teardown counterpart, where HPI_ADAPTER_DELETE still runs before free_irq().
Removing the duplicate free_irq() from asihpi_adapter_remove() (or moving it
before HPI_ADAPTER_DELETE) would avoid leaving dead code and a latent
use-after-free trap for any direct caller of asihpi_adapter_remove().
--
Sashiko AI review · https://sashiko.dev/#/patchset/2c1d9b73.57c.1a212c1b142.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (2 preceding siblings ...)
2026-11-13 12:04 ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
@ 2026-11-13 12:06 ` 徐晗翔
2026-11-25 12:50 ` [PATCH] " 徐晗翔
2026-11-13 12:15 ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
` (9 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:06 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 3582 bytes --]
`snd_card_asihpi_runtime_free()` frees the per-open `struct
snd_card_asihpi_pcm` while a polled timer callback or an IRQ/threaded handler
can still use it. The polled stop path uses `timer_delete()` (not
`timer_delete_sync()`), and the IRQ stop path clears
`card->llmode_streampriv` without `synchronize_irq()`. A normal PCM close can
therefore free `dpcm` and then `runtime` while the callback is still running.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
was available; the harness validates the ALSA core close ordering and the
exact `timer_delete`/`llmode_streampriv` lifetime pattern.
* Mechanism
`snd_card_asihpi_runtime_free()` (`asihpi.c:495-499`) does `kfree(dpcm)` and
is installed as `runtime->private_free` at playback open
(`asihpi.c:997-1000`) and capture open (`1166-1169`).
Polled mode:
snd_card_asihpi_pcm_timer_start() asihpi.c:501-513
mod_timer(&dpcm->timer, jiffies + expiry);
dpcm->respawn_timer = 1;
snd_card_asihpi_pcm_timer_stop() asihpi.c:515-522
dpcm->respawn_timer = 0;
timer_delete(&dpcm->timer); /* no sync */
`snd_card_asihpi_timer_function()` (`asihpi.c:710-896`) uses `dpcm`
throughout and can re-arm at 894-895 if it observes `respawn_timer`.
IRQ mode:
snd_card_asihpi_pcm_int_start() asihpi.c:524-538
card->llmode_streampriv = dpcm;
... set HPI IRQ rate ...
snd_card_asihpi_pcm_int_stop() asihpi.c:540-550
... set HPI IRQ rate 0 ...
card->llmode_streampriv = NULL; /* no synchronize_irq */
`snd_card_asihpi_isr()` (`asihpi.c:898-907`) reads
`asihpi->llmode_streampriv` twice (check, then dereference), so a threaded
handler can hold the old `dpcm` pointer across the NULL store.
Close path: `snd_pcm_release_substream()`
(`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()`
(`pcm_native.c:2267-2289`) -> `snd_pcm_detach_substream()`
(`sound/core/pcm.c:978-1005`) -> `runtime->private_free()` -> `kfree(dpcm)`
and then `kfree(runtime)`.
* Trigger model
Local user opens a capture or playback PCM, starts it, and closes it while
the polled timer or HPI IRQ is active. Polled mode is available on HPI6000
and HPI6205; IRQ mode requires HPI6205 in interrupt mode. SMP/preemption
needed for the cross-CPU window. Consequence: UAF of `dpcm`/`runtime` in
timer softirq or threaded IRQ; crash or memory corruption.
* Dynamic evidence
`sndpci_race.c` mode `pcm`, `verification/kmod/
sndpci/pcmtest.c close 200`: `.trigger STOP` uses `timer_delete()` and
`runtime->private_free` frees `dpcm`; timer pinned to CPU0, user close to
CPU1. Contain 35 KASAN UAF report fragments:
BUG: KASAN: slab-use-after-free in race_pcm_timer
...
Allocated by task: race_pcm_open
Freed by task: kfree -> snd_pcm_detach_substream -> snd_pcm_release
* Suggested direction
In `snd_card_asihpi_runtime_free()` (or immediately before it), for polled
mode call `timer_shutdown_sync(&dpcm->timer)`. For IRQ mode, first clear
`card->llmode_streampriv` (with the appropriate ordering), then
`synchronize_irq(card->hpi->irq)` before `kfree(dpcm)`. Do not put the
sleeping sync inside the PCM stream lock; do it in the detach/private_free
process context. Also consider quiescing before the HPI stream `.close`
(the extra HPI stream handle window is discussed in the report).
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndpci_race.c --]
[-- Type: text/plain, Size: 9729 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sndpci_race.c - minimal ALSA/kernel lifetime-race reproducers for the
* sound/pci manual-review cases V3/V4/V5.
*
* The module deliberately reproduces the *lifetime patterns* used by
* ctxfi/asihpi, using only exported ALSA core and timer APIs. It is not a
* ctxfi/asihpi emulator: those drivers need hardware that this QEMU does not
* provide. The purpose is to test whether the core/API windows identified in
* the report are real on an instrumented KASAN kernel.
*
* modes:
* v3 - timer_delete_sync_try() returns -1 while the callback runs on
* another CPU; free the object anyway (ctxfi system-timer pattern).
* pcm - create a fake ALSA card with two playback substreams. The guest
* program pcmtest then exercises close (V4) or link+close (V5).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/cpumask.h>
#include <linux/sched.h>
#include <linux/container_of.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndpci_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "v3 or pcm");
/* ------------------------------------------------------------------ */
/* V3: timer_delete_sync_try() ignored -1 */
/* ------------------------------------------------------------------ */
struct v3_obj {
struct timer_list timer;
u64 cookie;
struct task_struct *thread;
};
static void v3_callback(struct timer_list *t)
{
struct v3_obj *v = container_of(t, struct v3_obj, timer);
/* Keep the callback alive long enough for the freeing CPU to run. */
mdelay(20);
pr_info(DRV ": v3 callback cookie=%#llx\n", v->cookie);
/* Second read after the delay: the object may already be freed. */
if (v->cookie == COOKIE)
pr_info(DRV ": v3 callback read-after-free survived\n");
}
static int v3_thread(void *arg)
{
struct v3_obj *v;
int i, ret;
for (i = 0; i < 8; i++) {
v = kzalloc(sizeof(*v), GFP_KERNEL);
if (!v)
return -ENOMEM;
v->cookie = COOKIE;
timer_setup(&v->timer, v3_callback, 0);
/* Pin the callback to CPU0; this thread runs on CPU1. */
add_timer_on(&v->timer, 0);
usleep_range(2000, 3000);
ret = timer_delete_sync_try(&v->timer);
pr_info(DRV ": v3 iter=%d delete_sync_try=%d\n", i, ret);
if (ret == -1) {
/* BUG: callback is running on CPU0; free it anyway. */
if (safe)
timer_delete_sync(&v->timer);
kfree(v);
} else {
timer_delete_sync(&v->timer);
kfree(v);
}
usleep_range(60000, 70000);
}
pr_info(DRV ": v3 done\n");
return 0;
}
/* ------------------------------------------------------------------ */
/* V4/V5: fake ALSA PCM with a driver-private dpcm and a timer */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct timer_list timer;
struct snd_pcm_substream *substream;
u64 cookie;
bool respawn;
bool active;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_timer(struct timer_list *t)
{
struct race_pcm *dpcm = container_of(t, struct race_pcm, timer);
struct snd_pcm_substream *s;
struct snd_pcm_runtime *victim_rt = NULL;
u64 cookie;
if (!dpcm->active)
return;
pr_info(DRV ": timer start dpcm=%px\n", dpcm);
/*
* V5 pattern: walk the link group without the group lock and read
* each member's runtime/private_data. V4 uses the same callback for
* the current stream; the delay widens the close/free window.
*/
cookie = dpcm->cookie;
if (cookie == COOKIE && dpcm->substream && dpcm->substream->runtime) {
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_pcm_runtime *rt = READ_ONCE(s->runtime);
struct race_pcm *d = NULL;
if (rt)
d = READ_ONCE(rt->private_data);
if (d && d->cookie == COOKIE) {
/* Force the compiler to keep the load. */
barrier();
}
if (rt) {
(void)READ_ONCE(rt->dma_area);
if (s != dpcm->substream && !victim_rt)
victim_rt = rt;
}
/* A real driver also reports elapsed periods. */
if (rt)
snd_pcm_period_elapsed(s);
}
}
/* Widen the window between the callback's load and the free. */
mdelay(20);
if (victim_rt) {
struct race_pcm *d = READ_ONCE(victim_rt->private_data);
pr_info(DRV ": victim use rt=%px d=%px\n", victim_rt, d);
(void)READ_ONCE(victim_rt->dma_area);
}
pr_info(DRV ": timer end dpcm=%px\n", dpcm);
if (dpcm->respawn) {
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
}
}
static void race_pcm_free(struct snd_pcm_runtime *runtime)
{
struct race_pcm *dpcm = runtime->private_data;
pr_info(DRV ": pcm private_free dpcm=%px\n", dpcm);
if (safe)
timer_shutdown_sync(&dpcm->timer);
kfree(dpcm);
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
dpcm->substream = substream;
dpcm->cookie = COOKIE;
timer_setup(&dpcm->timer, race_pcm_timer, 0);
runtime->private_data = dpcm;
runtime->private_free = race_pcm_free;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": pcm open sub=%px dpcm=%px\n", substream, dpcm);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
pr_info(DRV ": pcm .close sub=%px\n", substream);
return 0;
}
static int race_pcm_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
pr_info(DRV ": pcm ioctl cmd=%u\n", cmd);
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_info(DRV ": hw_params rate=%u ch=%u fmt=%u period_bytes=%u buffer_bytes=%u\n",
params_rate(params), params_channels(params), params_format(params),
params_period_bytes(params), params_buffer_bytes(params));
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct race_pcm *dpcm = substream->runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream != race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
break;
dpcm->active = true;
dpcm->respawn = true;
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dpcm->active = false;
dpcm->respawn = false;
/* Deliberately not timer_delete_sync(): mirrors asihpi. */
timer_delete(&dpcm->timer);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.ioctl = race_pcm_ioctl,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int __init sndpci_init(void)
{
struct task_struct *t;
int ret;
pr_info(DRV ": init mode=%s\n", mode);
if (!strcmp(mode, "v3")) {
t = kthread_create(v3_thread, NULL, "sndpci_v3");
if (IS_ERR(t))
return PTR_ERR(t);
kthread_bind(t, 1);
wake_up_process(t);
return 0;
}
race_pdev = platform_device_register_simple("sndpci_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndPciRace", THIS_MODULE, 0, &race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndPciRace", 0, 0, 2, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE,
&race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev, SNDRV_DMA_TYPE_CONTINUOUS,
NULL, 64 * 1024, 64 * 1024);
ret = 0;
pr_info(DRV ": managed_buffer ret=%d dma_type=%d area=%px bytes=%zu\n", ret,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.dev.type,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.area,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.bytes);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered\n");
return 0;
}
static void __exit sndpci_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndpci_init);
module_exit(sndpci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/pci lifetime-race reproducer (V3/V4/V5)");
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
2026-11-13 12:06 ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
@ 2026-11-25 12:50 ` 徐晗翔
2026-11-25 13:06 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:50 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_card_asihpi_runtime_free() kfree()d the per-open
snd_card_asihpi_pcm while a polled timer callback or an
IRQ/threaded handler could still use it: the polled stop path uses
plain timer_delete() (no wait for a running callback), and the IRQ
stop path clears card->llmode_streampriv with a plain store and no
synchronize_irq().
Quiesce in runtime->private_free, which runs in process context from
snd_pcm_detach_substream() outside the PCM stream lock (so the
sleeping sync calls are allowed there): timer_shutdown_sync() for
the polled timer; for IRQ mode, clear card->llmode_streampriv and
synchronize_irq(card->hpi->irq) before the kfree(dpcm).
---
sound/pci/asihpi/asihpi.c | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
--- a/sound/pci/asihpi/asihpi.c
+++ b/sound/pci/asihpi/asihpi.c
@@ -495,6 +495,29 @@
static void snd_card_asihpi_runtime_free(struct snd_pcm_runtime *runtime)
{
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
+ struct snd_card_asihpi *card = snd_pcm_substream_chip(dpcm->substream);
+
+ /* Quiesce the polled timer and the low-latency IRQ stream before
+ * the memory goes away. This runs in process context from
+ * snd_pcm_detach_substream(), outside the PCM stream lock, so the
+ * sleeping sync calls are allowed here (they must NOT be put into
+ * the trigger/stop path under the stream lock).
+ *
+ * Polled mode: snd_card_asihpi_pcm_timer_stop() uses plain
+ * timer_delete(), which does not wait for a callback that is
+ * already running on another CPU -- the callback dereferences dpcm
+ * throughout and re-arms itself if it observes respawn_timer set.
+ *
+ * IRQ mode: card->llmode_streampriv is cleared with a plain store
+ * by snd_card_asihpi_pcm_int_stop(); the threaded handler may
+ * already have loaded the pointer, so synchronize the IRQ line
+ * after clearing before the kfree(). */
+ timer_shutdown_sync(&dpcm->timer);
+ if (card->llmode_streampriv == dpcm) {
+ card->llmode_streampriv = NULL;
+ if (card->hpi->irq)
+ synchronize_irq(card->hpi->irq);
+ }
kfree(dpcm);
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:06:38 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
>
> `snd_card_asihpi_runtime_free()` frees the per-open `struct
> snd_card_asihpi_pcm` while a polled timer callback or an IRQ/threaded handler
> can still use it. The polled stop path uses `timer_delete()` (not
> `timer_delete_sync()`), and the IRQ stop path clears
> `card->llmode_streampriv` without `synchronize_irq()`. A normal PCM close can
> therefore free `dpcm` and then `runtime` while the callback is still running.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> was available; the harness validates the ALSA core close ordering and the
> exact `timer_delete`/`llmode_streampriv` lifetime pattern.
>
> * Mechanism
>
> `snd_card_asihpi_runtime_free()` (`asihpi.c:495-499`) does `kfree(dpcm)` and
> is installed as `runtime->private_free` at playback open
> (`asihpi.c:997-1000`) and capture open (`1166-1169`).
>
> Polled mode:
>
> snd_card_asihpi_pcm_timer_start() asihpi.c:501-513
> mod_timer(&dpcm->timer, jiffies + expiry);
> dpcm->respawn_timer = 1;
>
> snd_card_asihpi_pcm_timer_stop() asihpi.c:515-522
> dpcm->respawn_timer = 0;
> timer_delete(&dpcm->timer); /* no sync */
>
> `snd_card_asihpi_timer_function()` (`asihpi.c:710-896`) uses `dpcm`
> throughout and can re-arm at 894-895 if it observes `respawn_timer`.
>
> IRQ mode:
>
> snd_card_asihpi_pcm_int_start() asihpi.c:524-538
> card->llmode_streampriv = dpcm;
> ... set HPI IRQ rate ...
>
> snd_card_asihpi_pcm_int_stop() asihpi.c:540-550
> ... set HPI IRQ rate 0 ...
> card->llmode_streampriv = NULL; /* no synchronize_irq */
>
> `snd_card_asihpi_isr()` (`asihpi.c:898-907`) reads
> `asihpi->llmode_streampriv` twice (check, then dereference), so a threaded
> handler can hold the old `dpcm` pointer across the NULL store.
>
> Close path: `snd_pcm_release_substream()`
> (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()`
> (`pcm_native.c:2267-2289`) -> `snd_pcm_detach_substream()`
> (`sound/core/pcm.c:978-1005`) -> `runtime->private_free()` -> `kfree(dpcm)`
> and then `kfree(runtime)`.
>
>
> * Trigger model
>
> Local user opens a capture or playback PCM, starts it, and closes it while
> the polled timer or HPI IRQ is active. Polled mode is available on HPI6000
> and HPI6205; IRQ mode requires HPI6205 in interrupt mode. SMP/preemption
> needed for the cross-CPU window. Consequence: UAF of `dpcm`/`runtime` in
> timer softirq or threaded IRQ; crash or memory corruption.
>
> * Dynamic evidence
>
> `sndpci_race.c` mode `pcm`, `verification/kmod/
> sndpci/pcmtest.c close 200`: `.trigger STOP` uses `timer_delete()` and
> `runtime->private_free` frees `dpcm`; timer pinned to CPU0, user close to
> CPU1. Contain 35 KASAN UAF report fragments:
>
> BUG: KASAN: slab-use-after-free in race_pcm_timer
> ...
> Allocated by task: race_pcm_open
> Freed by task: kfree -> snd_pcm_detach_substream -> snd_pcm_release
>
>
>
> * Suggested direction
>
> In `snd_card_asihpi_runtime_free()` (or immediately before it), for polled
> mode call `timer_shutdown_sync(&dpcm->timer)`. For IRQ mode, first clear
> `card->llmode_streampriv` (with the appropriate ordering), then
> `synchronize_irq(card->hpi->irq)` before `kfree(dpcm)`. Do not put the
> sleeping sync inside the PCM stream lock; do it in the detach/private_free
> process context. Also consider quiescing before the HPI stream `.close`
> (the extra HPI stream handle window is discussed in the report).
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
2026-11-25 12:50 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:06 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:06 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] ALSA: asihpi: missing Signed-off-by trailer in commit message
- [High] ALSA: asihpi: unreachable synchronize_irq() in
snd_card_asihpi_runtime_free()
- [High] ALSA: asihpi: quiescing in snd_card_asihpi_runtime_free() runs
after hw_free()
--
commit 95d808dec25e736dfee562fd8a1a93b51e97b152
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
>
> snd_card_asihpi_runtime_free() kfree()d the per-open
> snd_card_asihpi_pcm while a polled timer callback or an
> IRQ/threaded handler could still use it: the polled stop path uses
> plain timer_delete() (no wait for a running callback), and the IRQ
> stop path clears card->llmode_streampriv with a plain store and no
> synchronize_irq().
>
> Quiesce in runtime->private_free, which runs in process context from
> snd_pcm_detach_substream() outside the PCM stream lock (so the
> sleeping sync calls are allowed there): timer_shutdown_sync() for
> the polled timer; for IRQ mode, clear card->llmode_streampriv and
> synchronize_irq(card->hpi->irq) before the kfree(dpcm).
[Severity: High]
This commit is missing a Signed-off-by: trailer.
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> index b78e96caef9d0..f528039651ab1 100644
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -495,6 +495,29 @@ snd_card_asihpi_hw_free(struct snd_pcm_substream *substream)
> static void snd_card_asihpi_runtime_free(struct snd_pcm_runtime *runtime)
> {
> struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
> + struct snd_card_asihpi *card = snd_pcm_substream_chip(dpcm->substream);
> +
> + /* Quiesce the polled timer and the low-latency IRQ stream before
> + * the memory goes away. This runs in process context from
> + * snd_pcm_detach_substream(), outside the PCM stream lock, so the
> + * sleeping sync calls are allowed here (they must NOT be put into
> + * the trigger/stop path under the stream lock).
> + *
> + * Polled mode: snd_card_asihpi_pcm_timer_stop() uses plain
> + * timer_delete(), which does not wait for a callback that is
> + * already running on another CPU -- the callback dereferences dpcm
> + * throughout and re-arms itself if it observes respawn_timer set.
> + *
> + * IRQ mode: card->llmode_streampriv is cleared with a plain store
> + * by snd_card_asihpi_pcm_int_stop(); the threaded handler may
> + * already have loaded the pointer, so synchronize the IRQ line
> + * after clearing before the kfree(). */
> + timer_shutdown_sync(&dpcm->timer);
[Severity: High]
Isn't quiescing in runtime->private_free too late to protect
runtime->dma_area and dpcm->h_stream during teardown?
In snd_pcm_release_substream() (or when userspace issues
SNDRV_PCM_IOCTL_HW_FREE without closing the device), do_hw_free() and
substream->ops->close() run before snd_pcm_detach_substream() invokes
snd_card_asihpi_runtime_free():
CPU0 CPU1
snd_pcm_release_substream()
snd_pcm_drop()
...
timer_delete(&dpcm->timer)
snd_card_asihpi_timer_function()
do_hw_free()
snd_card_asihpi_hw_free()
hpi_stream_host_buffer_detach()
snd_pcm_lib_free_pages()
runtime->dma_area = NULL
substream->ops->close()
hpi_outstream_close()
pd = &s->runtime->dma_area[buf_ofs];
hpi_outstream_write_buf(ds->h_stream, pd, ...)
<-- NULL deref / DMA buffer UAF
snd_pcm_detach_substream()
snd_card_asihpi_runtime_free()
timer_shutdown_sync(&dpcm->timer)
Both snd_pcm_drop() and do_hw_free() call snd_pcm_sync_stop() outside the
PCM stream lock before freeing pages or closing the stream, so quiescing
the timer and IRQ in a struct snd_pcm_ops .sync_stop callback would cover
both hw_free and close.
> + if (card->llmode_streampriv == dpcm) {
> + card->llmode_streampriv = NULL;
> + if (card->hpi->irq)
> + synchronize_irq(card->hpi->irq);
> + }
> kfree(dpcm);
> }
[Severity: High]
Can synchronize_irq() ever be reached here?
snd_pcm_release_substream() unconditionally calls snd_pcm_drop() before
snd_pcm_detach_substream(). For an active stream in IRQ mode,
snd_pcm_drop() triggers snd_card_asihpi_pcm_int_stop(), which sets
card->llmode_streampriv = NULL:
sound/pci/asihpi/asihpi.c:snd_card_asihpi_pcm_int_stop() {
...
hpi_handle_error(hpi_adapter_set_property(card->hpi->adapter->index,
HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
card->llmode_streampriv = NULL;
}
By the time snd_card_asihpi_runtime_free() runs, card->llmode_streampriv
is already NULL, so card->llmode_streampriv == dpcm is always false and
kfree(dpcm) can still race with an in-flight threaded IRQ handler running
snd_card_asihpi_isr() -> snd_card_asihpi_timer_function().
--
Sashiko AI review · https://sashiko.dev/#/patchset/8e25ddf.57f.1a212c231fe.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (3 preceding siblings ...)
2026-11-13 12:06 ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
@ 2026-11-13 12:15 ` 徐晗翔
2026-11-25 12:55 ` [PATCH] " 徐晗翔
2026-11-13 12:28 ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
` (8 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:15 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 4714 bytes --]
`snd_card_asihpi_timer_function()` walks the PCM link group with
`snd_pcm_group_for_each_entry()` and dereferences each member's
`s->runtime->private_data`. That macro is a plain `list_for_each_entry()`;
the callback holds no group reference and no group lock. Close of another
linked substream can unlink/free the group and detach/free that substream's
runtime and `dpcm`, leaving the timer callback with a stale `s`/runtime
pointer. This is reachable from user space through
`SNDRV_PCM_IOCTL_LINK` plus close, on hardware whose driver supports PCM
linking (asihpi does).
The detailed description:
* Test environment / affected version
Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
was available; the harness reproduces the core group traversal and close
ordering, with the asihpi callback's exact
`snd_pcm_group_for_each_entry()` pattern.
* Mechanism
The group loops are at `sound/pci/asihpi/asihpi.c:729-735` and `821-827`.
They read `s->runtime->private_data` (and in one path `dma_area`) and call
`snd_pcm_period_elapsed(s)`. The macro is
`include/sound/pcm.h:694`:
#define snd_pcm_group_for_each_entry(s, substream) \
list_for_each_entry(s, &substream->group->substreams, link_list)
`snd_pcm_stream_lock_irq()` (`sound/core/pcm_native.c:140-144`) locks
`substream->self_group`, not the group that the timer callback walks.
`snd_pcm_unlink()` (`pcm_native.c:2370-2402`) takes
`snd_pcm_link_rwsem` and the group lock, removes the closing substream,
relinks the remaining streams, and may `kfree(group)`.
`snd_pcm_release_substream()` (`pcm_native.c:2785-2805`) calls
`pcm_release_private()` -> `snd_pcm_unlink()` at 2779-2783 before
`snd_pcm_detach_substream()` frees the runtime and `dpcm`.
A timer callback that already loaded member `s` or `s->runtime` can run
after B's unlink/detach. It may then read freed `runtime`, freed
`private_data`, or a freed group list node; `snd_pcm_period_elapsed(s)`
additionally takes the stale substream.
* Why existing synchronization does not close the window
`snd_pcm_stop()` does transiently take a group reference through
`snd_pcm_action()` -> `snd_pcm_stream_group_ref()` (`pcm_native.c:1378-1427`)
and group lock, but it drops the reference after the STOP action. The
asihpi timer callback is not part of that action and holds no group
reference. Taking `snd_pcm_stream_lock_irq(A)` in the callback would only
lock A's `self_group`; it would not pin B or the group. The group can be
freed while the callback holds a raw member pointer.
* Trigger model
Two capture substreams A and B, same PCM and runtime state; user does
`SNDRV_PCM_IOCTL_LINK` then starts A. While A's timer callback is walking
the group, user closes B. `SNDRV_PCM_IOCTL_LINK` is available to a local
user with the PCM device open; no special privilege is needed beyond access
to the PCM. Consequence: UAF in timer context, crash or memory corruption.
* How to run the PoC
The harness is self-contained and does not need ASI6205 hardware: it creates
a fake ALSA card with two capture substreams. The tested configuration was
7.3.0 with KASAN and 4 vCPU; a uniprocessor run may not overlap.
Build against the target kernel build tree:
printf 'obj-m := sndpci_race.o\n' > Kbuild
make -C <kernel-build-dir> M=$PWD modules
gcc -static -O2 -I<kernel-source>/include/uapi -o pcmtest pcmtest.c
Put `sndpci_race.ko` and `pcmtest` into the guest initramfs/rootfs, boot the
target kernel (QEMU/KVM recommended), then run as root:
insmod sndpci_race.ko mode=pcm
./pcmtest link 200
dmesg | grep -E 'BUG: KASAN|race_pcm_timer|victim use'
In the minimal guest the fake card enumerates as card 0 and `pcmtest` opens
`/dev/snd/pcmC0D0c`. If the test machine already has another sound card,
adjust `DEV` in `pcmtest.c` or use the QEMU initramfs. Expected result:
32 KASAN reports with `slab-use-after-free in race_pcm_timer` and about 114
`victim use` lines.
* Suggested direction
This needs a core/lifetime fix, not just an asihpi timer fix. Possible
directions: make group traversal safe against concurrent unlink (group
reference or RCU-protected/atomic-safe iterator that pins each member's
runtime), or provide a driver API that snapshots/refcounts members before
the callback walks them. On the asihpi side, quiesce the timer/IRQ before
allowing the linked substream to detach. Adding only
`snd_pcm_stream_lock_irq(A)` is not sufficient because it locks A's
`self_group`, not the group being walked.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndpci_race.c --]
[-- Type: text/plain, Size: 9729 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sndpci_race.c - minimal ALSA/kernel lifetime-race reproducers for the
* sound/pci manual-review cases V3/V4/V5.
*
* The module deliberately reproduces the *lifetime patterns* used by
* ctxfi/asihpi, using only exported ALSA core and timer APIs. It is not a
* ctxfi/asihpi emulator: those drivers need hardware that this QEMU does not
* provide. The purpose is to test whether the core/API windows identified in
* the report are real on an instrumented KASAN kernel.
*
* modes:
* v3 - timer_delete_sync_try() returns -1 while the callback runs on
* another CPU; free the object anyway (ctxfi system-timer pattern).
* pcm - create a fake ALSA card with two playback substreams. The guest
* program pcmtest then exercises close (V4) or link+close (V5).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/cpumask.h>
#include <linux/sched.h>
#include <linux/container_of.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndpci_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "v3 or pcm");
/* ------------------------------------------------------------------ */
/* V3: timer_delete_sync_try() ignored -1 */
/* ------------------------------------------------------------------ */
struct v3_obj {
struct timer_list timer;
u64 cookie;
struct task_struct *thread;
};
static void v3_callback(struct timer_list *t)
{
struct v3_obj *v = container_of(t, struct v3_obj, timer);
/* Keep the callback alive long enough for the freeing CPU to run. */
mdelay(20);
pr_info(DRV ": v3 callback cookie=%#llx\n", v->cookie);
/* Second read after the delay: the object may already be freed. */
if (v->cookie == COOKIE)
pr_info(DRV ": v3 callback read-after-free survived\n");
}
static int v3_thread(void *arg)
{
struct v3_obj *v;
int i, ret;
for (i = 0; i < 8; i++) {
v = kzalloc(sizeof(*v), GFP_KERNEL);
if (!v)
return -ENOMEM;
v->cookie = COOKIE;
timer_setup(&v->timer, v3_callback, 0);
/* Pin the callback to CPU0; this thread runs on CPU1. */
add_timer_on(&v->timer, 0);
usleep_range(2000, 3000);
ret = timer_delete_sync_try(&v->timer);
pr_info(DRV ": v3 iter=%d delete_sync_try=%d\n", i, ret);
if (ret == -1) {
/* BUG: callback is running on CPU0; free it anyway. */
if (safe)
timer_delete_sync(&v->timer);
kfree(v);
} else {
timer_delete_sync(&v->timer);
kfree(v);
}
usleep_range(60000, 70000);
}
pr_info(DRV ": v3 done\n");
return 0;
}
/* ------------------------------------------------------------------ */
/* V4/V5: fake ALSA PCM with a driver-private dpcm and a timer */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct timer_list timer;
struct snd_pcm_substream *substream;
u64 cookie;
bool respawn;
bool active;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_timer(struct timer_list *t)
{
struct race_pcm *dpcm = container_of(t, struct race_pcm, timer);
struct snd_pcm_substream *s;
struct snd_pcm_runtime *victim_rt = NULL;
u64 cookie;
if (!dpcm->active)
return;
pr_info(DRV ": timer start dpcm=%px\n", dpcm);
/*
* V5 pattern: walk the link group without the group lock and read
* each member's runtime/private_data. V4 uses the same callback for
* the current stream; the delay widens the close/free window.
*/
cookie = dpcm->cookie;
if (cookie == COOKIE && dpcm->substream && dpcm->substream->runtime) {
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_pcm_runtime *rt = READ_ONCE(s->runtime);
struct race_pcm *d = NULL;
if (rt)
d = READ_ONCE(rt->private_data);
if (d && d->cookie == COOKIE) {
/* Force the compiler to keep the load. */
barrier();
}
if (rt) {
(void)READ_ONCE(rt->dma_area);
if (s != dpcm->substream && !victim_rt)
victim_rt = rt;
}
/* A real driver also reports elapsed periods. */
if (rt)
snd_pcm_period_elapsed(s);
}
}
/* Widen the window between the callback's load and the free. */
mdelay(20);
if (victim_rt) {
struct race_pcm *d = READ_ONCE(victim_rt->private_data);
pr_info(DRV ": victim use rt=%px d=%px\n", victim_rt, d);
(void)READ_ONCE(victim_rt->dma_area);
}
pr_info(DRV ": timer end dpcm=%px\n", dpcm);
if (dpcm->respawn) {
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
}
}
static void race_pcm_free(struct snd_pcm_runtime *runtime)
{
struct race_pcm *dpcm = runtime->private_data;
pr_info(DRV ": pcm private_free dpcm=%px\n", dpcm);
if (safe)
timer_shutdown_sync(&dpcm->timer);
kfree(dpcm);
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
dpcm->substream = substream;
dpcm->cookie = COOKIE;
timer_setup(&dpcm->timer, race_pcm_timer, 0);
runtime->private_data = dpcm;
runtime->private_free = race_pcm_free;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": pcm open sub=%px dpcm=%px\n", substream, dpcm);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
pr_info(DRV ": pcm .close sub=%px\n", substream);
return 0;
}
static int race_pcm_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
pr_info(DRV ": pcm ioctl cmd=%u\n", cmd);
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_info(DRV ": hw_params rate=%u ch=%u fmt=%u period_bytes=%u buffer_bytes=%u\n",
params_rate(params), params_channels(params), params_format(params),
params_period_bytes(params), params_buffer_bytes(params));
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct race_pcm *dpcm = substream->runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream != race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
break;
dpcm->active = true;
dpcm->respawn = true;
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dpcm->active = false;
dpcm->respawn = false;
/* Deliberately not timer_delete_sync(): mirrors asihpi. */
timer_delete(&dpcm->timer);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.ioctl = race_pcm_ioctl,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int __init sndpci_init(void)
{
struct task_struct *t;
int ret;
pr_info(DRV ": init mode=%s\n", mode);
if (!strcmp(mode, "v3")) {
t = kthread_create(v3_thread, NULL, "sndpci_v3");
if (IS_ERR(t))
return PTR_ERR(t);
kthread_bind(t, 1);
wake_up_process(t);
return 0;
}
race_pdev = platform_device_register_simple("sndpci_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndPciRace", THIS_MODULE, 0, &race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndPciRace", 0, 0, 2, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE,
&race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev, SNDRV_DMA_TYPE_CONTINUOUS,
NULL, 64 * 1024, 64 * 1024);
ret = 0;
pr_info(DRV ": managed_buffer ret=%d dma_type=%d area=%px bytes=%zu\n", ret,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.dev.type,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.area,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.bytes);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered\n");
return 0;
}
static void __exit sndpci_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndpci_init);
module_exit(sndpci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/pci lifetime-race reproducer (V3/V4/V5)");
[-- Attachment #3: pcmtest.c --]
[-- Type: text/plain, Size: 3737 bytes --]
#define _GNU_SOURCE
// SPDX-License-Identifier: GPL-2.0
/*
* pcmtest.c - guest-side exerciser for sndpci_race.ko.
*
* Usage:
* pcmtest close [iters] - open/start/close one playback substream (V4)
* pcmtest link [iters] - link two playback substreams, close B while
* the A timer callback walks the group (V5)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <sched.h>
#include <sound/asound.h>
#define DEV "/dev/snd/pcmC0D0c"
static int set_hw_params(int fd)
{
struct snd_pcm_hw_params p;
int i, ret;
memset(&p, 0, sizeof(p));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_MASK -
SNDRV_PCM_HW_PARAM_FIRST_MASK; i++)
memset(&p.masks[i], 0xff, sizeof(p.masks[i]));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL -
SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; i++) {
p.intervals[i].min = 0;
p.intervals[i].max = UINT_MAX;
p.intervals[i].integer = 0;
}
p.rmask = ~0U;
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, &p);
printf("HW_REFINE ret=%d errno=%d\n", ret, errno);
if (ret < 0)
return -1;
printf("refined: rate=%u ch=%u fmt=%u ps=%u periods=%u bs=%u\n",
p.intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
__builtin_ctz(p.masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0]),
p.intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_PERIODS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min);
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, &p);
if (ret < 0) {
fprintf(stderr, "HW_PARAMS: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int open_stream(void)
{
int fd = open(DEV, O_RDWR | O_NONBLOCK);
if (fd < 0)
fprintf(stderr, "open %s: %s\n", DEV, strerror(errno));
return fd;
}
static int prepare_stream(int fd)
{
if (set_hw_params(fd) < 0)
return -1;
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE, 0) < 0) {
fprintf(stderr, "PREPARE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int start_stream(int fd)
{
if (ioctl(fd, SNDRV_PCM_IOCTL_START, 0) < 0) {
fprintf(stderr, "START: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int one_close(void)
{
int fd = open_stream();
if (fd < 0)
return -1;
if (prepare_stream(fd) < 0 || start_stream(fd) < 0) {
close(fd);
return -1;
}
usleep(10000);
close(fd);
return 0;
}
static int one_link(void)
{
int a = open_stream();
int b = open_stream();
if (a < 0 || b < 0)
return -1;
if (prepare_stream(a) < 0 || prepare_stream(b) < 0)
goto out;
if (ioctl(a, SNDRV_PCM_IOCTL_LINK, b) < 0) {
fprintf(stderr, "LINK: %s\n", strerror(errno));
goto out;
}
if (start_stream(a) < 0)
goto out;
/* Let the A timer callback start walking the linked group. */
usleep(1500);
/* Close B while A's callback may be in the group loop. */
close(b);
b = -1;
usleep(1500);
out:
if (b >= 0)
close(b);
if (a >= 0)
close(a);
return 0;
}
int main(int argc, char **argv)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(1, &set);
sched_setaffinity(0, sizeof(set), &set);
int i, n = 200;
if (argc < 2) {
fprintf(stderr, "usage: %s close|link [iters]\n", argv[0]);
return 2;
}
if (argc > 2)
n = atoi(argv[2]);
printf("pcmtest: mode=%s iters=%d\n", argv[1], n);
for (i = 0; i < n; i++) {
if (!strcmp(argv[1], "link")) {
if (one_link() < 0)
break;
} else {
if (one_close() < 0)
break;
}
}
printf("pcmtest: done i=%d\n", i);
return 0;
}
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
2026-11-13 12:15 ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
@ 2026-11-25 12:55 ` 徐晗翔
2026-11-25 13:12 ` sashiko-bot
2026-11-25 13:27 ` Takashi Iwai
0 siblings, 2 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:55 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_pcm_group_for_each_entry() is a plain list_for_each_entry() over
substream->group->substreams. A driver timer callback (asihpi's
snd_card_asihpi_timer_function()) walked that list from softirq with
no group reference and no link rwsem, while the close of another
linked substream could unlink the members, reassign the survivors
and kfree() the group object -- the callback kept dereferencing a
stale s/runtime pointer and freed group memory (KASAN UAF).
Core: free the group object only after an RCU grace period (new
rcu_head in struct snd_pcm_group, kfree_rcu() at both free sites),
so a group pointer read without the link rwsem stays memory-safe
while a concurrent unlink tears the group down.
Driver: walk the group one member at a time under the group lock
with rcu_read_lock() held -- the lock makes membership (and each
member's runtime) stable while the member is processed, and RCU
keeps the group object alive. snd_pcm_stop_xrun()/
snd_pcm_period_elapsed() are deferred out of the locked section:
they enter snd_pcm_action(), which re-takes the group lock. A
substream object outlives its fd's close and both helpers recheck
substream->runtime under the stream lock, so the deferred calls are
safe against a concurrent close of the member.
---
sound/core/pcm_native.c | 12 ++++++++++--
include/sound/pcm.h | 6 ++++++
sound/pci/asihpi/asihpi.c | 144 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
3 files changed, 145 insertions(+), 17 deletions(-)
diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c
--- a/sound/core/pcm_native.c
+++ b/sound/core/pcm_native.c
@@ -1368,7 +1368,11 @@
do_free = refcount_dec_and_test(&group->refs);
snd_pcm_group_unlock(group, substream->pcm->nonatomic);
if (do_free)
- kfree(group);
+ /* free only after an RCU grace period: a driver timer
+ * callback (softirq context) may hold group->lock under
+ * rcu_read_lock() without the link rwsem and must not
+ * touch freed group memory */
+ kfree_rcu(group, rcu_head);
}
/*
@@ -2401,7 +2405,11 @@
snd_pcm_group_unlock_irq(group, nonatomic);
if (do_free)
- kfree(group);
+ /* free only after an RCU grace period: a driver timer
+ * callback (softirq context) may hold group->lock under
+ * rcu_read_lock() without the link rwsem and must not
+ * touch freed group memory */
+ kfree_rcu(group, rcu_head);
return 0;
}
diff --git a/include/sound/pcm.h b/include/sound/pcm.h
--- a/include/sound/pcm.h
+++ b/include/sound/pcm.h
@@ -16,6 +16,7 @@
#include <linux/bitops.h>
#include <linux/pm_qos.h>
#include <linux/refcount.h>
+#include <linux/rcupdate.h>
#include <linux/uio.h>
#define snd_pcm_substream_chip(substream) ((substream)->private_data)
@@ -455,6 +456,11 @@
struct mutex mutex;
struct list_head substreams;
refcount_t refs;
+ /* a group object is freed only after an RCU grace period, so a
+ * lockless/atomic group walker (e.g. a driver timer callback that
+ * takes group->lock under rcu_read_lock()) cannot touch freed
+ * group memory while a concurrent unlink tears the group down */
+ struct rcu_head rcu_head;
};
struct pid;
diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
--- a/sound/pci/asihpi/asihpi.c
+++ b/sound/pci/asihpi/asihpi.c
@@ -136,6 +136,8 @@
unsigned int pcm_buf_dma_ofs; /* DMA R/W offset in buffer */
unsigned int pcm_buf_elapsed_dma_ofs; /* DMA R/W offset in buffer */
unsigned int drained_count;
+ bool timer_walked; /* one-shot mark for the timer
+ * callback's group walk */
struct snd_pcm_substream *substream;
u32 h_stream;
struct hpi_format format;
@@ -705,6 +707,31 @@
return result;
}
+/* Pick the next group member this timer callback has not processed yet.
+ * Must be called with the group lock held and under rcu_read_lock(): the
+ * group list cannot change under us, so every member's runtime is still
+ * alive. */
+static struct snd_pcm_substream *
+asihpi_timer_next_member(struct snd_pcm_substream *substream,
+ struct snd_card_asihpi *card)
+{
+ struct snd_pcm_substream *s;
+
+ snd_pcm_group_for_each_entry(s, substream) {
+ struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
+
+ if (snd_pcm_substream_chip(s) != card)
+ continue;
+ /* don't link Cap and Play */
+ if (substream->stream != s->stream)
+ continue;
+ if (ds->timer_walked)
+ continue;
+ return s;
+ }
+ return NULL;
+}
+
/** Timer function, equivalent to interrupt service routine for cards
*/
static void snd_card_asihpi_timer_function(struct timer_list *t)
@@ -713,10 +740,12 @@
struct snd_pcm_substream *substream = dpcm->substream;
struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime;
+ struct snd_pcm_group *group;
struct snd_pcm_substream *s;
unsigned int newdata = 0;
unsigned int pcm_buf_dma_ofs, min_buf_pos = 0;
unsigned int remdata, xfercount, next_jiffies;
+ unsigned long flags;
int first = 1;
u16 state;
u32 buffer_size, bytes_avail, samples_played, on_card_bytes;
@@ -725,17 +754,58 @@
snd_pcm_debug_name(substream, name, sizeof(name));
- /* find minimum newdata and buffer pos in group */
+ /*
+ * Walk the PCM link group one member at a time, under the group
+ * lock and an RCU read lock. This callback runs from a timer
+ * (softirq) with no group reference and no link rwsem, so a close
+ * of another linked substream could previously unlink the members,
+ * free the group object and free that member's runtime while this
+ * walk was holding a stale s/runtime pointer.
+ *
+ * The group lock keeps the membership (and each member's runtime)
+ * stable while the member is processed; the RCU read lock keeps
+ * the group object itself alive (snd_pcm_unlink() frees it only
+ * after a grace period). snd_pcm_stop_xrun() and
+ * snd_pcm_period_elapsed() must run WITHOUT the group lock -- they
+ * enter snd_pcm_action(), which re-takes the group lock -- so they
+ * are deferred to after the unlocked section. A substream object
+ * outlives the close of its fd, and both helpers recheck
+ * substream->runtime under the stream lock.
+ */
+
+ /* clear the one-shot walk marks of the previous invocation */
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
snd_pcm_group_for_each_entry(s, substream) {
- struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
- runtime = s->runtime;
+ if (snd_pcm_substream_chip(s) == card) {
+ struct snd_card_asihpi_pcm *ds =
+ s->runtime->private_data;
- if (snd_pcm_substream_chip(s) != card)
- continue;
+ ds->timer_walked = false;
+ }
+ }
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
- /* don't link Cap and Play */
- if (substream->stream != s->stream)
- continue;
+ /* find minimum newdata and buffer pos in group */
+ for (;;) {
+ struct snd_card_asihpi_pcm *ds;
+ struct snd_pcm_substream *xrun = NULL;
+
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
+
+ s = asihpi_timer_next_member(substream, card);
+ if (!s) {
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+ break;
+ }
+ ds = s->runtime->private_data;
+ runtime = s->runtime;
+ ds->timer_walked = true;
hpi_handle_error(hpi_stream_get_info_ex(
ds->h_stream, &state,
@@ -762,8 +832,9 @@
"P%d drained\n", s->number);
ds->drained_count++;
if (ds->drained_count > 20) {
- snd_pcm_stop_xrun(s);
- continue;
+ /* defer to after the unlock */
+ xrun = s;
+ goto member_done;
}
} else {
ds->drained_count = 0;
@@ -799,6 +870,13 @@
(unsigned long)frames_to_bytes(runtime,
runtime->control->appl_ptr)
);
+
+member_done:
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+
+ if (xrun)
+ snd_pcm_stop_xrun(xrun);
}
pcm_buf_dma_ofs = min_buf_pos;
@@ -818,12 +896,41 @@
asihpi_dbg("timer2, jif=%d, buf_pos=%d, newdata=%d, xfer=%d\n",
next_jiffies, pcm_buf_dma_ofs, newdata, xfercount);
+ /* clear the one-shot walk marks again for the second pass */
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
snd_pcm_group_for_each_entry(s, substream) {
- struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
+ if (snd_pcm_substream_chip(s) == card) {
+ struct snd_card_asihpi_pcm *ds =
+ s->runtime->private_data;
- /* don't link Cap and Play */
- if (substream->stream != s->stream)
- continue;
+ ds->timer_walked = false;
+ }
+ }
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+
+ /* second pass, again one member at a time under the group lock
+ * (see above); snd_pcm_period_elapsed() is deferred to after the
+ * unlock for the same reason as snd_pcm_stop_xrun() */
+ for (;;) {
+ struct snd_card_asihpi_pcm *ds;
+ struct snd_pcm_substream *elapsed = NULL;
+
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
+
+ s = asihpi_timer_next_member(substream, card);
+ if (!s) {
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+ break;
+ }
+ ds = s->runtime->private_data;
+ runtime = s->runtime;
+ ds->timer_walked = true;
/* Store dma offset for use by pointer callback */
ds->pcm_buf_dma_ofs = pcm_buf_dma_ofs;
@@ -887,8 +994,15 @@
/* ? host_rw_ofs always ahead of elapsed_dma_ofs by preload size? */
ds->pcm_buf_host_rw_ofs += xfercount;
ds->pcm_buf_elapsed_dma_ofs += xfercount;
- snd_pcm_period_elapsed(s);
+ /* defer to after the unlock */
+ elapsed = s;
}
+
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+
+ if (elapsed)
+ snd_pcm_period_elapsed(elapsed);
}
if (!card->hpi->interrupt_mode && dpcm->respawn_timer)
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:15:08 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
>
> `snd_card_asihpi_timer_function()` walks the PCM link group with
> `snd_pcm_group_for_each_entry()` and dereferences each member's
> `s->runtime->private_data`. That macro is a plain `list_for_each_entry()`;
> the callback holds no group reference and no group lock. Close of another
> linked substream can unlink/free the group and detach/free that substream's
> runtime and `dpcm`, leaving the timer callback with a stale `s`/runtime
> pointer. This is reachable from user space through
> `SNDRV_PCM_IOCTL_LINK` plus close, on hardware whose driver supports PCM
> linking (asihpi does).
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> was available; the harness reproduces the core group traversal and close
> ordering, with the asihpi callback's exact
> `snd_pcm_group_for_each_entry()` pattern.
>
> * Mechanism
>
> The group loops are at `sound/pci/asihpi/asihpi.c:729-735` and `821-827`.
> They read `s->runtime->private_data` (and in one path `dma_area`) and call
> `snd_pcm_period_elapsed(s)`. The macro is
> `include/sound/pcm.h:694`:
>
> #define snd_pcm_group_for_each_entry(s, substream) \
> list_for_each_entry(s, &substream->group->substreams, link_list)
>
> `snd_pcm_stream_lock_irq()` (`sound/core/pcm_native.c:140-144`) locks
> `substream->self_group`, not the group that the timer callback walks.
> `snd_pcm_unlink()` (`pcm_native.c:2370-2402`) takes
> `snd_pcm_link_rwsem` and the group lock, removes the closing substream,
> relinks the remaining streams, and may `kfree(group)`.
> `snd_pcm_release_substream()` (`pcm_native.c:2785-2805`) calls
> `pcm_release_private()` -> `snd_pcm_unlink()` at 2779-2783 before
> `snd_pcm_detach_substream()` frees the runtime and `dpcm`.
>
> A timer callback that already loaded member `s` or `s->runtime` can run
> after B's unlink/detach. It may then read freed `runtime`, freed
> `private_data`, or a freed group list node; `snd_pcm_period_elapsed(s)`
> additionally takes the stale substream.
>
> * Why existing synchronization does not close the window
>
> `snd_pcm_stop()` does transiently take a group reference through
> `snd_pcm_action()` -> `snd_pcm_stream_group_ref()` (`pcm_native.c:1378-1427`)
> and group lock, but it drops the reference after the STOP action. The
> asihpi timer callback is not part of that action and holds no group
> reference. Taking `snd_pcm_stream_lock_irq(A)` in the callback would only
> lock A's `self_group`; it would not pin B or the group. The group can be
> freed while the callback holds a raw member pointer.
>
> * Trigger model
>
> Two capture substreams A and B, same PCM and runtime state; user does
> `SNDRV_PCM_IOCTL_LINK` then starts A. While A's timer callback is walking
> the group, user closes B. `SNDRV_PCM_IOCTL_LINK` is available to a local
> user with the PCM device open; no special privilege is needed beyond access
> to the PCM. Consequence: UAF in timer context, crash or memory corruption.
>
>
> * How to run the PoC
>
> The harness is self-contained and does not need ASI6205 hardware: it creates
> a fake ALSA card with two capture substreams. The tested configuration was
> 7.3.0 with KASAN and 4 vCPU; a uniprocessor run may not overlap.
>
> Build against the target kernel build tree:
>
> printf 'obj-m := sndpci_race.o\n' > Kbuild
> make -C <kernel-build-dir> M=$PWD modules
> gcc -static -O2 -I<kernel-source>/include/uapi -o pcmtest pcmtest.c
>
> Put `sndpci_race.ko` and `pcmtest` into the guest initramfs/rootfs, boot the
> target kernel (QEMU/KVM recommended), then run as root:
>
> insmod sndpci_race.ko mode=pcm
> ./pcmtest link 200
> dmesg | grep -E 'BUG: KASAN|race_pcm_timer|victim use'
>
> In the minimal guest the fake card enumerates as card 0 and `pcmtest` opens
> `/dev/snd/pcmC0D0c`. If the test machine already has another sound card,
> adjust `DEV` in `pcmtest.c` or use the QEMU initramfs. Expected result:
> 32 KASAN reports with `slab-use-after-free in race_pcm_timer` and about 114
> `victim use` lines.
>
>
> * Suggested direction
>
> This needs a core/lifetime fix, not just an asihpi timer fix. Possible
> directions: make group traversal safe against concurrent unlink (group
> reference or RCU-protected/atomic-safe iterator that pins each member's
> runtime), or provide a driver API that snapshots/refcounts members before
> the callback walks them. On the asihpi side, quiesce the timer/IRQ before
> allowing the linked substream to detach. Adding only
> `snd_pcm_stream_lock_irq(A)` is not sufficient because it locks A's
> `self_group`, not the group being walked.
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
2026-11-25 12:55 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:12 ` sashiko-bot
2026-11-25 13:27 ` Takashi Iwai
1 sibling, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:12 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [Critical] ALSA: asihpi: unlocked group list walk in
snd_card_asihpi_timer_function()
- [Critical] ALSA: asihpi: deferred elapsed/xrun calls race with
snd_pcm_detach_substream()
- [Critical] ALSA: asihpi: unsynchronized timer stop and missing runtime
checks on close
- [High] ALSA: asihpi: shared timer_walked race in
snd_card_asihpi_timer_function()
- [High] ALSA: asihpi: spin_lock_irqsave held across DSP polling and
MMIO transfers
- [High] ALSA: pcm: missing Signed-off-by trailer in commit message
- [Low] ALSA: pcm: missing Fixes trailer in commit message
--
commit 7d06715d1a9473c30893b41b4784ed5585d479ae
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
>
> snd_pcm_group_for_each_entry() is a plain list_for_each_entry() over
> substream->group->substreams. A driver timer callback (asihpi's
> snd_card_asihpi_timer_function()) walked that list from softirq with
> no group reference and no link rwsem, while the close of another
> linked substream could unlink the members, reassign the survivors
> and kfree() the group object -- the callback kept dereferencing a
> stale s/runtime pointer and freed group memory (KASAN UAF).
>
> Core: free the group object only after an RCU grace period (new
> rcu_head in struct snd_pcm_group, kfree_rcu() at both free sites),
> so a group pointer read without the link rwsem stays memory-safe
> while a concurrent unlink tears the group down.
>
> Driver: walk the group one member at a time under the group lock
> with rcu_read_lock() held -- the lock makes membership (and each
> member's runtime) stable while the member is processed, and RCU
> keeps the group object alive. snd_pcm_stop_xrun()/
> snd_pcm_period_elapsed() are deferred out of the locked section:
> they enter snd_pcm_action(), which re-takes the group lock. A
> substream object outlives its fd's close and both helpers recheck
> substream->runtime under the stream lock, so the deferred calls are
> safe against a concurrent close of the member.
[Severity: High]
The commit message is missing a Signed-off-by: trailer.
[Severity: Low]
Since this fixes a bug in the asihpi timer callback, should it include a
Fixes: tag?
Fixes: 719f82d3987a ("ALSA: Add support of AudioScience ASI boards")
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> index b78e96caef9d0..768f2969004fb 100644
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -136,6 +136,8 @@ struct snd_card_asihpi_pcm {
> unsigned int pcm_buf_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int pcm_buf_elapsed_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int drained_count;
> + bool timer_walked; /* one-shot mark for the timer
> + * callback's group walk */
> struct snd_pcm_substream *substream;
> u32 h_stream;
> struct hpi_format format;
> @@ -705,6 +707,31 @@ static inline unsigned int modulo_min(unsigned int a, unsigned int b,
> return result;
> }
>
> +/* Pick the next group member this timer callback has not processed yet.
> + * Must be called with the group lock held and under rcu_read_lock(): the
> + * group list cannot change under us, so every member's runtime is still
> + * alive. */
> +static struct snd_pcm_substream *
> +asihpi_timer_next_member(struct snd_pcm_substream *substream,
> + struct snd_card_asihpi *card)
> +{
> + struct snd_pcm_substream *s;
> +
> + snd_pcm_group_for_each_entry(s, substream) {
> + struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> +
> + if (snd_pcm_substream_chip(s) != card)
> + continue;
> + /* don't link Cap and Play */
> + if (substream->stream != s->stream)
> + continue;
> + if (ds->timer_walked)
> + continue;
> + return s;
> + }
> + return NULL;
> +}
> +
> /** Timer function, equivalent to interrupt service routine for cards
> */
> static void snd_card_asihpi_timer_function(struct timer_list *t)
> @@ -713,10 +740,12 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
> struct snd_pcm_substream *substream = dpcm->substream;
> struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
> struct snd_pcm_runtime *runtime;
> + struct snd_pcm_group *group;
> struct snd_pcm_substream *s;
> unsigned int newdata = 0;
> unsigned int pcm_buf_dma_ofs, min_buf_pos = 0;
> unsigned int remdata, xfercount, next_jiffies;
> + unsigned long flags;
> int first = 1;
> u16 state;
> u32 buffer_size, bytes_avail, samples_played, on_card_bytes;
> @@ -725,17 +754,58 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
>
> snd_pcm_debug_name(substream, name, sizeof(name));
>
> - /* find minimum newdata and buffer pos in group */
> + /*
> + * Walk the PCM link group one member at a time, under the group
> + * lock and an RCU read lock. This callback runs from a timer
> + * (softirq) with no group reference and no link rwsem, so a close
> + * of another linked substream could previously unlink the members,
> + * free the group object and free that member's runtime while this
> + * walk was holding a stale s/runtime pointer.
> + *
> + * The group lock keeps the membership (and each member's runtime)
> + * stable while the member is processed; the RCU read lock keeps
> + * the group object itself alive (snd_pcm_unlink() frees it only
> + * after a grace period). snd_pcm_stop_xrun() and
> + * snd_pcm_period_elapsed() must run WITHOUT the group lock -- they
> + * enter snd_pcm_action(), which re-takes the group lock -- so they
> + * are deferred to after the unlocked section. A substream object
> + * outlives the close of its fd, and both helpers recheck
> + * substream->runtime under the stream lock.
> + */
> +
> + /* clear the one-shot walk marks of the previous invocation */
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> snd_pcm_group_for_each_entry(s, substream) {
> - struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> - runtime = s->runtime;
> + if (snd_pcm_substream_chip(s) == card) {
> + struct snd_card_asihpi_pcm *ds =
> + s->runtime->private_data;
>
> - if (snd_pcm_substream_chip(s) != card)
> - continue;
> + ds->timer_walked = false;
> + }
> + }
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
>
> - /* don't link Cap and Play */
> - if (substream->stream != s->stream)
> - continue;
> + /* find minimum newdata and buffer pos in group */
> + for (;;) {
> + struct snd_card_asihpi_pcm *ds;
> + struct snd_pcm_substream *xrun = NULL;
> +
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> +
> + s = asihpi_timer_next_member(substream, card);
> + if (!s) {
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> + break;
> + }
> + ds = s->runtime->private_data;
> + runtime = s->runtime;
> + ds->timer_walked = true;
[Severity: Critical]
Can snd_card_asihpi_timer_function() lock a stale group and then walk
substream->group->substreams without holding the current group's lock?
All four lock sites read group = READ_ONCE(substream->group) and acquire
group->lock without rechecking that substream->group == group (the way
snd_pcm_stream_group_ref() does), while snd_pcm_group_for_each_entry()
expands to list_for_each_entry(s, &substream->group->substreams, link_list)
and re-reads substream->group:
CPU0 (<softirq>) CPU1
snd_card_asihpi_timer_function()
group = READ_ONCE(substream->group)
/* group == G1 */
snd_pcm_unlink(peer)
spin_lock_irq(&G1->lock)
relink_to_local(substream)
substream->group = &substream->self_group
spin_unlock_irq(&G1->lock)
snd_pcm_link(other, substream)
/* moves substream to G2 */
spin_lock_irqsave(&G1->lock, ...)
asihpi_timer_next_member()
snd_pcm_group_for_each_entry()
/* walks G2->substreams under G1->lock */
close(member_in_G2)
snd_pcm_unlink(member_in_G2)
snd_pcm_detach_substream(member_in_G2)
kfree(runtime)
s->runtime->private_data <-- use-after-free
In addition, snd_pcm_link() calls snd_pcm_group_assign(substream, group)
under substream->self_group.lock before acquiring target_group->lock, so
reading substream->group without substream->self_group.lock can also observe
the new group while snd_pcm_group_assign() is still mutating its substreams
list. If substream->group changes mid-loop, the list_entry_is_head() check
in snd_pcm_group_for_each_entry() also compares against the new list head
and walks past the old list head.
[Severity: High]
Can two timers running in the same link group corrupt each other's walk
state through ds->timer_walked and use on_card_bytes uninitialized?
Multiple members of the same group can have active timers at once: for
instance, when a playback and a capture substream on the same card are
linked (snd_card_asihpi_trigger() starts a timer per direction, whereas the
two mark-clearing loops clear ds->timer_walked for all group members on the
card regardless of stream direction), or when two already-running streams
are linked via SNDRV_PCM_IOCTL_LINK. Because group->lock is dropped after
clearing ds->timer_walked and after each member:
CPU0 (timer A) CPU1 (timer B)
snd_card_asihpi_timer_function()
/* clear timer_walked = false */
spin_unlock_irqrestore(&group->lock)
snd_card_asihpi_timer_function()
/* Pass 1 marks all members
* ds->timer_walked = true */
spin_lock_irqsave(&group->lock)
asihpi_timer_next_member()
/* returns NULL on 1st iter */
break;
if (xfercount &&
on_card_bytes > ...) <-- uninitialized on_card_bytes
When Pass 1 exits on its first iteration like this, on_card_bytes has never
been written by hpi_stream_get_info_ex() and Pass 2 overwrites each member's
ds->pcm_buf_dma_ofs with min_buf_pos (0). Conversely, if timer B runs its
mark-clearing loop while timer A is partway through Pass 2, timer A visits
already-processed members a second time, performing duplicate
hpi_outstream_write_buf() / hpi_instream_read_buf() transfers and advancing
pcm_buf_host_rw_ofs and pcm_buf_elapsed_dma_ofs twice in one pass. Also,
because Pass 2 leaves ds->timer_walked set to true, a stream linked into the
group after the first mark-clearing loop is skipped in Pass 1.
[ ... ]
> @@ -799,6 +870,13 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
> (unsigned long)frames_to_bytes(runtime,
> runtime->control->appl_ptr)
> );
> +
> +member_done:
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (xrun)
> + snd_pcm_stop_xrun(xrun);
> }
> pcm_buf_dma_ofs = min_buf_pos;
[ ... ]
> @@ -887,8 +994,15 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
> /* ? host_rw_ofs always ahead of elapsed_dma_ofs by preload size? */
> ds->pcm_buf_host_rw_ofs += xfercount;
> ds->pcm_buf_elapsed_dma_ofs += xfercount;
> - snd_pcm_period_elapsed(s);
> + /* defer to after the unlock */
> + elapsed = s;
> }
> +
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (elapsed)
> + snd_pcm_period_elapsed(elapsed);
> }
>
> if (!card->hpi->interrupt_mode && dpcm->respawn_timer)
[Severity: Critical]
Does deferring snd_pcm_stop_xrun() and snd_pcm_period_elapsed() outside
group->lock race with snd_pcm_detach_substream() on a closing member?
The comment notes that both helpers recheck substream->runtime under the
stream lock, but snd_pcm_detach_substream() does not acquire
pcm_stream_lock:
sound/core/pcm.c:snd_pcm_detach_substream() {
...
if (substream->timer) {
scoped_guard(spinlock_irq, &substream->timer->lock)
substream->runtime = NULL;
} else {
substream->runtime = NULL;
}
mutex_destroy(&runtime->buffer_mutex);
snd_fasync_free(runtime->fasync);
kfree(runtime);
...
}
Once group->lock is dropped, a concurrent close() on elapsed (or xrun) can
finish snd_pcm_unlink() and enter snd_pcm_detach_substream():
CPU0 (<softirq>) CPU1
snd_card_asihpi_timer_function()
elapsed = s;
spin_unlock_irqrestore(&group->lock)
snd_pcm_release_substream(s)
snd_pcm_unlink(s)
...
snd_pcm_detach_substream(s)
snd_pcm_period_elapsed(elapsed)
guard(pcm_stream_lock_irqsave)(s)
snd_pcm_period_elapsed_under_stream_lock(s)
if (PCM_RUNTIME_CHECK(s))
runtime = s->runtime;
s->runtime = NULL;
snd_fasync_free(runtime->fasync);
kfree(runtime);
if (!snd_pcm_running(s) || ...)
/* dereferences s->runtime->state */
snd_kill_fasync(runtime->fasync, ...) <-- use-after-free
Even if snd_pcm_detach_substream() finishes setting elapsed->runtime = NULL
before snd_pcm_period_elapsed() takes the stream lock,
PCM_RUNTIME_CHECK(substream) triggers snd_BUG_ON(!substream->runtime) when
CONFIG_SND_DEBUG is enabled.
[Severity: Critical]
What happens if the timer-owning substream itself is closed, or a member
runs hw_free, while snd_card_asihpi_timer_function() is between its locked
sections?
A substream stays on its own substream->self_group.substreams list even
after unlink and close, and snd_card_asihpi_pcm_timer_stop() only calls
timer_delete(&dpcm->timer) (not timer_delete_sync(), with no .sync_stop
callback):
CPU0 (<softirq>) CPU1
snd_card_asihpi_timer_function()
/* finishes Pass 1, unlocks */
snd_pcm_release_substream(substream)
snd_pcm_unlink(substream)
/* moves to self_group.substreams */
snd_pcm_drop(substream)
timer_delete(&dpcm->timer)
do_hw_free(substream)
snd_pcm_detach_substream(substream)
/* frees dpcm, sets runtime = NULL */
spin_lock_irqsave(&group->lock)
snd_pcm_group_for_each_entry()
s->runtime->private_data <-- NULL pointer dereference
...
if (... && dpcm->respawn_timer)
add_timer(&dpcm->timer) <-- use-after-free on dpcm
Similarly, in Pass 2, a member stopped by the deferred snd_pcm_stop_xrun()
at the end of Pass 1 (or by a concurrent SNDRV_PCM_IOCTL_DROP) can undergo
SNDRV_PCM_IOCTL_HW_FREE before Pass 2 acquires group->lock; do_hw_free()
clears s->runtime->dma_area = NULL without unlinking s, and Pass 2 does not
check snd_pcm_running(s) or s->runtime->dma_area before reading
&s->runtime->dma_area[buf_ofs] and passing it to hpi_outstream_write_buf()
or hpi_instream_read_buf().
[Severity: High]
Does holding spin_lock_irqsave(&group->lock, flags) across the bodies of
Pass 1 and Pass 2 disable local hardware interrupts during DSP polling and
multi-kilobyte PCI MMIO transfers?
Previously snd_card_asihpi_timer_function() ran with hardirqs enabled (from
TIMER_SOFTIRQ or the threaded ISR asihpi_isr_thread), and
hpios_dsplock_lock() used spin_lock_bh(). With spin_lock_irqsave() held
around each member, hpi_stream_get_info_ex(), hpi_stream_start(),
hpi_outstream_write_buf(), and hpi_instream_read_buf() now execute with local
IRQs disabled while busy-waiting in wait_dsp_ack() (udelay(4) polling loops
in sound/pci/asihpi/hpi6205.c) and transferring period buffers over PCI MMIO
in sound/pci/asihpi/hpi6000.c. In addition, rescanning from the list head in
asihpi_timer_next_member() on every iteration makes both passes O(N^2) with
2N + 4 lock acquisitions per callback.
--
Sashiko AI review · https://sashiko.dev/#/patchset/49f1dede.596.1a212c69040.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
2026-11-25 12:55 ` [PATCH] " 徐晗翔
2026-11-25 13:12 ` sashiko-bot
@ 2026-11-25 13:27 ` Takashi Iwai
1 sibling, 0 replies; 41+ messages in thread
From: Takashi Iwai @ 2026-11-25 13:27 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:55:32 +0100,
徐晗翔 wrote:
>
> snd_pcm_group_for_each_entry() is a plain list_for_each_entry() over
> substream->group->substreams. A driver timer callback (asihpi's
> snd_card_asihpi_timer_function()) walked that list from softirq with
> no group reference and no link rwsem, while the close of another
> linked substream could unlink the members, reassign the survivors
> and kfree() the group object -- the callback kept dereferencing a
> stale s/runtime pointer and freed group memory (KASAN UAF).
>
> Core: free the group object only after an RCU grace period (new
> rcu_head in struct snd_pcm_group, kfree_rcu() at both free sites),
> so a group pointer read without the link rwsem stays memory-safe
> while a concurrent unlink tears the group down.
>
> Driver: walk the group one member at a time under the group lock
> with rcu_read_lock() held -- the lock makes membership (and each
> member's runtime) stable while the member is processed, and RCU
> keeps the group object alive. snd_pcm_stop_xrun()/
> snd_pcm_period_elapsed() are deferred out of the locked section:
> they enter snd_pcm_action(), which re-takes the group lock. A
> substream object outlives its fd's close and both helpers recheck
> substream->runtime under the stream lock, so the deferred calls are
> safe against a concurrent close of the member.
I don't think we want to add a RCU there. It can open a can of worms.
IMO, an easier and safer fix would be to keep the ASIHPI's timer
callback alive only during the PCM stream running, i.e. assure to kill
the timer callback at PCM stop and sync_stop. During the PCM running
state, PCM links can't be changed, hence the list is safe to traverse.
thanks,
Takashi
> ---
> sound/core/pcm_native.c | 12 ++++++++++--
> include/sound/pcm.h | 6 ++++++
> sound/pci/asihpi/asihpi.c | 144 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
> 3 files changed, 145 insertions(+), 17 deletions(-)
>
> diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c
> --- a/sound/core/pcm_native.c
> +++ b/sound/core/pcm_native.c
> @@ -1368,7 +1368,11 @@
> do_free = refcount_dec_and_test(&group->refs);
> snd_pcm_group_unlock(group, substream->pcm->nonatomic);
> if (do_free)
> - kfree(group);
> + /* free only after an RCU grace period: a driver timer
> + * callback (softirq context) may hold group->lock under
> + * rcu_read_lock() without the link rwsem and must not
> + * touch freed group memory */
> + kfree_rcu(group, rcu_head);
> }
>
> /*
> @@ -2401,7 +2405,11 @@
>
> snd_pcm_group_unlock_irq(group, nonatomic);
> if (do_free)
> - kfree(group);
> + /* free only after an RCU grace period: a driver timer
> + * callback (softirq context) may hold group->lock under
> + * rcu_read_lock() without the link rwsem and must not
> + * touch freed group memory */
> + kfree_rcu(group, rcu_head);
> return 0;
> }
>
> diff --git a/include/sound/pcm.h b/include/sound/pcm.h
> --- a/include/sound/pcm.h
> +++ b/include/sound/pcm.h
> @@ -16,6 +16,7 @@
> #include <linux/bitops.h>
> #include <linux/pm_qos.h>
> #include <linux/refcount.h>
> +#include <linux/rcupdate.h>
> #include <linux/uio.h>
>
> #define snd_pcm_substream_chip(substream) ((substream)->private_data)
> @@ -455,6 +456,11 @@
> struct mutex mutex;
> struct list_head substreams;
> refcount_t refs;
> + /* a group object is freed only after an RCU grace period, so a
> + * lockless/atomic group walker (e.g. a driver timer callback that
> + * takes group->lock under rcu_read_lock()) cannot touch freed
> + * group memory while a concurrent unlink tears the group down */
> + struct rcu_head rcu_head;
> };
>
> struct pid;
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -136,6 +136,8 @@
> unsigned int pcm_buf_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int pcm_buf_elapsed_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int drained_count;
> + bool timer_walked; /* one-shot mark for the timer
> + * callback's group walk */
> struct snd_pcm_substream *substream;
> u32 h_stream;
> struct hpi_format format;
> @@ -705,6 +707,31 @@
> return result;
> }
>
> +/* Pick the next group member this timer callback has not processed yet.
> + * Must be called with the group lock held and under rcu_read_lock(): the
> + * group list cannot change under us, so every member's runtime is still
> + * alive. */
> +static struct snd_pcm_substream *
> +asihpi_timer_next_member(struct snd_pcm_substream *substream,
> + struct snd_card_asihpi *card)
> +{
> + struct snd_pcm_substream *s;
> +
> + snd_pcm_group_for_each_entry(s, substream) {
> + struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> +
> + if (snd_pcm_substream_chip(s) != card)
> + continue;
> + /* don't link Cap and Play */
> + if (substream->stream != s->stream)
> + continue;
> + if (ds->timer_walked)
> + continue;
> + return s;
> + }
> + return NULL;
> +}
> +
> /** Timer function, equivalent to interrupt service routine for cards
> */
> static void snd_card_asihpi_timer_function(struct timer_list *t)
> @@ -713,10 +740,12 @@
> struct snd_pcm_substream *substream = dpcm->substream;
> struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
> struct snd_pcm_runtime *runtime;
> + struct snd_pcm_group *group;
> struct snd_pcm_substream *s;
> unsigned int newdata = 0;
> unsigned int pcm_buf_dma_ofs, min_buf_pos = 0;
> unsigned int remdata, xfercount, next_jiffies;
> + unsigned long flags;
> int first = 1;
> u16 state;
> u32 buffer_size, bytes_avail, samples_played, on_card_bytes;
> @@ -725,17 +754,58 @@
>
> snd_pcm_debug_name(substream, name, sizeof(name));
>
> - /* find minimum newdata and buffer pos in group */
> + /*
> + * Walk the PCM link group one member at a time, under the group
> + * lock and an RCU read lock. This callback runs from a timer
> + * (softirq) with no group reference and no link rwsem, so a close
> + * of another linked substream could previously unlink the members,
> + * free the group object and free that member's runtime while this
> + * walk was holding a stale s/runtime pointer.
> + *
> + * The group lock keeps the membership (and each member's runtime)
> + * stable while the member is processed; the RCU read lock keeps
> + * the group object itself alive (snd_pcm_unlink() frees it only
> + * after a grace period). snd_pcm_stop_xrun() and
> + * snd_pcm_period_elapsed() must run WITHOUT the group lock -- they
> + * enter snd_pcm_action(), which re-takes the group lock -- so they
> + * are deferred to after the unlocked section. A substream object
> + * outlives the close of its fd, and both helpers recheck
> + * substream->runtime under the stream lock.
> + */
> +
> + /* clear the one-shot walk marks of the previous invocation */
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> snd_pcm_group_for_each_entry(s, substream) {
> - struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> - runtime = s->runtime;
> + if (snd_pcm_substream_chip(s) == card) {
> + struct snd_card_asihpi_pcm *ds =
> + s->runtime->private_data;
>
> - if (snd_pcm_substream_chip(s) != card)
> - continue;
> + ds->timer_walked = false;
> + }
> + }
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
>
> - /* don't link Cap and Play */
> - if (substream->stream != s->stream)
> - continue;
> + /* find minimum newdata and buffer pos in group */
> + for (;;) {
> + struct snd_card_asihpi_pcm *ds;
> + struct snd_pcm_substream *xrun = NULL;
> +
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> +
> + s = asihpi_timer_next_member(substream, card);
> + if (!s) {
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> + break;
> + }
> + ds = s->runtime->private_data;
> + runtime = s->runtime;
> + ds->timer_walked = true;
>
> hpi_handle_error(hpi_stream_get_info_ex(
> ds->h_stream, &state,
> @@ -762,8 +832,9 @@
> "P%d drained\n", s->number);
> ds->drained_count++;
> if (ds->drained_count > 20) {
> - snd_pcm_stop_xrun(s);
> - continue;
> + /* defer to after the unlock */
> + xrun = s;
> + goto member_done;
> }
> } else {
> ds->drained_count = 0;
> @@ -799,6 +870,13 @@
> (unsigned long)frames_to_bytes(runtime,
> runtime->control->appl_ptr)
> );
> +
> +member_done:
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (xrun)
> + snd_pcm_stop_xrun(xrun);
> }
> pcm_buf_dma_ofs = min_buf_pos;
>
> @@ -818,12 +896,41 @@
> asihpi_dbg("timer2, jif=%d, buf_pos=%d, newdata=%d, xfer=%d\n",
> next_jiffies, pcm_buf_dma_ofs, newdata, xfercount);
>
> + /* clear the one-shot walk marks again for the second pass */
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> snd_pcm_group_for_each_entry(s, substream) {
> - struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> + if (snd_pcm_substream_chip(s) == card) {
> + struct snd_card_asihpi_pcm *ds =
> + s->runtime->private_data;
>
> - /* don't link Cap and Play */
> - if (substream->stream != s->stream)
> - continue;
> + ds->timer_walked = false;
> + }
> + }
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + /* second pass, again one member at a time under the group lock
> + * (see above); snd_pcm_period_elapsed() is deferred to after the
> + * unlock for the same reason as snd_pcm_stop_xrun() */
> + for (;;) {
> + struct snd_card_asihpi_pcm *ds;
> + struct snd_pcm_substream *elapsed = NULL;
> +
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> +
> + s = asihpi_timer_next_member(substream, card);
> + if (!s) {
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> + break;
> + }
> + ds = s->runtime->private_data;
> + runtime = s->runtime;
> + ds->timer_walked = true;
>
> /* Store dma offset for use by pointer callback */
> ds->pcm_buf_dma_ofs = pcm_buf_dma_ofs;
> @@ -887,8 +994,15 @@
> /* ? host_rw_ofs always ahead of elapsed_dma_ofs by preload size? */
> ds->pcm_buf_host_rw_ofs += xfercount;
> ds->pcm_buf_elapsed_dma_ofs += xfercount;
> - snd_pcm_period_elapsed(s);
> + /* defer to after the unlock */
> + elapsed = s;
> }
> +
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (elapsed)
> + snd_pcm_period_elapsed(elapsed);
> }
>
> if (!card->hpi->interrupt_mode && dpcm->respawn_timer)
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-13 20:15:08 (星期五)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
> >
> > `snd_card_asihpi_timer_function()` walks the PCM link group with
> > `snd_pcm_group_for_each_entry()` and dereferences each member's
> > `s->runtime->private_data`. That macro is a plain `list_for_each_entry()`;
> > the callback holds no group reference and no group lock. Close of another
> > linked substream can unlink/free the group and detach/free that substream's
> > runtime and `dpcm`, leaving the timer callback with a stale `s`/runtime
> > pointer. This is reachable from user space through
> > `SNDRV_PCM_IOCTL_LINK` plus close, on hardware whose driver supports PCM
> > linking (asihpi does).
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> > was available; the harness reproduces the core group traversal and close
> > ordering, with the asihpi callback's exact
> > `snd_pcm_group_for_each_entry()` pattern.
> >
> > * Mechanism
> >
> > The group loops are at `sound/pci/asihpi/asihpi.c:729-735` and `821-827`.
> > They read `s->runtime->private_data` (and in one path `dma_area`) and call
> > `snd_pcm_period_elapsed(s)`. The macro is
> > `include/sound/pcm.h:694`:
> >
> > #define snd_pcm_group_for_each_entry(s, substream) \
> > list_for_each_entry(s, &substream->group->substreams, link_list)
> >
> > `snd_pcm_stream_lock_irq()` (`sound/core/pcm_native.c:140-144`) locks
> > `substream->self_group`, not the group that the timer callback walks.
> > `snd_pcm_unlink()` (`pcm_native.c:2370-2402`) takes
> > `snd_pcm_link_rwsem` and the group lock, removes the closing substream,
> > relinks the remaining streams, and may `kfree(group)`.
> > `snd_pcm_release_substream()` (`pcm_native.c:2785-2805`) calls
> > `pcm_release_private()` -> `snd_pcm_unlink()` at 2779-2783 before
> > `snd_pcm_detach_substream()` frees the runtime and `dpcm`.
> >
> > A timer callback that already loaded member `s` or `s->runtime` can run
> > after B's unlink/detach. It may then read freed `runtime`, freed
> > `private_data`, or a freed group list node; `snd_pcm_period_elapsed(s)`
> > additionally takes the stale substream.
> >
> > * Why existing synchronization does not close the window
> >
> > `snd_pcm_stop()` does transiently take a group reference through
> > `snd_pcm_action()` -> `snd_pcm_stream_group_ref()` (`pcm_native.c:1378-1427`)
> > and group lock, but it drops the reference after the STOP action. The
> > asihpi timer callback is not part of that action and holds no group
> > reference. Taking `snd_pcm_stream_lock_irq(A)` in the callback would only
> > lock A's `self_group`; it would not pin B or the group. The group can be
> > freed while the callback holds a raw member pointer.
> >
> > * Trigger model
> >
> > Two capture substreams A and B, same PCM and runtime state; user does
> > `SNDRV_PCM_IOCTL_LINK` then starts A. While A's timer callback is walking
> > the group, user closes B. `SNDRV_PCM_IOCTL_LINK` is available to a local
> > user with the PCM device open; no special privilege is needed beyond access
> > to the PCM. Consequence: UAF in timer context, crash or memory corruption.
> >
> >
> > * How to run the PoC
> >
> > The harness is self-contained and does not need ASI6205 hardware: it creates
> > a fake ALSA card with two capture substreams. The tested configuration was
> > 7.3.0 with KASAN and 4 vCPU; a uniprocessor run may not overlap.
> >
> > Build against the target kernel build tree:
> >
> > printf 'obj-m := sndpci_race.o\n' > Kbuild
> > make -C <kernel-build-dir> M=$PWD modules
> > gcc -static -O2 -I<kernel-source>/include/uapi -o pcmtest pcmtest.c
> >
> > Put `sndpci_race.ko` and `pcmtest` into the guest initramfs/rootfs, boot the
> > target kernel (QEMU/KVM recommended), then run as root:
> >
> > insmod sndpci_race.ko mode=pcm
> > ./pcmtest link 200
> > dmesg | grep -E 'BUG: KASAN|race_pcm_timer|victim use'
> >
> > In the minimal guest the fake card enumerates as card 0 and `pcmtest` opens
> > `/dev/snd/pcmC0D0c`. If the test machine already has another sound card,
> > adjust `DEV` in `pcmtest.c` or use the QEMU initramfs. Expected result:
> > 32 KASAN reports with `slab-use-after-free in race_pcm_timer` and about 114
> > `victim use` lines.
> >
> >
> > * Suggested direction
> >
> > This needs a core/lifetime fix, not just an asihpi timer fix. Possible
> > directions: make group traversal safe against concurrent unlink (group
> > reference or RCU-protected/atomic-safe iterator that pins each member's
> > runtime), or provide a driver API that snapshots/refcounts members before
> > the callback walks them. On the asihpi side, quiesce the timer/IRQ before
> > allowing the linked substream to detach. Adding only
> > `snd_pcm_stream_lock_irq(A)` is not sufficient because it locks A's
> > `self_group`, not the group being walked.
> >
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread
* ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (4 preceding siblings ...)
2026-11-13 12:15 ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
@ 2026-11-13 12:28 ` 徐晗翔
2026-11-25 12:48 ` [PATCH] " 徐晗翔
2026-11-13 12:29 ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
` (7 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:28 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8212 bytes --]
tascam_playback_close() and tascam_capture_close() only clear the
substream pointer; they do not stop URBs or cancel work. The ALSA
release path then calls snd_pcm_detach_substream(), which sets
substream->runtime to NULL and frees the snd_pcm_runtime. A
playback/feedback URB completion, or the capture work, can have loaded
the substream/runtime pointer before close; after detach it dereferences
runtime->rate, runtime->buffer_size, runtime->dma_area or
runtime->status, and may resubmit the next URB. This is a
use-after-free / oops on an ordinary PCM close while the device remains
connected. It is not the disconnect path. Capture close is also
affected because feedback_urb_complete() uses the capture runtime.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
sound/usb/usx2y/us144mkii.c, us144mkii_playback.c,
us144mkii_capture.c and us144mkii_pcm.c. The driver binds the
TASCAM US-144MKII (0644:8020) and US-144 (0644:800f). The relevant
configuration is CONFIG_SND_USB_US144MKII=m.
This report is based on source inspection, plus a synthetic ALSA PCM
model used to validate the close/detach lifetime pattern (see
"Reproducer (attached POC)" below). I have not run the real driver on
TASCAM hardware or under KASAN; no real-hardware result is claimed.
* Mechanism
1. The close callbacks do not stop I/O:
static int tascam_playback_close(struct snd_pcm_substream *substream)
{
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
tascam->playback_substream = NULL;
return 0;
}
(us144mkii_playback.c:35-42; tascam_capture_close() is the same at
us144mkii_capture.c:35-42). No usb_kill_urb(), no
cancel_work_sync().
2. tascam_pcm_trigger() on STOP only clears the active flags and
schedules stop_work asynchronously:
atomic_set(&tascam->playback_active, 0);
atomic_set(&tascam->capture_active, 0);
...
schedule_work(&tascam->stop_work);
(us144mkii_pcm.c:280-287 and 352-353). tascam_pcm_hw_free() is a
no-op (us144mkii_pcm.c:257-260), so ALSA's do_hw_free() cannot stop
anything either.
3. ALSA then frees the runtime:
snd_pcm_drop(substream); /* trigger STOP */
...
substream->ops->close(substream); /* only NULLs ptr */
...
snd_pcm_detach_substream(substream); /* frees runtime */
(sound/core/pcm_native.c:2785-2805; snd_pcm_detach_substream() at
sound/core/pcm.c:978-1005, substream->runtime = NULL at 997 and
kfree(runtime) at 1001).
4. Three consumers can already hold the old runtime pointer:
- playback_urb_complete() reads tascam->playback_substream and
substream->runtime at us144mkii_playback.c:176-182, then uses
runtime->rate / runtime->buffer_size under tascam->lock and
runtime->dma_area after unlocking (184-234), before resubmitting
at 237-247.
- feedback_urb_complete() reads the playback and capture
substreams at us144mkii_playback.c:282-288. It uses
capture_rt->period_size at 413-417 and calls
snd_pcm_period_elapsed(capture_ss) at 430 after unlocking.
Therefore capture close must also stop the feedback URB; it
currently stops neither capture nor feedback URBs.
- tascam_capture_work_handler() reads
tascam->capture_substream and substream->runtime at
us144mkii_capture.c:157-169 and writes runtime->dma_area at 230
under tascam->lock. It is queued by capture_urb_complete() at
line 301.
5. The asynchronous stop_work is not a close-time barrier.
usb_kill_anchored_urbs() in tascam_stop_work_handler() does wait
for a completion that is already inside the HCD giveback path
(__usb_hcd_giveback_urb() suspends the anchor wakeups before
usb_unanchor_urb(), and resumes them only after urb->complete()),
but stop_work itself is scheduled asynchronously by trigger(STOP).
close does not wait for stop_work, so detach can free the runtime
before stop_work runs. A per-URB usb_kill_urb() in close() is the
explicit synchronous barrier; it waits for urb->use_count == 0
(drivers/usb/core/urb.c:703-720).
6. A completion that has already passed the active/pointer check can
resubmit a URB after close's kill unless the final check and
usb_submit_urb() are serialized with close. The close path must
clear the active flag and substream pointer under tascam->lock,
kill the URBs, cancel the work, and make the completion's final
submit path take the same lock.
7. There is a second direction: feedback completion consumes the
capture runtime, but tascam_capture_close() stops neither capture
URBs nor feedback URBs. Closing capture while playback (and
therefore feedback) remains open can free capture_runtime while
feedback completion still uses capture_rt.
8. close() must also be serialized with tascam_disconnect():
tascam_disconnect() calls tascam_free_urbs() before
snd_card_free() waits for open PCM files to close
(us144mkii.c:580-611; free at 38-110). Without a
disconnect_lock/disconnected flag, a close that runs after the
slots were freed can call usb_kill_urb(NULL), or race the free.
* Reproducer
Attached files:
tascam_poc.c - synthetic ALSA PCM kernel module (C1 mode pcm1)
pcmtest.c - userland exerciser
Makefile - builds tascam_poc.ko against the running kernel
This POC does not drive the TASCAM device. It creates a synthetic ALSA
PCM card whose .close() only drops the substream pointer, starts an
asynchronous work item that caches the runtime, and lets ALSA detach and
free the runtime before the work runs. It therefore reproduces the
lifetime ordering in point 3/4 above, not the real USB URB completion.
A KASAN kernel is required to observe the UAF.
Build and run:
make
gcc -static -O2 -o pcmtest pcmtest.c
sudo modprobe snd-pcm
sudo insmod ./tascam_poc.ko mode=pcm1
sudo ./pcmtest 1
dmesg | tail -50
sudo rmmod tascam_poc
Expected result with KASAN:
BUG: KASAN: slab-use-after-free in race_pcm_work+0xce/0x140
Allocated by task ... (snd_pcm_open)
Freed by task ... (snd_pcm_release_substream/snd_pcm_detach_substream)
Negative control (close cancels the work):
sudo insmod ./tascam_poc.ko mode=pcm1 safe=1
sudo ./pcmtest 1
Expected: no KASAN report.
The module creates a capture PCM at card index 0; if that index is
occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
For a real-hardware KASAN run, the proposed procedure is:
arecord -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/null &
aplay -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/zero
# start playback, then close it while feedback is active;
# repeat open/start/close in a loop and watch dmesg for KASAN
For the capture-close direction, keep the playback process running
and repeatedly open/start/close the capture stream. The expected
KASAN top frames are playback_urb_complete(), feedback_urb_complete()
or tascam_capture_work_handler().
* Suggested direction
In .close(), under tascam->lock, clear the active flag and substream
pointer, then call usb_kill_urb() for every feedback/playback URB
(capture close: feedback/capture), and finally cancel_work_sync() for
stop_pcm_work, stop_work and capture_work as appropriate, before
returning to snd_pcm_detach_substream().
Use a disconnect_lock plus a disconnected flag to serialize this
cleanup with tascam_disconnect()'s tascam_free_urbs(); release the
lock before snd_card_free(). The completion's final
active/pointer check and usb_anchor_urb()/usb_submit_urb() should run
under the same tascam->lock, so a completion that raced with close
cannot submit a new URB after the kill.
I am happy to test a proposed fix.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: tascam_poc.c --]
[-- Type: text/plain, Size: 6616 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* tascam_poc.c - synthetic ALSA PCM lifetime reproducer for the TASCAM
* US-144MKII manual-review cases C1 and C2.
*
* This module deliberately reproduces the *lifetime patterns* of the driver,
* not the USB device itself:
* pcm1 : ALSA PCM .close() drops the runtime while an asynchronous
* "completion" still holds a runtime pointer (C1).
* pcm2 : a queued work item calls snd_pcm_stop() after .close()/detach
* (C2).
*
* The ALSA card is a synthetic platform device; no TASCAM hardware or USB
* traffic is involved. Build and run instructions are in README.txt.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/wait.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndusb_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm1";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "pcm1 or pcm2");
MODULE_PARM_DESC(safe, "take the safe cleanup path (negative control)");
/* ------------------------------------------------------------------ */
/* V1/V2 synthetic ALSA PCM */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
struct work_struct work;
atomic_t active;
bool c2;
u64 cookie;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_work(struct work_struct *work)
{
struct race_pcm *m = container_of(work, struct race_pcm, work);
struct snd_pcm_runtime *rt = m->runtime;
struct snd_pcm_substream *ss = m->substream;
pr_info(DRV ": work start mode=%s rt=%px ss=%px cookie=%#llx\n",
m->c2 ? "c2" : "c1", rt, ss, m->cookie);
if (!m->c2 && !rt)
return;
if (m->c2 && !ss)
return;
/* Give the closing thread time to run .close() and detach/free. */
msleep(120);
if (!m->c2) {
/*
* C1: the completion cached runtime before close; after
* snd_pcm_detach_substream() this is freed memory.
*/
pr_info(DRV ": c1 use rt=%px dma_area=%px\n", rt,
READ_ONCE(rt->dma_area));
barrier();
(void)READ_ONCE(rt->dma_area);
} else {
/*
* C2: the work cached the substream, but detach made
* ss->runtime NULL; snd_pcm_stop() dereferences it.
*/
pr_info(DRV ": c2 call snd_pcm_stop ss=%px runtime=%px\n",
ss, READ_ONCE(ss->runtime));
snd_pcm_stop(ss, SNDRV_PCM_STATE_XRUN);
}
pr_info(DRV ": work end\n");
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m;
m = kzalloc(sizeof(*m), GFP_KERNEL);
if (!m)
return -ENOMEM;
m->substream = substream;
m->runtime = runtime;
m->cookie = COOKIE;
m->c2 = !strcmp(mode, "pcm2");
INIT_WORK(&m->work, race_pcm_work);
atomic_set(&m->active, 0);
runtime->private_data = m;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": open sub=%px rt=%px mode=%s\n", substream, runtime, mode);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
pr_info(DRV ": close sub=%px rt=%px m=%px safe=%d\n",
substream, runtime, m, safe);
if (m && safe)
cancel_work_sync(&m->work);
if (m) {
m->substream = NULL;
m->runtime = NULL;
}
return 0;
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
if (!m)
return 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
atomic_set(&m->active, 1);
pr_info(DRV ": trigger start, queue work\n");
schedule_work(&m->work);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
atomic_set(&m->active, 0);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int sndusb_pcm_init(void)
{
int ret;
race_pdev = platform_device_register_simple("sndusb_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndUsbRace", THIS_MODULE, 0,
&race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndUsbRace", 0, 0, 1, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE, &race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev,
SNDRV_DMA_TYPE_CONTINUOUS, NULL,
64 * 1024, 64 * 1024);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered mode=%s safe=%d\n", mode, safe);
return 0;
}
static int __init sndusb_init(void)
{
pr_info(DRV ": init mode=%s safe=%d\n", mode, safe);
return sndusb_pcm_init();
}
static void __exit sndusb_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndusb_init);
module_exit(sndusb_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TASCAM US-144MKII C1/C2 synthetic lifetime reproducer");
[-- Attachment #3: pcmtest.c --]
[-- Type: text/plain, Size: 3737 bytes --]
#define _GNU_SOURCE
// SPDX-License-Identifier: GPL-2.0
/*
* pcmtest.c - guest-side exerciser for sndpci_race.ko.
*
* Usage:
* pcmtest close [iters] - open/start/close one playback substream (V4)
* pcmtest link [iters] - link two playback substreams, close B while
* the A timer callback walks the group (V5)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <sched.h>
#include <sound/asound.h>
#define DEV "/dev/snd/pcmC0D0c"
static int set_hw_params(int fd)
{
struct snd_pcm_hw_params p;
int i, ret;
memset(&p, 0, sizeof(p));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_MASK -
SNDRV_PCM_HW_PARAM_FIRST_MASK; i++)
memset(&p.masks[i], 0xff, sizeof(p.masks[i]));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL -
SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; i++) {
p.intervals[i].min = 0;
p.intervals[i].max = UINT_MAX;
p.intervals[i].integer = 0;
}
p.rmask = ~0U;
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, &p);
printf("HW_REFINE ret=%d errno=%d\n", ret, errno);
if (ret < 0)
return -1;
printf("refined: rate=%u ch=%u fmt=%u ps=%u periods=%u bs=%u\n",
p.intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
__builtin_ctz(p.masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0]),
p.intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_PERIODS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min);
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, &p);
if (ret < 0) {
fprintf(stderr, "HW_PARAMS: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int open_stream(void)
{
int fd = open(DEV, O_RDWR | O_NONBLOCK);
if (fd < 0)
fprintf(stderr, "open %s: %s\n", DEV, strerror(errno));
return fd;
}
static int prepare_stream(int fd)
{
if (set_hw_params(fd) < 0)
return -1;
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE, 0) < 0) {
fprintf(stderr, "PREPARE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int start_stream(int fd)
{
if (ioctl(fd, SNDRV_PCM_IOCTL_START, 0) < 0) {
fprintf(stderr, "START: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int one_close(void)
{
int fd = open_stream();
if (fd < 0)
return -1;
if (prepare_stream(fd) < 0 || start_stream(fd) < 0) {
close(fd);
return -1;
}
usleep(10000);
close(fd);
return 0;
}
static int one_link(void)
{
int a = open_stream();
int b = open_stream();
if (a < 0 || b < 0)
return -1;
if (prepare_stream(a) < 0 || prepare_stream(b) < 0)
goto out;
if (ioctl(a, SNDRV_PCM_IOCTL_LINK, b) < 0) {
fprintf(stderr, "LINK: %s\n", strerror(errno));
goto out;
}
if (start_stream(a) < 0)
goto out;
/* Let the A timer callback start walking the linked group. */
usleep(1500);
/* Close B while A's callback may be in the group loop. */
close(b);
b = -1;
usleep(1500);
out:
if (b >= 0)
close(b);
if (a >= 0)
close(a);
return 0;
}
int main(int argc, char **argv)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(1, &set);
sched_setaffinity(0, sizeof(set), &set);
int i, n = 200;
if (argc < 2) {
fprintf(stderr, "usage: %s close|link [iters]\n", argv[0]);
return 2;
}
if (argc > 2)
n = atoi(argv[2]);
printf("pcmtest: mode=%s iters=%d\n", argv[1], n);
for (i = 0; i < n; i++) {
if (!strcmp(argv[1], "link")) {
if (one_link() < 0)
break;
} else {
if (one_close() < 0)
break;
}
}
printf("pcmtest: done i=%d\n", i);
return 0;
}
[-- Attachment #4: Makefile --]
[-- Type: application/octet-stream, Size: 320 bytes --]
# Build against the running kernel's headers.
# For a KASAN test kernel, set KDIR to that build tree, e.g.:
# make KDIR=/path/to/linux KASAN=1
KDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
obj-m := tascam_poc.o
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
2026-11-13 12:28 ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
@ 2026-11-25 12:48 ` 徐晗翔
2026-11-25 13:13 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
tascam_playback_close() and tascam_capture_close() only cleared the
substream pointer; the ALSA release path then detached the substream
and freed the snd_pcm_runtime while a playback/feedback URB
completion or the capture work still used it.
Make close() a real synchronous barrier:
- clear the active flag and the substream pointer under
tascam->lock, and load them under the same lock in the
completions, so a completion cannot observe a stale substream of
a stream being quiesced;
- usb_kill_urb() every playback/feedback URB on playback close and
every capture/feedback URB on capture close (the feedback
completion consumes BOTH runtimes); usb_kill_urb() waits for each
in-flight completion, including one already inside the giveback
path;
- serialize the completions' final usb_submit_urb() with the close
under tascam->lock, so a completion that raced the close cannot
resubmit a killed URB;
- cancel_work_sync() for capture_work/stop_work/stop_pcm_work;
- serialize the whole quiesce with tascam_disconnect()'s
tascam_free_urbs() through a new cleanup_lock plus a
tascam->disconnected flag, released before snd_card_free() waits
for the open PCM files.
---
sound/usb/usx2y/us144mkii.h | 3 +++
sound/usb/usx2y/us144mkii_playback.c | 145 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------------------
sound/usb/usx2y/us144mkii.c | 16 ++++++++++++++++
sound/usb/usx2y/us144mkii_capture.c | 37 ++++++++++++++++++++++++++++++++++++-
4 files changed, 159 insertions(+), 42 deletions(-)
diff --git a/sound/usb/usx2y/us144mkii.h b/sound/usb/usx2y/us144mkii.h
--- a/sound/usb/usx2y/us144mkii.h
+++ b/sound/usb/usx2y/us144mkii.h
@@ -229,6 +229,9 @@
/* --- Stream State --- */
spinlock_t lock;
+ struct mutex cleanup_lock; /* serializes the close-time URB quiesce
+ * with disconnect()'s free path */
+ bool disconnected; /* disconnect() freed the URBs */
atomic_t playback_active;
atomic_t capture_active;
atomic_t active_urbs;
diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
--- a/sound/usb/usx2y/us144mkii_playback.c
+++ b/sound/usb/usx2y/us144mkii_playback.c
@@ -35,8 +35,40 @@
static int tascam_playback_close(struct snd_pcm_substream *substream)
{
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
+ int i;
- tascam->playback_substream = NULL;
+ /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
+ * via the cleanup lock; after disconnect() has run there is nothing
+ * left to kill. */
+ guard(mutex)(&tascam->cleanup_lock);
+ if (!tascam->disconnected) {
+ /* Clear the state under tascam->lock first, so a completion
+ * that races this close observes the cleared flag before its
+ * final resubmit (see the completions) and cannot bring an
+ * URB back to life after the kill. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ atomic_set(&tascam->playback_active, 0);
+ tascam->playback_substream = NULL;
+ }
+
+ /*
+ * Per-URB usb_kill_urb() is the explicit synchronous close
+ * barrier: it waits for each in-flight completion (including
+ * one that already passed the active/pointer checks). The
+ * feedback completion also consumes the playback runtime.
+ */
+ for (i = 0; i < NUM_PLAYBACK_URBS; i++)
+ if (tascam->playback_urbs[i])
+ usb_kill_urb(tascam->playback_urbs[i]);
+ for (i = 0; i < NUM_FEEDBACK_URBS; i++)
+ if (tascam->feedback_urbs[i])
+ usb_kill_urb(tascam->feedback_urbs[i]);
+ }
+
+ cancel_work_sync(&tascam->stop_work);
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
@@ -158,8 +190,8 @@
void playback_urb_complete(struct urb *urb)
{
struct tascam_card *tascam = urb->context;
- struct snd_pcm_substream *substream;
- struct snd_pcm_runtime *runtime;
+ struct snd_pcm_substream *substream = NULL;
+ struct snd_pcm_runtime *runtime = NULL;
size_t total_bytes_for_urb = 0;
snd_pcm_uframes_t offset_frames;
snd_pcm_uframes_t frames_to_copy;
@@ -173,15 +205,21 @@
urb->status);
goto out;
}
- if (!tascam || !atomic_read(&tascam->playback_active))
- goto out;
-
- substream = tascam->playback_substream;
- if (!substream || !substream->runtime)
+ if (!tascam)
goto out;
- runtime = substream->runtime;
+ /* Load the active flag and the substream under tascam->lock: a
+ * concurrent close clears both under the same lock, so this read
+ * cannot observe a stale substream of a stream that is being
+ * quiesced. */
scoped_guard(spinlock_irqsave, &tascam->lock) {
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ substream = tascam->playback_substream;
+ if (!substream || !substream->runtime)
+ goto out;
+ runtime = substream->runtime;
+
for (i = 0; i < urb->number_of_packets; i++) {
unsigned int frames_for_packet;
size_t bytes_for_packet;
@@ -237,18 +275,26 @@
frames_to_copy);
}
- urb->dev = tascam->dev;
- usb_get_urb(urb);
- usb_anchor_urb(urb, &tascam->playback_anchor);
- ret = usb_submit_urb(urb, GFP_ATOMIC);
- if (ret < 0) {
- dev_err_ratelimited(tascam->card->dev,
- "Failed to resubmit playback URB: %d\n",
- ret);
- usb_unanchor_urb(urb);
- usb_put_urb(urb);
- atomic_dec(
- &tascam->active_urbs); /* Decrement on failed resubmission */
+ /* Serialize the final resubmit with a concurrent close(): the close
+ * clears playback_active under tascam->lock, so observing it
+ * cleared here means the stream is being quiesced -- do not bring
+ * the URB back to life after the close's per-URB kill. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ urb->dev = tascam->dev;
+ usb_get_urb(urb);
+ usb_anchor_urb(urb, &tascam->playback_anchor);
+ ret = usb_submit_urb(urb, GFP_ATOMIC);
+ if (ret < 0) {
+ dev_err_ratelimited(tascam->card->dev,
+ "Failed to resubmit playback URB: %d\n",
+ ret);
+ usb_unanchor_urb(urb);
+ usb_put_urb(urb);
+ atomic_dec(
+ &tascam->active_urbs); /* Decrement on failed resubmission */
+ }
}
out:
usb_put_urb(urb);
@@ -257,8 +303,8 @@
void feedback_urb_complete(struct urb *urb)
{
struct tascam_card *tascam = urb->context;
- struct snd_pcm_substream *playback_ss, *capture_ss;
- struct snd_pcm_runtime *playback_rt, *capture_rt;
+ struct snd_pcm_substream *playback_ss = NULL, *capture_ss = NULL;
+ struct snd_pcm_runtime *playback_rt = NULL, *capture_rt = NULL;
u64 total_frames_in_urb = 0;
int ret, p;
unsigned int old_in_idx, new_in_idx;
@@ -276,18 +322,27 @@
}
goto out;
}
- if (!tascam || !atomic_read(&tascam->playback_active))
+ if (!tascam)
goto out;
- playback_ss = tascam->playback_substream;
- if (!playback_ss || !playback_ss->runtime)
- goto out;
- playback_rt = playback_ss->runtime;
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ /* Load the active flag and the substreams under
+ * tascam->lock: a concurrent playback or capture close
+ * clears the flag and the pointers under the same lock, so
+ * these reads cannot observe a stale substream whose
+ * runtime is being detached. The feedback completion
+ * consumes both runtimes, hence capture close must also
+ * quiesce the feedback URBs (see tascam_capture_close()). */
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ playback_ss = tascam->playback_substream;
+ if (!playback_ss || !playback_ss->runtime)
+ goto out;
+ playback_rt = playback_ss->runtime;
- capture_ss = tascam->capture_substream;
- capture_rt = capture_ss ? capture_ss->runtime : NULL;
+ capture_ss = tascam->capture_substream;
+ capture_rt = capture_ss ? capture_ss->runtime : NULL;
- scoped_guard(spinlock_irqsave, &tascam->lock) {
if (tascam->feedback_urb_skip_count > 0) {
tascam->feedback_urb_skip_count--;
break;
@@ -429,16 +484,24 @@
if (capture_period_elapsed)
snd_pcm_period_elapsed(capture_ss);
- urb->dev = tascam->dev;
- usb_get_urb(urb);
- usb_anchor_urb(urb, &tascam->feedback_anchor);
- ret = usb_submit_urb(urb, GFP_ATOMIC);
- if (ret < 0) {
- dev_err_ratelimited(tascam->card->dev,
- "Failed to resubmit feedback URB: %d\n",
- ret);
- usb_unanchor_urb(urb);
- usb_put_urb(urb);
+ /* Serialize the final resubmit with a concurrent close(): observing
+ * playback_active cleared under tascam->lock means the playback
+ * stream is being quiesced -- do not bring the URB back to life
+ * after the close's per-URB kill. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ urb->dev = tascam->dev;
+ usb_get_urb(urb);
+ usb_anchor_urb(urb, &tascam->feedback_anchor);
+ ret = usb_submit_urb(urb, GFP_ATOMIC);
+ if (ret < 0) {
+ dev_err_ratelimited(tascam->card->dev,
+ "Failed to resubmit feedback URB: %d\n",
+ ret);
+ usb_unanchor_urb(urb);
+ usb_put_urb(urb);
+ }
}
out:
usb_put_urb(urb);
diff --git a/sound/usb/usx2y/us144mkii.c b/sound/usb/usx2y/us144mkii.c
--- a/sound/usb/usx2y/us144mkii.c
+++ b/sound/usb/usx2y/us144mkii.c
@@ -497,6 +497,7 @@
tascam->capture_34_source = 1;
spin_lock_init(&tascam->lock);
+ mutex_init(&tascam->cleanup_lock);
spin_lock_init(&tascam->midi_in_lock);
spin_lock_init(&tascam->midi_out_lock);
init_usb_anchor(&tascam->playback_anchor);
@@ -588,6 +589,17 @@
snd_card_disconnect(tascam->card);
/*
+ * Serialize with a concurrent PCM close()'s quiesce (the
+ * per-URB kills below and tascam_free_urbs() must not race
+ * each other), then release the lock before snd_card_free()
+ * waits for the open PCM files: a close that runs during
+ * that wait sees tascam->disconnected and skips the URB
+ * handling.
+ */
+ mutex_lock(&tascam->cleanup_lock);
+ tascam->disconnected = true;
+
+ /*
* Kill the URBs before cancelling the work, so a late URB
* completion cannot re-arm a work that then runs after
* snd_card_free().
@@ -605,6 +617,10 @@
cancel_work_sync(&tascam->stop_pcm_work);
timer_delete_sync(&tascam->error_timer);
tascam_free_urbs(tascam);
+ /* release before snd_card_free(): it waits for the open PCM
+ * files, and a close running during that wait takes this
+ * lock (and sees tascam->disconnected) */
+ mutex_unlock(&tascam->cleanup_lock);
snd_card_free(tascam->card);
dev_idx--;
}
diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
--- a/sound/usb/usx2y/us144mkii_capture.c
+++ b/sound/usb/usx2y/us144mkii_capture.c
@@ -35,8 +35,43 @@
static int tascam_capture_close(struct snd_pcm_substream *substream)
{
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
+ int i;
- tascam->capture_substream = NULL;
+ /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
+ * via the cleanup lock; after disconnect() has run there is nothing
+ * left to kill. */
+ guard(mutex)(&tascam->cleanup_lock);
+ if (!tascam->disconnected) {
+ /* Clear the state under tascam->lock first (ordered against
+ * the completions' locked reads) before killing. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ atomic_set(&tascam->capture_active, 0);
+ tascam->capture_substream = NULL;
+ }
+
+ /*
+ * Kill the capture URBs, and the feedback URBs, too: the
+ * feedback completion consumes the capture runtime
+ * (capture_rt->period_size, snd_pcm_period_elapsed()), so
+ * closing capture while playback stays open must quiesce
+ * the feedback path as well. usb_kill_urb() waits for each
+ * in-flight completion -- the explicit synchronous barrier.
+ */
+ for (i = 0; i < NUM_CAPTURE_URBS; i++)
+ if (tascam->capture_urbs[i])
+ usb_kill_urb(tascam->capture_urbs[i]);
+ for (i = 0; i < NUM_FEEDBACK_URBS; i++)
+ if (tascam->feedback_urbs[i])
+ usb_kill_urb(tascam->feedback_urbs[i]);
+ }
+
+ /* the capture work caches substream->runtime at entry and writes
+ * runtime->dma_area; it must not run after the detach below */
+ cancel_work_sync(&tascam->capture_work);
+ cancel_work_sync(&tascam->stop_work);
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:28:42 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
>
> tascam_playback_close() and tascam_capture_close() only clear the
> substream pointer; they do not stop URBs or cancel work. The ALSA
> release path then calls snd_pcm_detach_substream(), which sets
> substream->runtime to NULL and frees the snd_pcm_runtime. A
> playback/feedback URB completion, or the capture work, can have loaded
> the substream/runtime pointer before close; after detach it dereferences
> runtime->rate, runtime->buffer_size, runtime->dma_area or
> runtime->status, and may resubmit the next URB. This is a
> use-after-free / oops on an ordinary PCM close while the device remains
> connected. It is not the disconnect path. Capture close is also
> affected because feedback_urb_complete() uses the capture runtime.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
> sound/usb/usx2y/us144mkii.c, us144mkii_playback.c,
> us144mkii_capture.c and us144mkii_pcm.c. The driver binds the
> TASCAM US-144MKII (0644:8020) and US-144 (0644:800f). The relevant
> configuration is CONFIG_SND_USB_US144MKII=m.
>
> This report is based on source inspection, plus a synthetic ALSA PCM
> model used to validate the close/detach lifetime pattern (see
> "Reproducer (attached POC)" below). I have not run the real driver on
> TASCAM hardware or under KASAN; no real-hardware result is claimed.
>
> * Mechanism
>
> 1. The close callbacks do not stop I/O:
>
> static int tascam_playback_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
>
> tascam->playback_substream = NULL;
> return 0;
> }
>
> (us144mkii_playback.c:35-42; tascam_capture_close() is the same at
> us144mkii_capture.c:35-42). No usb_kill_urb(), no
> cancel_work_sync().
>
> 2. tascam_pcm_trigger() on STOP only clears the active flags and
> schedules stop_work asynchronously:
>
> atomic_set(&tascam->playback_active, 0);
> atomic_set(&tascam->capture_active, 0);
> ...
> schedule_work(&tascam->stop_work);
>
> (us144mkii_pcm.c:280-287 and 352-353). tascam_pcm_hw_free() is a
> no-op (us144mkii_pcm.c:257-260), so ALSA's do_hw_free() cannot stop
> anything either.
>
> 3. ALSA then frees the runtime:
>
> snd_pcm_drop(substream); /* trigger STOP */
> ...
> substream->ops->close(substream); /* only NULLs ptr */
> ...
> snd_pcm_detach_substream(substream); /* frees runtime */
>
> (sound/core/pcm_native.c:2785-2805; snd_pcm_detach_substream() at
> sound/core/pcm.c:978-1005, substream->runtime = NULL at 997 and
> kfree(runtime) at 1001).
>
> 4. Three consumers can already hold the old runtime pointer:
>
> - playback_urb_complete() reads tascam->playback_substream and
> substream->runtime at us144mkii_playback.c:176-182, then uses
> runtime->rate / runtime->buffer_size under tascam->lock and
> runtime->dma_area after unlocking (184-234), before resubmitting
> at 237-247.
>
> - feedback_urb_complete() reads the playback and capture
> substreams at us144mkii_playback.c:282-288. It uses
> capture_rt->period_size at 413-417 and calls
> snd_pcm_period_elapsed(capture_ss) at 430 after unlocking.
> Therefore capture close must also stop the feedback URB; it
> currently stops neither capture nor feedback URBs.
>
> - tascam_capture_work_handler() reads
> tascam->capture_substream and substream->runtime at
> us144mkii_capture.c:157-169 and writes runtime->dma_area at 230
> under tascam->lock. It is queued by capture_urb_complete() at
> line 301.
>
> 5. The asynchronous stop_work is not a close-time barrier.
> usb_kill_anchored_urbs() in tascam_stop_work_handler() does wait
> for a completion that is already inside the HCD giveback path
> (__usb_hcd_giveback_urb() suspends the anchor wakeups before
> usb_unanchor_urb(), and resumes them only after urb->complete()),
> but stop_work itself is scheduled asynchronously by trigger(STOP).
> close does not wait for stop_work, so detach can free the runtime
> before stop_work runs. A per-URB usb_kill_urb() in close() is the
> explicit synchronous barrier; it waits for urb->use_count == 0
> (drivers/usb/core/urb.c:703-720).
>
> 6. A completion that has already passed the active/pointer check can
> resubmit a URB after close's kill unless the final check and
> usb_submit_urb() are serialized with close. The close path must
> clear the active flag and substream pointer under tascam->lock,
> kill the URBs, cancel the work, and make the completion's final
> submit path take the same lock.
>
> 7. There is a second direction: feedback completion consumes the
> capture runtime, but tascam_capture_close() stops neither capture
> URBs nor feedback URBs. Closing capture while playback (and
> therefore feedback) remains open can free capture_runtime while
> feedback completion still uses capture_rt.
>
> 8. close() must also be serialized with tascam_disconnect():
> tascam_disconnect() calls tascam_free_urbs() before
> snd_card_free() waits for open PCM files to close
> (us144mkii.c:580-611; free at 38-110). Without a
> disconnect_lock/disconnected flag, a close that runs after the
> slots were freed can call usb_kill_urb(NULL), or race the free.
>
>
>
> * Reproducer
>
> Attached files:
> tascam_poc.c - synthetic ALSA PCM kernel module (C1 mode pcm1)
> pcmtest.c - userland exerciser
> Makefile - builds tascam_poc.ko against the running kernel
>
> This POC does not drive the TASCAM device. It creates a synthetic ALSA
> PCM card whose .close() only drops the substream pointer, starts an
> asynchronous work item that caches the runtime, and lets ALSA detach and
> free the runtime before the work runs. It therefore reproduces the
> lifetime ordering in point 3/4 above, not the real USB URB completion.
> A KASAN kernel is required to observe the UAF.
>
> Build and run:
> make
> gcc -static -O2 -o pcmtest pcmtest.c
> sudo modprobe snd-pcm
> sudo insmod ./tascam_poc.ko mode=pcm1
> sudo ./pcmtest 1
> dmesg | tail -50
> sudo rmmod tascam_poc
>
> Expected result with KASAN:
> BUG: KASAN: slab-use-after-free in race_pcm_work+0xce/0x140
> Allocated by task ... (snd_pcm_open)
> Freed by task ... (snd_pcm_release_substream/snd_pcm_detach_substream)
>
> Negative control (close cancels the work):
> sudo insmod ./tascam_poc.ko mode=pcm1 safe=1
> sudo ./pcmtest 1
> Expected: no KASAN report.
>
> The module creates a capture PCM at card index 0; if that index is
> occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
>
> For a real-hardware KASAN run, the proposed procedure is:
>
> arecord -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/null &
> aplay -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/zero
> # start playback, then close it while feedback is active;
> # repeat open/start/close in a loop and watch dmesg for KASAN
>
> For the capture-close direction, keep the playback process running
> and repeatedly open/start/close the capture stream. The expected
> KASAN top frames are playback_urb_complete(), feedback_urb_complete()
> or tascam_capture_work_handler().
>
>
> * Suggested direction
>
> In .close(), under tascam->lock, clear the active flag and substream
> pointer, then call usb_kill_urb() for every feedback/playback URB
> (capture close: feedback/capture), and finally cancel_work_sync() for
> stop_pcm_work, stop_work and capture_work as appropriate, before
> returning to snd_pcm_detach_substream().
>
> Use a disconnect_lock plus a disconnected flag to serialize this
> cleanup with tascam_disconnect()'s tascam_free_urbs(); release the
> lock before snd_card_free(). The completion's final
> active/pointer check and usb_anchor_urb()/usb_submit_urb() should run
> under the same tascam->lock, so a completion that raced with close
> cannot submit a new URB after the kill.
>
> I am happy to test a proposed fix.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
2026-11-25 12:48 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:13 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:13 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 8 potential
issues to consider:
- [High] ALSA: usb-audio: us144mkii: missing Signed-off-by trailer in
commit
- [High] ALSA: usb-audio: us144mkii: cancelling stop_work wedges
active_urbs
- [High] ALSA: usb-audio: us144mkii: killing feedback URBs on close
stalls stream
- [High] ALSA: usb-audio: us144mkii: DMA buffer freed in do_hw_free()
before close()
- [High] ALSA: usb-audio: us144mkii: unlocked resubmit in
capture_urb_complete()
- [Medium] ALSA: usb-audio: us144mkii: stop_work cancelled before
stop_pcm_work
- [Low] ALSA: usb-audio: us144mkii: missing Fixes trailer on UAF bug fix
- [Low] ALSA: usb-audio: us144mkii: missing kernel-doc for new
tascam_card fields
--
commit 7f947095f0e3230e63ce245111703c733cee7d7a
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
>
> tascam_playback_close() and tascam_capture_close() only cleared the
> substream pointer; the ALSA release path then detached the substream
> and freed the snd_pcm_runtime while a playback/feedback URB
> completion or the capture work still used it.
>
> Make close() a real synchronous barrier:
>
> - clear the active flag and the substream pointer under
> tascam->lock, and load them under the same lock in the
> completions, so a completion cannot observe a stale substream of
> a stream being quiesced;
> - usb_kill_urb() every playback/feedback URB on playback close and
> every capture/feedback URB on capture close (the feedback
> completion consumes BOTH runtimes); usb_kill_urb() waits for each
> in-flight completion, including one already inside the giveback
> path;
> - serialize the completions' final usb_submit_urb() with the close
> under tascam->lock, so a completion that raced the close cannot
> resubmit a killed URB;
> - cancel_work_sync() for capture_work/stop_work/stop_pcm_work;
> - serialize the whole quiesce with tascam_disconnect()'s
> tascam_free_urbs() through a new cleanup_lock plus a
> tascam->disconnected flag, released before snd_card_free() waits
> for the open PCM files.
[Severity: High]
The commit message is missing a Signed-off-by: trailer, which is required
under the Developer's Certificate of Origin.
[Severity: Low]
Since this fixes a use-after-free in the playback/feedback and capture
paths, should it include Fixes: trailers for those commits?
Fixes: a2a2210f2c2e ("ALSA: usb-audio: us144mkii: Implement audio playback and feedback")
Fixes: c1bb0c13e430 ("ALSA: usb-audio: us144mkii: Implement audio capture and decoding")
> diff --git a/sound/usb/usx2y/us144mkii.c b/sound/usb/usx2y/us144mkii.c
> index 58ef23146f209..d2f2cd8bb3305 100644
> --- a/sound/usb/usx2y/us144mkii.c
> +++ b/sound/usb/usx2y/us144mkii.c
[ ... ]
> @@ -605,6 +617,10 @@ static void tascam_disconnect(struct usb_interface *intf)
> cancel_work_sync(&tascam->stop_pcm_work);
> timer_delete_sync(&tascam->error_timer);
> tascam_free_urbs(tascam);
> + /* release before snd_card_free(): it waits for the open PCM
> + * files, and a close running during that wait takes this
> + * lock (and sees tascam->disconnected) */
> + mutex_unlock(&tascam->cleanup_lock);
> snd_card_free(tascam->card);
> dev_idx--;
> }
[Severity: Medium]
Can tascam_stop_pcm_work_handler() re-arm tascam->stop_work after
cancel_work_sync(&tascam->stop_work) has already returned here and in
tascam_playback_close() / tascam_capture_close()?
tascam_stop_pcm_work_handler() calls snd_pcm_stop(), which invokes
tascam_pcm_trigger(SNDRV_PCM_TRIGGER_STOP) and calls
schedule_work(&tascam->stop_work). If stop_pcm_work is already running
when stop_work is cancelled first, it can queue stop_work again before
cancel_work_sync(&tascam->stop_pcm_work) runs, leaving stop_work pending
after close() or after snd_card_free() frees tascam_card. Cancelling
stop_pcm_work before stop_work avoids this.
> diff --git a/sound/usb/usx2y/us144mkii.h b/sound/usb/usx2y/us144mkii.h
> index 95c4341f038ad..4d049db675ef6 100644
> --- a/sound/usb/usx2y/us144mkii.h
> +++ b/sound/usb/usx2y/us144mkii.h
> @@ -229,6 +229,9 @@ struct tascam_card {
>
> /* --- Stream State --- */
> spinlock_t lock;
> + struct mutex cleanup_lock; /* serializes the close-time URB quiesce
> + * with disconnect()'s free path */
> + bool disconnected; /* disconnect() freed the URBs */
> atomic_t playback_active;
> atomic_t capture_active;
> atomic_t active_urbs;
[Severity: Low]
struct tascam_card has a kernel-doc comment header above it, so adding
cleanup_lock and disconnected without @cleanup_lock and @disconnected
entries in that comment block will trigger W=1 kernel-doc warnings.
> diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
> index d7cdf9e0f6851..0eba34cea5d1d 100644
> --- a/sound/usb/usx2y/us144mkii_capture.c
> +++ b/sound/usb/usx2y/us144mkii_capture.c
> @@ -35,8 +35,43 @@ static int tascam_capture_open(struct snd_pcm_substream *substream)
> static int tascam_capture_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> + int i;
> +
> + /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
> + * via the cleanup lock; after disconnect() has run there is nothing
> + * left to kill. */
> + guard(mutex)(&tascam->cleanup_lock);
> + if (!tascam->disconnected) {
> + /* Clear the state under tascam->lock first (ordered against
> + * the completions' locked reads) before killing. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + atomic_set(&tascam->capture_active, 0);
> + tascam->capture_substream = NULL;
> + }
> +
> + /*
> + * Kill the capture URBs, and the feedback URBs, too: the
> + * feedback completion consumes the capture runtime
> + * (capture_rt->period_size, snd_pcm_period_elapsed()), so
> + * closing capture while playback stays open must quiesce
> + * the feedback path as well. usb_kill_urb() waits for each
> + * in-flight completion -- the explicit synchronous barrier.
> + */
> + for (i = 0; i < NUM_CAPTURE_URBS; i++)
> + if (tascam->capture_urbs[i])
> + usb_kill_urb(tascam->capture_urbs[i]);
> + for (i = 0; i < NUM_FEEDBACK_URBS; i++)
> + if (tascam->feedback_urbs[i])
> + usb_kill_urb(tascam->feedback_urbs[i]);
> + }
[Severity: High]
Does killing tascam->feedback_urbs[] here without restarting them stall an
active playback stream when capture is closed?
When usb_kill_urb() unlinks the feedback URBs, feedback_urb_complete()
bails out on -ENOENT without resubmitting (and any in-flight completion
with status 0 fails usb_submit_urb() with -EPERM while urb->reject is
set). Because tascam_capture_close() never resubmits feedback_urbs[],
feedback_urb_complete() stops running altogether, halting
tascam->playback_frames_consumed updates and snd_pcm_period_elapsed() for
playback. Symmetrically, closing playback while capture is running clears
tascam->playback_active and kills feedback_urbs[] in
tascam_playback_close(), which freezes capture_frames_processed and causes
capture's later tascam_pcm_trigger(SNDRV_PCM_TRIGGER_STOP) to do nothing
because it checks atomic_read(&tascam->playback_active).
[Severity: High]
Is capture_urb_complete() missing the tascam->lock serialization that this
patch adds to playback_urb_complete() and feedback_urb_complete()?
sound/usb/usx2y/us144mkii_capture.c:capture_urb_complete() {
...
if (!tascam || !atomic_read(&tascam->capture_active))
goto out;
...
usb_get_urb(urb);
usb_anchor_urb(urb, &tascam->capture_anchor);
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret < 0) {
dev_err_ratelimited(tascam->card->dev,
"Failed to resubmit capture URB: %d\n",
ret);
usb_unanchor_urb(urb);
usb_put_urb(urb);
atomic_dec(
&tascam->active_urbs); /* Decrement on failed resubmission */
return;
}
out:
usb_put_urb(urb);
}
If capture_urb_complete() passes the unlocked capture_active check just
before tascam_capture_close() clears capture_active, it will still call
schedule_work(&tascam->capture_work) and usb_submit_urb(). If
tascam_capture_close() has already finished usb_kill_urb() on that URB
index, the URB is resubmitted after capture_active is 0; if usb_kill_urb()
is currently running on that URB, usb_submit_urb() fails with -EPERM and
the early return skips out: usb_put_urb(urb), leaking the URB reference
acquired when the completed transfer was submitted.
tascam_capture_work_handler() also still reads tascam->capture_substream
and substream->runtime at entry without holding tascam->lock.
>
> - tascam->capture_substream = NULL;
> + /* the capture work caches substream->runtime at entry and writes
> + * runtime->dma_area; it must not run after the detach below */
> + cancel_work_sync(&tascam->capture_work);
> + cancel_work_sync(&tascam->stop_work);
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
[Severity: High]
Does cancelling tascam->stop_work here and in tascam_playback_close()
leave tascam->active_urbs permanently non-zero after closing a running
stream?
When a running stream is closed, snd_pcm_release_substream() calls
snd_pcm_drop() -> tascam_pcm_trigger(SNDRV_PCM_TRIGGER_STOP), which queues
tascam->stop_work, and then immediately calls .close(). None of the URB
completions decrement tascam->active_urbs when an URB is killed with
-ENOENT; tascam_stop_work_handler() is the only place that resets
atomic_set(&tascam->active_urbs, 0) (and kills all three URB anchors,
including capture_anchor on playback close and playback_anchor on capture
close). When cancel_work_sync(&tascam->stop_work) cancels the pending
work item before it runs, tascam->active_urbs stays at 16 and every
subsequent SNDRV_PCM_TRIGGER_START fails with -EAGAIN at:
sound/usb/usx2y/us144mkii_pcm.c:tascam_pcm_trigger() {
...
if (do_start) {
if (atomic_read(&tascam->active_urbs) > 0) {
dev_warn(tascam->card->dev,
"Cannot start, URBs still active.\n");
return -EAGAIN;
}
...
}
> diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
> index 7efaca0a64899..58de4721ee859 100644
> --- a/sound/usb/usx2y/us144mkii_playback.c
> +++ b/sound/usb/usx2y/us144mkii_playback.c
> @@ -35,8 +35,40 @@ static int tascam_playback_open(struct snd_pcm_substream *substream)
> static int tascam_playback_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> + int i;
> +
> + /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
> + * via the cleanup lock; after disconnect() has run there is nothing
> + * left to kill. */
> + guard(mutex)(&tascam->cleanup_lock);
> + if (!tascam->disconnected) {
> + /* Clear the state under tascam->lock first, so a completion
> + * that races this close observes the cleared flag before its
> + * final resubmit (see the completions) and cannot bring an
> + * URB back to life after the kill. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + atomic_set(&tascam->playback_active, 0);
> + tascam->playback_substream = NULL;
> + }
> +
> + /*
> + * Per-URB usb_kill_urb() is the explicit synchronous close
> + * barrier: it waits for each in-flight completion (including
> + * one that already passed the active/pointer checks). The
> + * feedback completion also consumes the playback runtime.
> + */
> + for (i = 0; i < NUM_PLAYBACK_URBS; i++)
> + if (tascam->playback_urbs[i])
> + usb_kill_urb(tascam->playback_urbs[i]);
> + for (i = 0; i < NUM_FEEDBACK_URBS; i++)
> + if (tascam->feedback_urbs[i])
> + usb_kill_urb(tascam->feedback_urbs[i]);
> + }
[Severity: High]
Is .close() too late to quiesce playback_urb_complete() and
tascam_capture_work_handler() against runtime->dma_area teardown?
CPU0 CPU1 (<softirq> / kworker)
snd_pcm_release_substream()
snd_pcm_drop()
tascam_pcm_trigger(STOP)
schedule_work(&stop_work)
playback_urb_complete()
/* or tascam_capture_work_handler() */
do_hw_free()
tascam_pcm_hw_free() /* no-op */
snd_pcm_lib_free_pages()
runtime->dma_area = NULL;
memcpy(..., runtime->dma_area + ...)
<-- NULL dereference / UAF
substream->ops->close()
tascam_playback_close()
Because the driver uses snd_pcm_set_managed_buffer_all() and has neither a
.sync_stop callback nor URB/work quiescing in tascam_pcm_hw_free(),
do_hw_free() frees the DMA buffer and sets runtime->dma_area = NULL before
tascam_playback_close() or tascam_capture_close() is reached (and userspace
can also trigger do_hw_free() directly via SNDRV_PCM_IOCTL_HW_FREE without
closing). Stop synchronization needs to happen in .sync_stop or .hw_free
before snd_pcm_lib_free_pages() runs.
--
Sashiko AI review · https://sashiko.dev/#/patchset/7b5aed28.578.1a212c08a97.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (5 preceding siblings ...)
2026-11-13 12:28 ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
@ 2026-11-13 12:29 ` 徐晗翔
2026-11-25 12:49 ` [PATCH] " 徐晗翔
2026-11-22 7:43 ` sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF) 徐晗翔
` (6 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:29 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8406 bytes --]
tascam_stop_pcm_work_handler() is queued by feedback_urb_complete()
after a feedback sync loss, then reads tascam->playback_substream and
tascam->capture_substream without any lock and calls snd_pcm_stop() on
them. PCM close does not cancel this work. If close completes first,
snd_pcm_detach_substream() sets substream->runtime to NULL and frees the
snd_pcm_runtime; when the handler reaches snd_pcm_stop(),
snd_pcm_pre_stop() re-reads substream->runtime and dereferences the NULL
pointer. This is a conditional NULL-pointer dereference / oops on an
ordinary PCM close; a narrower runtime-UAF window is theoretically
possible but was not reproduced, so this report does not claim UAF.
The handler also violates the ALSA convention that snd_pcm_action()
must be called with the PCM stream lock held.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
sound/usb/usx2y/us144mkii_playback.c, us144mkii_pcm.c and
us144mkii.h. The driver binds the TASCAM US-144MKII (0644:8020) and
US-144 (0644:800f). The relevant configuration is
CONFIG_SND_USB_US144MKII=m.
This report is based on source inspection, plus a synthetic ALSA PCM
model used to validate the close/detach ordering. I have not run the
real driver on TASCAM hardware; no real-hardware result is claimed.
The attached POC is that synthetic-ordering model, not a TASCAM
hardware reproducer.
* Mechanism
1. The work is queued on feedback sync loss:
if (tascam->feedback_synced) {
tascam->feedback_consecutive_errors++;
if (tascam->feedback_consecutive_errors >
FEEDBACK_SYNC_LOSS_THRESHOLD) {
dev_err(tascam->card->dev,
"Fatal: Feedback sync lost. Stopping stream.\n");
schedule_work(&tascam->stop_pcm_work);
tascam->feedback_synced = false;
break;
}
}
(us144mkii_playback.c:347-356). FEEDBACK_SYNC_LOSS_THRESHOLD is
41 (us144mkii.h:88), so the condition is reached after 42
consecutive feedback errors.
2. The handler reads the pointers without a lock:
void tascam_stop_pcm_work_handler(struct work_struct *work)
{
struct tascam_card *tascam =
container_of(work, struct tascam_card,
stop_pcm_work);
if (tascam->playback_substream)
snd_pcm_stop(tascam->playback_substream,
SNDRV_PCM_STATE_XRUN);
if (tascam->capture_substream)
snd_pcm_stop(tascam->capture_substream,
SNDRV_PCM_STATE_XRUN);
}
(us144mkii_playback.c:447-456).
3. PCM close only NULLs the pointers and does not cancel the work:
tascam->playback_substream = NULL; /* or capture */
return 0;
(us144mkii_playback.c:35-42, us144mkii_capture.c:35-42). There
is no cancel_work_sync(&tascam->stop_pcm_work) in either close
callback.
4. ALSA then detaches and frees the runtime:
snd_pcm_drop(substream);
...
substream->ops->close(substream);
...
snd_pcm_detach_substream(substream);
(sound/core/pcm_native.c:2785-2805; sound/core/pcm.c:978-1005:
substream->runtime = NULL at 997, kfree(runtime) at 1001).
5. snd_pcm_stop() is not safe without the stream lock.
snd_pcm_action() is documented "Note: call with stream lock"
(sound/core/pcm_native.c:1411-1412); snd_pcm_pre_stop() does:
struct snd_pcm_runtime *runtime = substream->runtime;
if (runtime->state == SNDRV_PCM_STATE_OPEN)
return -EBADFD;
runtime->trigger_master = substream;
(sound/core/pcm_native.c:1549-1558). After detach runtime is
NULL, so the first dereference is a NULL-pointer oops.
snd_pcm_do_stop()/snd_pcm_post_stop() would also touch
runtime->trigger_master and runtime->sleep/tsleep (1570-1577).
6. Interleaving: the handler loads tascam->playback_substream (or
capture_substream) before close clears it, is preempted, close then
detaches and frees the runtime, and the handler proceeds into
snd_pcm_stop() and touches the NULL/freed runtime. The workqueue
item does not need to overlap with an URB completion at close time;
it only needs to be queued before close and executed after detach.
If the handler already passed a runtime non-NULL check before
detach, a narrower UAF is possible, but that form was not
reproduced and is not the primary claim.
* Trigger model
Feedback sync loss is needed: 42 consecutive feedback errors while
playback or capture is running. This can be produced with a USB
traffic fault injector, a short-packet/loss injection on the feedback
endpoint, or a programmable USB gadget emulating the device. After
the driver logs the feedback sync loss and queues the work, close the
PCM stream before the work runs. No special privilege beyond access
to the PCM device is required; TASCAM US-144MKII/US-144 hardware (or
an emulated equivalent) is required.
Consequence: NULL-pointer dereference / oops in
tascam_stop_pcm_work_handler() -> snd_pcm_stop() ->
snd_pcm_pre_stop(); because the work is already queued, this is
independent of the URB completion timing in Case 1.
* Reproducer (attached POC)
Attached files:
tascam_poc.c - synthetic ALSA PCM kernel module (C2 mode pcm2)
pcmtest.c - userland exerciser
Makefile - builds tascam_poc.ko against the running kernel
This POC does not drive the TASCAM device or inject feedback errors.
It creates a synthetic ALSA PCM card whose .close() only drops the
substream pointer, queues work that caches the substream, starts the
stream, and lets ALSA detach the runtime before the work calls
snd_pcm_stop(). It therefore reproduces the close/detach ordering in
point 4 above, not the real feedback-error path.
Build and run:
make
gcc -static -O2 -o pcmtest pcmtest.c
sudo modprobe snd-pcm
sudo insmod ./tascam_poc.ko mode=pcm2
sudo ./pcmtest 1
dmesg | tail -50
sudo rmmod tascam_poc
Expected result:
sndusb_race: c2 call snd_pcm_stop ss=... runtime=0000000000000000
BUG: KASAN: null-ptr-deref in snd_pcm_pre_stop+0x24/0x50
BUG: kernel NULL pointer dereference, address: 0000000000000000
Oops: 0000 [#1] SMP KASAN NOPTI
RIP: snd_pcm_pre_stop+0x24/0x50
Negative control (close cancels the work):
sudo insmod ./tascam_poc.ko mode=pcm2 safe=1
sudo ./pcmtest 1
Expected: no oops/KASAN report.
The module creates a capture PCM at card index 0; if that index is
occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
A minimal real-hardware KASAN test would:
- start playback and/or capture;
- inject 42 consecutive feedback errors (or use a gadget that
returns short/error packets on the feedback endpoint) until the
driver logs "Fatal: Feedback sync lost. Stopping stream.";
- immediately close the PCM stream in a loop;
- watch dmesg for a KASAN report with
tascam_stop_pcm_work_handler in the stack.
* Suggested direction
Make .close() cancel the work before returning to ALSA: clear the
active flag and pointer under tascam->lock, kill the relevant URBs
per-URB, then cancel_work_sync(&tascam->stop_pcm_work) (and
stop_work/capture_work as appropriate). cancel_work_sync() is the
lifecycle guarantee; it waits for a running handler.
In the handler, use snd_pcm_stop_xrun()
(sound/core/pcm_native.c:1628-1635), which takes the PCM stream lock
and rechecks substream->runtime. That fixes the API-convention
violation, but it is not a substitute for cancelling the work in
close: snd_pcm_detach_substream() does not take the stream lock, so
a handler that already passed the runtime check can still race with
detach.
I am happy to test a proposed fix.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: tascam_poc.c --]
[-- Type: text/plain, Size: 6616 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* tascam_poc.c - synthetic ALSA PCM lifetime reproducer for the TASCAM
* US-144MKII manual-review cases C1 and C2.
*
* This module deliberately reproduces the *lifetime patterns* of the driver,
* not the USB device itself:
* pcm1 : ALSA PCM .close() drops the runtime while an asynchronous
* "completion" still holds a runtime pointer (C1).
* pcm2 : a queued work item calls snd_pcm_stop() after .close()/detach
* (C2).
*
* The ALSA card is a synthetic platform device; no TASCAM hardware or USB
* traffic is involved. Build and run instructions are in README.txt.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/wait.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndusb_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm1";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "pcm1 or pcm2");
MODULE_PARM_DESC(safe, "take the safe cleanup path (negative control)");
/* ------------------------------------------------------------------ */
/* V1/V2 synthetic ALSA PCM */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
struct work_struct work;
atomic_t active;
bool c2;
u64 cookie;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_work(struct work_struct *work)
{
struct race_pcm *m = container_of(work, struct race_pcm, work);
struct snd_pcm_runtime *rt = m->runtime;
struct snd_pcm_substream *ss = m->substream;
pr_info(DRV ": work start mode=%s rt=%px ss=%px cookie=%#llx\n",
m->c2 ? "c2" : "c1", rt, ss, m->cookie);
if (!m->c2 && !rt)
return;
if (m->c2 && !ss)
return;
/* Give the closing thread time to run .close() and detach/free. */
msleep(120);
if (!m->c2) {
/*
* C1: the completion cached runtime before close; after
* snd_pcm_detach_substream() this is freed memory.
*/
pr_info(DRV ": c1 use rt=%px dma_area=%px\n", rt,
READ_ONCE(rt->dma_area));
barrier();
(void)READ_ONCE(rt->dma_area);
} else {
/*
* C2: the work cached the substream, but detach made
* ss->runtime NULL; snd_pcm_stop() dereferences it.
*/
pr_info(DRV ": c2 call snd_pcm_stop ss=%px runtime=%px\n",
ss, READ_ONCE(ss->runtime));
snd_pcm_stop(ss, SNDRV_PCM_STATE_XRUN);
}
pr_info(DRV ": work end\n");
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m;
m = kzalloc(sizeof(*m), GFP_KERNEL);
if (!m)
return -ENOMEM;
m->substream = substream;
m->runtime = runtime;
m->cookie = COOKIE;
m->c2 = !strcmp(mode, "pcm2");
INIT_WORK(&m->work, race_pcm_work);
atomic_set(&m->active, 0);
runtime->private_data = m;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": open sub=%px rt=%px mode=%s\n", substream, runtime, mode);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
pr_info(DRV ": close sub=%px rt=%px m=%px safe=%d\n",
substream, runtime, m, safe);
if (m && safe)
cancel_work_sync(&m->work);
if (m) {
m->substream = NULL;
m->runtime = NULL;
}
return 0;
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
if (!m)
return 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
atomic_set(&m->active, 1);
pr_info(DRV ": trigger start, queue work\n");
schedule_work(&m->work);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
atomic_set(&m->active, 0);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int sndusb_pcm_init(void)
{
int ret;
race_pdev = platform_device_register_simple("sndusb_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndUsbRace", THIS_MODULE, 0,
&race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndUsbRace", 0, 0, 1, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE, &race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev,
SNDRV_DMA_TYPE_CONTINUOUS, NULL,
64 * 1024, 64 * 1024);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered mode=%s safe=%d\n", mode, safe);
return 0;
}
static int __init sndusb_init(void)
{
pr_info(DRV ": init mode=%s safe=%d\n", mode, safe);
return sndusb_pcm_init();
}
static void __exit sndusb_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndusb_init);
module_exit(sndusb_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TASCAM US-144MKII C1/C2 synthetic lifetime reproducer");
[-- Attachment #3: pcmtest.c --]
[-- Type: text/plain, Size: 3737 bytes --]
#define _GNU_SOURCE
// SPDX-License-Identifier: GPL-2.0
/*
* pcmtest.c - guest-side exerciser for sndpci_race.ko.
*
* Usage:
* pcmtest close [iters] - open/start/close one playback substream (V4)
* pcmtest link [iters] - link two playback substreams, close B while
* the A timer callback walks the group (V5)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <sched.h>
#include <sound/asound.h>
#define DEV "/dev/snd/pcmC0D0c"
static int set_hw_params(int fd)
{
struct snd_pcm_hw_params p;
int i, ret;
memset(&p, 0, sizeof(p));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_MASK -
SNDRV_PCM_HW_PARAM_FIRST_MASK; i++)
memset(&p.masks[i], 0xff, sizeof(p.masks[i]));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL -
SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; i++) {
p.intervals[i].min = 0;
p.intervals[i].max = UINT_MAX;
p.intervals[i].integer = 0;
}
p.rmask = ~0U;
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, &p);
printf("HW_REFINE ret=%d errno=%d\n", ret, errno);
if (ret < 0)
return -1;
printf("refined: rate=%u ch=%u fmt=%u ps=%u periods=%u bs=%u\n",
p.intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
__builtin_ctz(p.masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0]),
p.intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_PERIODS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min);
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, &p);
if (ret < 0) {
fprintf(stderr, "HW_PARAMS: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int open_stream(void)
{
int fd = open(DEV, O_RDWR | O_NONBLOCK);
if (fd < 0)
fprintf(stderr, "open %s: %s\n", DEV, strerror(errno));
return fd;
}
static int prepare_stream(int fd)
{
if (set_hw_params(fd) < 0)
return -1;
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE, 0) < 0) {
fprintf(stderr, "PREPARE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int start_stream(int fd)
{
if (ioctl(fd, SNDRV_PCM_IOCTL_START, 0) < 0) {
fprintf(stderr, "START: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int one_close(void)
{
int fd = open_stream();
if (fd < 0)
return -1;
if (prepare_stream(fd) < 0 || start_stream(fd) < 0) {
close(fd);
return -1;
}
usleep(10000);
close(fd);
return 0;
}
static int one_link(void)
{
int a = open_stream();
int b = open_stream();
if (a < 0 || b < 0)
return -1;
if (prepare_stream(a) < 0 || prepare_stream(b) < 0)
goto out;
if (ioctl(a, SNDRV_PCM_IOCTL_LINK, b) < 0) {
fprintf(stderr, "LINK: %s\n", strerror(errno));
goto out;
}
if (start_stream(a) < 0)
goto out;
/* Let the A timer callback start walking the linked group. */
usleep(1500);
/* Close B while A's callback may be in the group loop. */
close(b);
b = -1;
usleep(1500);
out:
if (b >= 0)
close(b);
if (a >= 0)
close(a);
return 0;
}
int main(int argc, char **argv)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(1, &set);
sched_setaffinity(0, sizeof(set), &set);
int i, n = 200;
if (argc < 2) {
fprintf(stderr, "usage: %s close|link [iters]\n", argv[0]);
return 2;
}
if (argc > 2)
n = atoi(argv[2]);
printf("pcmtest: mode=%s iters=%d\n", argv[1], n);
for (i = 0; i < n; i++) {
if (!strcmp(argv[1], "link")) {
if (one_link() < 0)
break;
} else {
if (one_close() < 0)
break;
}
}
printf("pcmtest: done i=%d\n", i);
return 0;
}
[-- Attachment #4: Makefile --]
[-- Type: application/octet-stream, Size: 320 bytes --]
# Build against the running kernel's headers.
# For a KASAN test kernel, set KDIR to that build tree, e.g.:
# make KDIR=/path/to/linux KASAN=1
KDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
obj-m := tascam_poc.o
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
2026-11-13 12:29 ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
@ 2026-11-25 12:49 ` 徐晗翔
2026-11-25 13:03 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:49 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
A stop_pcm_work queued by feedback_urb_complete() after a feedback
sync loss read tascam->playback_substream/capture_substream without
any lock and called snd_pcm_stop() on them; PCM close did not
cancel the work, so after snd_pcm_detach_substream() cleared
substream->runtime the handler's snd_pcm_stop() oopsed in
snd_pcm_pre_stop() on the NULL runtime.
Cancel the work in both .close() callbacks (cancel_work_sync() is
the lifecycle guarantee; it waits for a running handler), and make
the handler use snd_pcm_stop_xrun(), which takes the PCM stream
lock itself and rechecks substream->runtime -- fixing both the
missing close-cancel and the ALSA convention that snd_pcm_action()
must run under the stream lock. This patch touches the same .close()
functions as the separate PCM-close UAF report; the two fixes are
complementary, not interchangeable.
---
sound/usb/usx2y/us144mkii_playback.c | 12 ++++++++++--
sound/usb/usx2y/us144mkii_capture.c | 3 +++
2 files changed, 13 insertions(+), 2 deletions(-)
diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
--- a/sound/usb/usx2y/us144mkii_playback.c
+++ b/sound/usb/usx2y/us144mkii_playback.c
@@ -37,6 +37,9 @@
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
tascam->playback_substream = NULL;
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
@@ -449,8 +452,13 @@
struct tascam_card *tascam =
container_of(work, struct tascam_card, stop_pcm_work);
+ /* snd_pcm_stop() requires the PCM stream lock and dereferences
+ * substream->runtime unconditionally; after a concurrent close the
+ * runtime is NULL and snd_pcm_pre_stop() oopses. Use
+ * snd_pcm_stop_xrun(), which takes the stream lock itself and
+ * rechecks substream->runtime before touching it. */
if (tascam->playback_substream)
- snd_pcm_stop(tascam->playback_substream, SNDRV_PCM_STATE_XRUN);
+ snd_pcm_stop_xrun(tascam->playback_substream);
if (tascam->capture_substream)
- snd_pcm_stop(tascam->capture_substream, SNDRV_PCM_STATE_XRUN);
+ snd_pcm_stop_xrun(tascam->capture_substream);
}
diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
--- a/sound/usb/usx2y/us144mkii_capture.c
+++ b/sound/usb/usx2y/us144mkii_capture.c
@@ -37,6 +37,9 @@
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
tascam->capture_substream = NULL;
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:29:53 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
>
> tascam_stop_pcm_work_handler() is queued by feedback_urb_complete()
> after a feedback sync loss, then reads tascam->playback_substream and
> tascam->capture_substream without any lock and calls snd_pcm_stop() on
> them. PCM close does not cancel this work. If close completes first,
> snd_pcm_detach_substream() sets substream->runtime to NULL and frees the
> snd_pcm_runtime; when the handler reaches snd_pcm_stop(),
> snd_pcm_pre_stop() re-reads substream->runtime and dereferences the NULL
> pointer. This is a conditional NULL-pointer dereference / oops on an
> ordinary PCM close; a narrower runtime-UAF window is theoretically
> possible but was not reproduced, so this report does not claim UAF.
> The handler also violates the ALSA convention that snd_pcm_action()
> must be called with the PCM stream lock held.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
> sound/usb/usx2y/us144mkii_playback.c, us144mkii_pcm.c and
> us144mkii.h. The driver binds the TASCAM US-144MKII (0644:8020) and
> US-144 (0644:800f). The relevant configuration is
> CONFIG_SND_USB_US144MKII=m.
>
> This report is based on source inspection, plus a synthetic ALSA PCM
> model used to validate the close/detach ordering. I have not run the
> real driver on TASCAM hardware; no real-hardware result is claimed.
> The attached POC is that synthetic-ordering model, not a TASCAM
> hardware reproducer.
>
> * Mechanism
>
> 1. The work is queued on feedback sync loss:
>
> if (tascam->feedback_synced) {
> tascam->feedback_consecutive_errors++;
> if (tascam->feedback_consecutive_errors >
> FEEDBACK_SYNC_LOSS_THRESHOLD) {
> dev_err(tascam->card->dev,
> "Fatal: Feedback sync lost. Stopping stream.\n");
> schedule_work(&tascam->stop_pcm_work);
> tascam->feedback_synced = false;
> break;
> }
> }
>
> (us144mkii_playback.c:347-356). FEEDBACK_SYNC_LOSS_THRESHOLD is
> 41 (us144mkii.h:88), so the condition is reached after 42
> consecutive feedback errors.
>
> 2. The handler reads the pointers without a lock:
>
> void tascam_stop_pcm_work_handler(struct work_struct *work)
> {
> struct tascam_card *tascam =
> container_of(work, struct tascam_card,
> stop_pcm_work);
>
> if (tascam->playback_substream)
> snd_pcm_stop(tascam->playback_substream,
> SNDRV_PCM_STATE_XRUN);
> if (tascam->capture_substream)
> snd_pcm_stop(tascam->capture_substream,
> SNDRV_PCM_STATE_XRUN);
> }
>
> (us144mkii_playback.c:447-456).
>
> 3. PCM close only NULLs the pointers and does not cancel the work:
>
> tascam->playback_substream = NULL; /* or capture */
> return 0;
>
> (us144mkii_playback.c:35-42, us144mkii_capture.c:35-42). There
> is no cancel_work_sync(&tascam->stop_pcm_work) in either close
> callback.
>
> 4. ALSA then detaches and frees the runtime:
>
> snd_pcm_drop(substream);
> ...
> substream->ops->close(substream);
> ...
> snd_pcm_detach_substream(substream);
>
> (sound/core/pcm_native.c:2785-2805; sound/core/pcm.c:978-1005:
> substream->runtime = NULL at 997, kfree(runtime) at 1001).
>
> 5. snd_pcm_stop() is not safe without the stream lock.
> snd_pcm_action() is documented "Note: call with stream lock"
> (sound/core/pcm_native.c:1411-1412); snd_pcm_pre_stop() does:
>
> struct snd_pcm_runtime *runtime = substream->runtime;
> if (runtime->state == SNDRV_PCM_STATE_OPEN)
> return -EBADFD;
> runtime->trigger_master = substream;
>
> (sound/core/pcm_native.c:1549-1558). After detach runtime is
> NULL, so the first dereference is a NULL-pointer oops.
> snd_pcm_do_stop()/snd_pcm_post_stop() would also touch
> runtime->trigger_master and runtime->sleep/tsleep (1570-1577).
>
> 6. Interleaving: the handler loads tascam->playback_substream (or
> capture_substream) before close clears it, is preempted, close then
> detaches and frees the runtime, and the handler proceeds into
> snd_pcm_stop() and touches the NULL/freed runtime. The workqueue
> item does not need to overlap with an URB completion at close time;
> it only needs to be queued before close and executed after detach.
> If the handler already passed a runtime non-NULL check before
> detach, a narrower UAF is possible, but that form was not
> reproduced and is not the primary claim.
>
> * Trigger model
>
> Feedback sync loss is needed: 42 consecutive feedback errors while
> playback or capture is running. This can be produced with a USB
> traffic fault injector, a short-packet/loss injection on the feedback
> endpoint, or a programmable USB gadget emulating the device. After
> the driver logs the feedback sync loss and queues the work, close the
> PCM stream before the work runs. No special privilege beyond access
> to the PCM device is required; TASCAM US-144MKII/US-144 hardware (or
> an emulated equivalent) is required.
>
> Consequence: NULL-pointer dereference / oops in
> tascam_stop_pcm_work_handler() -> snd_pcm_stop() ->
> snd_pcm_pre_stop(); because the work is already queued, this is
> independent of the URB completion timing in Case 1.
>
> * Reproducer (attached POC)
>
> Attached files:
> tascam_poc.c - synthetic ALSA PCM kernel module (C2 mode pcm2)
> pcmtest.c - userland exerciser
> Makefile - builds tascam_poc.ko against the running kernel
>
> This POC does not drive the TASCAM device or inject feedback errors.
> It creates a synthetic ALSA PCM card whose .close() only drops the
> substream pointer, queues work that caches the substream, starts the
> stream, and lets ALSA detach the runtime before the work calls
> snd_pcm_stop(). It therefore reproduces the close/detach ordering in
> point 4 above, not the real feedback-error path.
>
> Build and run:
> make
> gcc -static -O2 -o pcmtest pcmtest.c
> sudo modprobe snd-pcm
> sudo insmod ./tascam_poc.ko mode=pcm2
> sudo ./pcmtest 1
> dmesg | tail -50
> sudo rmmod tascam_poc
>
> Expected result:
> sndusb_race: c2 call snd_pcm_stop ss=... runtime=0000000000000000
> BUG: KASAN: null-ptr-deref in snd_pcm_pre_stop+0x24/0x50
> BUG: kernel NULL pointer dereference, address: 0000000000000000
> Oops: 0000 [#1] SMP KASAN NOPTI
> RIP: snd_pcm_pre_stop+0x24/0x50
>
> Negative control (close cancels the work):
> sudo insmod ./tascam_poc.ko mode=pcm2 safe=1
> sudo ./pcmtest 1
> Expected: no oops/KASAN report.
>
> The module creates a capture PCM at card index 0; if that index is
> occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
>
> A minimal real-hardware KASAN test would:
> - start playback and/or capture;
> - inject 42 consecutive feedback errors (or use a gadget that
> returns short/error packets on the feedback endpoint) until the
> driver logs "Fatal: Feedback sync lost. Stopping stream.";
> - immediately close the PCM stream in a loop;
> - watch dmesg for a KASAN report with
> tascam_stop_pcm_work_handler in the stack.
>
>
> * Suggested direction
>
> Make .close() cancel the work before returning to ALSA: clear the
> active flag and pointer under tascam->lock, kill the relevant URBs
> per-URB, then cancel_work_sync(&tascam->stop_pcm_work) (and
> stop_work/capture_work as appropriate). cancel_work_sync() is the
> lifecycle guarantee; it waits for a running handler.
>
> In the handler, use snd_pcm_stop_xrun()
> (sound/core/pcm_native.c:1628-1635), which takes the PCM stream lock
> and rechecks substream->runtime. That fixes the API-convention
> violation, but it is not a substitute for cancelling the work in
> close: snd_pcm_detach_substream() does not take the stream lock, so
> a handler that already passed the runtime check can still race with
> detach.
>
> I am happy to test a proposed fix.
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
2026-11-25 12:49 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:03 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 13:03 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 5 potential
issues to consider:
- [High] ALSA: usb-audio: us144mkii: missing Signed-off-by trailer in
commit
- [High] ALSA: usb-audio: us144mkii: feedback_urb_complete() re-arms
work after close
- [Medium] ALSA: usb-audio: us144mkii: unlocked TOCTOU substream read in
stop_pcm_work
- [Medium] ALSA: usb-audio: us144mkii: cancel_work_sync() in close drops
sibling XRUN
- [Low] ALSA: usb-audio: us144mkii: missing Fixes trailer in commit
message
--
commit b36c55bb30946f2fb9b8c0b478d61532334be47c
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
>
> A stop_pcm_work queued by feedback_urb_complete() after a feedback
> sync loss read tascam->playback_substream/capture_substream without
> any lock and called snd_pcm_stop() on them; PCM close did not
> cancel the work, so after snd_pcm_detach_substream() cleared
> substream->runtime the handler's snd_pcm_stop() oopsed in
> snd_pcm_pre_stop() on the NULL runtime.
>
> Cancel the work in both .close() callbacks (cancel_work_sync() is
> the lifecycle guarantee; it waits for a running handler), and make
> the handler use snd_pcm_stop_xrun(), which takes the PCM stream
> lock itself and rechecks substream->runtime -- fixing both the
> missing close-cancel and the ALSA convention that snd_pcm_action()
> must run under the stream lock. This patch touches the same .close()
> functions as the separate PCM-close UAF report; the two fixes are
> complementary, not interchangeable.
[Severity: High]
This commit message is missing a Signed-off-by: trailer.
[Severity: Low]
Since this fixes a bug introduced when playback and feedback handling were
added, should it include a Fixes: tag?
Fixes: a2a2210f2c2e ("ALSA: usb-audio: us144mkii: Implement audio playback and feedback")
> diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
> index d7cdf9e0f6851..1f6d87a9421a5 100644
> --- a/sound/usb/usx2y/us144mkii_capture.c
> +++ b/sound/usb/usx2y/us144mkii_capture.c
> @@ -37,6 +37,9 @@ static int tascam_capture_close(struct snd_pcm_substream *substream)
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
>
> tascam->capture_substream = NULL;
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
[Severity: Medium]
Can cancelling tascam->stop_pcm_work here drop a pending feedback-sync-loss
XRUN stop for a playback substream that is still running?
tascam->stop_pcm_work is shared by both playback and capture. When
feedback_urb_complete() queues tascam->stop_pcm_work, it immediately sets
tascam->feedback_synced = false:
sound/usb/usx2y/us144mkii_playback.c:feedback_urb_complete() {
...
if (tascam->feedback_synced) {
tascam->feedback_consecutive_errors++;
if (tascam->feedback_consecutive_errors >
FEEDBACK_SYNC_LOSS_THRESHOLD) {
...
schedule_work(
&tascam->stop_pcm_work);
tascam->feedback_synced = false;
break;
}
}
...
}
If capture is opened and closed (for example by an application probing the
device) while playback is running and losing feedback sync,
tascam_capture_close() cancels the pending work item and
feedback_urb_complete() will never re-queue it because feedback_synced is
already false, leaving playback running unsynchronized instead of entering
SNDRV_PCM_STATE_XRUN.
> diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
> index 7efaca0a64899..1bdc68006baf1 100644
> --- a/sound/usb/usx2y/us144mkii_playback.c
> +++ b/sound/usb/usx2y/us144mkii_playback.c
> @@ -37,6 +37,9 @@ static int tascam_playback_close(struct snd_pcm_substream *substream)
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
>
> tascam->playback_substream = NULL;
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
[Severity: High]
Can an in-flight feedback_urb_complete() schedule tascam->stop_pcm_work
again after cancel_work_sync() returns?
During close, tascam_pcm_trigger() with SNDRV_PCM_TRIGGER_STOP only queues
tascam->stop_work asynchronously to kill the anchored URBs, and neither
tascam_playback_close() nor tascam_capture_close() flushes tascam->stop_work
or kills tascam->feedback_anchor before calling
cancel_work_sync(&tascam->stop_pcm_work):
CPU0 (close) CPU1 (<softirq>)
tascam_pcm_trigger(STOP)
playback_active = 0
schedule_work(&stop_work)
feedback_urb_complete()
/* entered before URBs killed */
tascam_playback_close()
cancel_work_sync(&stop_pcm_work)
schedule_work(&stop_pcm_work) <-- re-armed
In addition, snd_pcm_stop_xrun() does not serialize against
snd_pcm_detach_substream(), because snd_pcm_detach_substream() frees
runtime->status, clears substream->runtime, and frees runtime without
taking pcm_stream_lock.
> @@ -449,8 +452,13 @@ void tascam_stop_pcm_work_handler(struct work_struct *work)
> struct tascam_card *tascam =
> container_of(work, struct tascam_card, stop_pcm_work);
>
> + /* snd_pcm_stop() requires the PCM stream lock and dereferences
> + * substream->runtime unconditionally; after a concurrent close the
> + * runtime is NULL and snd_pcm_pre_stop() oopses. Use
> + * snd_pcm_stop_xrun(), which takes the stream lock itself and
> + * rechecks substream->runtime before touching it. */
> if (tascam->playback_substream)
> - snd_pcm_stop(tascam->playback_substream, SNDRV_PCM_STATE_XRUN);
> + snd_pcm_stop_xrun(tascam->playback_substream);
> if (tascam->capture_substream)
> - snd_pcm_stop(tascam->capture_substream, SNDRV_PCM_STATE_XRUN);
> + snd_pcm_stop_xrun(tascam->capture_substream);
> }
[Severity: Medium]
Can tascam_stop_pcm_work_handler() pass a NULL substream pointer to
snd_pcm_stop_xrun() when racing with tascam_playback_close() or
tascam_capture_close()?
The close callbacks clear tascam->playback_substream and
tascam->capture_substream without a lock before calling
cancel_work_sync(&tascam->stop_pcm_work), while
tascam_stop_pcm_work_handler() reads each field unlocked in the condition
and can reload it when passing the argument to snd_pcm_stop_xrun():
CPU0 (kworker) CPU1 (close)
tascam_stop_pcm_work_handler()
if (tascam->playback_substream)
tascam_playback_close()
tascam->playback_substream = NULL;
cancel_work_sync(&tascam->stop_pcm_work)
snd_pcm_stop_xrun(tascam->playback_substream)
guard(pcm_stream_lock_irqsave)(NULL) <-- NULL pointer dereference
snd_pcm_stop_xrun() immediately dereferences substream when acquiring
pcm_stream_lock_irqsave.
--
Sashiko AI review · https://sashiko.dev/#/patchset/753f2e86.57a.1a212c1052c.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (6 preceding siblings ...)
2026-11-13 12:29 ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
@ 2026-11-22 7:43 ` 徐晗翔
2026-11-22 8:07 ` Takashi Iwai
2026-11-22 7:48 ` sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref) 徐晗翔
` (5 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:43 UTC (permalink / raw)
To: vkoul, perex, tiwai; +Cc: linux-sound, linux-kernel, lgirdwood, broonie
[-- Attachment #1: Type: text/plain, Size: 6864 bytes --]
snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
card->files_list, without taking a persistent card device reference and
without taking a module reference; it even drops the lookup reference
with snd_card_unref() before returning. The ASoC card can therefore be
unbound and freed while the compress fd is still open, after which
ioctl/read/write/poll/close dereference freed struct snd_compr and
snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
kernel with a small test module: open the compress device, call
snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
already reports slab-use-after-free in mutex_lock(&stream->device->lock)
inside snd_compr_ioctl().
This is not a theoretical lost-reference issue. The upstream compress
offload code has an explicit open-file lifetime: snd_card_file_add() plus
try_module_get() at open, a data->list node linked into compr->open_list,
list_del_init() + module_put() + snd_card_file_remove() at free, and a
dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
The current tree removed all of it at the structure level: struct
snd_compr_file no longer has a list node and struct snd_compr no longer
has open_list. Consequently snd_card_disconnect_sync(), which waits for
card->files_list to drain, returns immediately with the compress fd still
open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
frees the objects the fd still points to.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
The only build-time changes were temporary Kconfig prompts to build
snd-compress.ko and snd-rawmidi.ko as modules; no functional source
change was made for this case. The exact version line is in
evidence/kernel-version.txt.
* Root cause and object lifetime
The open path, sound/core/compress_offload.c:75-143, does only:
compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
...
data = kzalloc_obj(*data);
runtime = kzalloc_obj(*runtime);
data->stream.device = compr;
f->private_data = data;
scoped_guard(mutex, &compr->lock)
ret = compr->ops->open(&data->stream);
snd_card_unref(compr->card);
There is no snd_card_file_add(compr->card, f), no
try_module_get(compr->card->module), and no list_add_tail() into an
open list. The structure definitions were changed too:
sound/core/compress_offload.c:44-49 has
struct snd_compr_file {
unsigned long caps;
struct snd_compr_stream stream;
};
while include/sound/compress_driver.h:194-210 has no open_list member
in struct snd_compr.
The free path, sound/core/compress_offload.c:145-170, calls
cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
ops->free() and kfree() -- but no list_del_init(), no module_put() and
no snd_card_file_remove().
The disconnect callback, sound/core/compress_offload.c:1432-1447, is
only:
compr = device->device_data;
snd_unregister_device(compr->dev);
return 0;
It does not walk open streams, does not stop them, does not set
SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
Upstream by contrast has all of these: snd_card_file_add() and
try_module_get() in snd_compr_open(), data->list linked into
compr->open_list, matching list_del_init()/module_put()/
snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
takes compr->lock, stops active streams and sets DISCONNECTED.
* Why card removal reaches the freed objects
The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
(sound/core/init.c:571-582) waits under files_lock for files_list to
become empty. A compress fd is not in files_list, so this wait is a
no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
device_unregister(rtd->dev), while the fd still has
data->stream.device = compr and data->stream.private_data = rtd.
snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
snd_compr_poll() all begin with
guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
freed struct snd_compr before looking at stream->runtime.
* Trigger model
- A compress offload device must exist (real ASoC compress driver, or
the attached test module);
- a user with access to /dev/snd/comprC*D* opens it;
- the card is removed/unbound (driver unbind, card unregister, module
unload, or the test module's free parameter);
- the same fd is used again (ioctl/read/write/poll) or closed.
The card-removal step normally needs a privileged action, but the fd
and the removal can belong to different processes and the kernel must
not free objects that an open file still references. No hardware is
required for the reproducer.
* Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
sndcore_compress.c registers one card with one compress device and a
minimal struct snd_compr_ops; the card private_free function kfree()s
the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
module's "free" parameter to call snd_card_free(), then calls ioctl()
on the stale fd.
Observed (evidence/mr03-kasan-uaf.log):
free: calling snd_card_free(...)
BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
Write of size 8 at addr ... by task sndcore_test/88
Call Trace:
mutex_lock+0x72/0xe0
snd_compr_ioctl+0xd2/0xff0 [snd_compress]
...
BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
KASAN bug count: 2
The bug count is the number of KASAN reports collected in that run;
the first report is the mutex_lock() inside the ioctl entry.
* Suggested direction
Restore the upstream lifetime in one series:
- snd_compr_open(): snd_card_file_add(), try_module_get(), link
data->list into compr->open_list;
- snd_compr_free(): list_del_init(), module_put() and
snd_card_file_remove(), with the error paths undoing in reverse;
- snd_compress_dev_disconnect(): walk compr->open_list under
compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
- restore struct snd_compr_file.list and struct snd_compr.open_list.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_compress.c --]
[-- Type: text/plain, Size: 2050 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/compress_driver.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static struct snd_compr *compr;
static int c_open(struct snd_compr_stream *stream) { return 0; }
static int c_free(struct snd_compr_stream *stream) { return 0; }
static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
static struct snd_compr_ops compr_ops = {
.open = c_open,
.free = c_free,
.trigger = c_trigger,
};
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
pr_info("free: calling snd_card_free(%p)\n", card);
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
static void card_private_free(struct snd_card *c)
{
pr_info("card private_free: kfree(compr=%p)\n", compr);
kfree(compr);
compr = NULL;
}
static int __init sndcore_compress_init(void)
{
int err;
err = sndcore_card_new(&card, "sndcore_compress");
if (err < 0)
return err;
compr = kzalloc(sizeof(*compr), GFP_KERNEL);
if (!compr) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return -ENOMEM;
}
compr->ops = &compr_ops;
card->private_free = card_private_free;
err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
if (err < 0) {
kfree(compr);
compr = NULL;
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("compress card registered\n");
return 0;
}
static void __exit sndcore_compress_exit(void)
{
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_compress_init);
module_exit(sndcore_compress_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
2026-11-22 7:43 ` sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF) 徐晗翔
@ 2026-11-22 8:07 ` Takashi Iwai
2026-11-25 12:44 ` [PATCH] Re: " 徐晗翔
0 siblings, 1 reply; 41+ messages in thread
From: Takashi Iwai @ 2026-11-22 8:07 UTC (permalink / raw)
To: 徐晗翔
Cc: vkoul, perex, tiwai, linux-sound, linux-kernel, lgirdwood,
broonie
On Sun, 22 Nov 2026 08:43:32 +0100,
徐晗翔 wrote:
>
> snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
> card->files_list, without taking a persistent card device reference and
> without taking a module reference; it even drops the lookup reference
> with snd_card_unref() before returning. The ASoC card can therefore be
> unbound and freed while the compress fd is still open, after which
> ioctl/read/write/poll/close dereference freed struct snd_compr and
> snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
> kernel with a small test module: open the compress device, call
> snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
> already reports slab-use-after-free in mutex_lock(&stream->device->lock)
> inside snd_compr_ioctl().
>
> This is not a theoretical lost-reference issue. The upstream compress
> offload code has an explicit open-file lifetime: snd_card_file_add() plus
> try_module_get() at open, a data->list node linked into compr->open_list,
> list_del_init() + module_put() + snd_card_file_remove() at free, and a
> dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
> PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
> The current tree removed all of it at the structure level: struct
> snd_compr_file no longer has a list node and struct snd_compr no longer
> has open_list. Consequently snd_card_disconnect_sync(), which waits for
> card->files_list to drain, returns immediately with the compress fd still
> open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
> frees the objects the fd still points to.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
> The only build-time changes were temporary Kconfig prompts to build
> snd-compress.ko and snd-rawmidi.ko as modules; no functional source
> change was made for this case. The exact version line is in
> evidence/kernel-version.txt.
>
> * Root cause and object lifetime
>
> The open path, sound/core/compress_offload.c:75-143, does only:
>
> compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
> ...
> data = kzalloc_obj(*data);
> runtime = kzalloc_obj(*runtime);
> data->stream.device = compr;
> f->private_data = data;
> scoped_guard(mutex, &compr->lock)
> ret = compr->ops->open(&data->stream);
> snd_card_unref(compr->card);
>
> There is no snd_card_file_add(compr->card, f), no
> try_module_get(compr->card->module), and no list_add_tail() into an
> open list. The structure definitions were changed too:
> sound/core/compress_offload.c:44-49 has
>
> struct snd_compr_file {
> unsigned long caps;
> struct snd_compr_stream stream;
> };
>
> while include/sound/compress_driver.h:194-210 has no open_list member
> in struct snd_compr.
>
> The free path, sound/core/compress_offload.c:145-170, calls
> cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
> ops->free() and kfree() -- but no list_del_init(), no module_put() and
> no snd_card_file_remove().
>
> The disconnect callback, sound/core/compress_offload.c:1432-1447, is
> only:
>
> compr = device->device_data;
> snd_unregister_device(compr->dev);
> return 0;
>
> It does not walk open streams, does not stop them, does not set
> SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
>
> Upstream by contrast has all of these: snd_card_file_add() and
> try_module_get() in snd_compr_open(), data->list linked into
> compr->open_list, matching list_del_init()/module_put()/
> snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
> takes compr->lock, stops active streams and sets DISCONNECTED.
>
> * Why card removal reaches the freed objects
>
> The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
> soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
> then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
> snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
> (sound/core/init.c:571-582) waits under files_lock for files_list to
> become empty. A compress fd is not in files_list, so this wait is a
> no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
> device_unregister(rtd->dev), while the fd still has
> data->stream.device = compr and data->stream.private_data = rtd.
> snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
> snd_compr_poll() all begin with
> guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
> freed struct snd_compr before looking at stream->runtime.
>
> * Trigger model
>
> - A compress offload device must exist (real ASoC compress driver, or
> the attached test module);
> - a user with access to /dev/snd/comprC*D* opens it;
> - the card is removed/unbound (driver unbind, card unregister, module
> unload, or the test module's free parameter);
> - the same fd is used again (ioctl/read/write/poll) or closed.
>
> The card-removal step normally needs a privileged action, but the fd
> and the removal can belong to different processes and the kernel must
> not free objects that an open file still references. No hardware is
> required for the reproducer.
>
> * Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
>
> sndcore_compress.c registers one card with one compress device and a
> minimal struct snd_compr_ops; the card private_free function kfree()s
> the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
> userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
> module's "free" parameter to call snd_card_free(), then calls ioctl()
> on the stale fd.
>
> Observed (evidence/mr03-kasan-uaf.log):
>
> free: calling snd_card_free(...)
> BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
> Write of size 8 at addr ... by task sndcore_test/88
> Call Trace:
> mutex_lock+0x72/0xe0
> snd_compr_ioctl+0xd2/0xff0 [snd_compress]
> ...
> BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
> snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
> KASAN bug count: 2
>
> The bug count is the number of KASAN reports collected in that run;
> the first report is the mutex_lock() inside the ioctl entry.
>
>
>
> * Suggested direction
>
> Restore the upstream lifetime in one series:
> - snd_compr_open(): snd_card_file_add(), try_module_get(), link
> data->list into compr->open_list;
> - snd_compr_free(): list_del_init(), module_put() and
> snd_card_file_remove(), with the error paths undoing in reverse;
> - snd_compress_dev_disconnect(): walk compr->open_list under
> compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
> SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
> - restore struct snd_compr_file.list and struct snd_compr.open_list.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
> // SPDX-License-Identifier: GPL-2.0
> #define _GNU_SOURCE
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #include <fcntl.h>
> #include <unistd.h>
> #include <errno.h>
> #include <pthread.h>
> #include <sys/ioctl.h>
> #include <sound/asound.h>
>
> static int write_free(const char *mod)
> {
> char path[256];
> int fd;
>
> snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
> fd = open(path, O_WRONLY);
> if (fd < 0) {
> fprintf(stderr, "open %s: %s\n", path, strerror(errno));
> return -1;
> }
> if (write(fd, "1\n", 2) != 2)
> fprintf(stderr, "write %s: %s\n", path, strerror(errno));
> close(fd);
> return 0;
> }
>
> static int do_hwdep(void)
> {
> struct snd_hwdep_dsp_image img;
> int fd;
>
> fd = open("/dev/snd/hwC0D0", O_RDWR);
> if (fd < 0) {
> fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> return 1;
> }
> memset(&img, 0, sizeof(img));
> img.index = 0;
> img.length = 0;
> img.image = 0;
> for (int i = 0; i < 4; i++) {
> if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
> fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
> }
> close(fd);
> printf("HWDEP: ioctl done (max_active should be >= 2)\n");
> sleep(1);
> return 0;
> }
>
> static void *hwdep_thread(void *arg)
> {
> int fd = *(int *)arg;
> struct snd_hwdep_dsp_image img;
>
> memset(&img, 0, sizeof(img));
> img.index = 0;
> ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
> return NULL;
> }
>
> static int do_hwdep_race(void)
> {
> pthread_t th[4];
> int fd;
>
> fd = open("/dev/snd/hwC0D0", O_RDWR);
> if (fd < 0) {
> fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> return 1;
> }
> for (int i = 0; i < 4; i++)
> pthread_create(&th[i], NULL, hwdep_thread, &fd);
> for (int i = 0; i < 4; i++)
> pthread_join(th[i], NULL);
> close(fd);
> printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
> sleep(1);
> return 0;
> }
>
> static int do_compress(void)
> {
> int fd;
>
> fd = open("/dev/snd/comprC0D0", O_WRONLY);
> if (fd < 0) {
> fprintf(stderr, "open compress: %s\n", strerror(errno));
> return 1;
> }
> printf("COMPRESS: fd open, freeing card\n");
> write_free("sndcore_compress");
> printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
> if (ioctl(fd, 0x4300, 0) < 0)
> fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
> printf("COMPRESS: ioctl returned without KASAN report\n");
> close(fd);
> sleep(1);
> return 0;
> }
>
> static int do_rawmidi(void)
> {
> int fd;
>
> fd = open("/dev/snd/midiC0D0", O_RDONLY);
> if (fd < 0) {
> fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
> return 1;
> }
> printf("RAWMIDI: fd open, letting flood thread run\n");
> sleep(2);
> printf("RAWMIDI: closing (trigger/cancel/free window)\n");
> close(fd);
> sleep(3);
> printf("RAWMIDI: close returned, freeing card\n");
> write_free("sndcore_rawmidi");
> sleep(1);
> return 0;
> }
>
> int main(int argc, char **argv)
> {
> if (argc < 2) {
> fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
> return 2;
> }
> if (!strcmp(argv[1], "jackfree"))
> return write_free("sndcore_jack");
> if (!strcmp(argv[1], "compress"))
> return do_compress();
> if (!strcmp(argv[1], "rawmidi"))
> return do_rawmidi();
> if (!strcmp(argv[1], "hwdep"))
> return do_hwdep();
> if (!strcmp(argv[1], "hwdep-race"))
> return do_hwdep_race();
> fprintf(stderr, "unknown mode %s\n", argv[1]);
> return 2;
> }
>
> // SPDX-License-Identifier: GPL-2.0
> #include <linux/module.h>
> #include <linux/kernel.h>
> #include <linux/slab.h>
> #include <sound/core.h>
> #include <sound/compress_driver.h>
> #include "sndcore_parent.h"
>
> static struct snd_card *card;
> static struct snd_compr *compr;
>
> static int c_open(struct snd_compr_stream *stream) { return 0; }
> static int c_free(struct snd_compr_stream *stream) { return 0; }
> static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
>
> static struct snd_compr_ops compr_ops = {
> .open = c_open,
> .free = c_free,
> .trigger = c_trigger,
> };
>
> static int free_set(const char *val, const struct kernel_param *kp)
> {
> if (card) {
> pr_info("free: calling snd_card_free(%p)\n", card);
> snd_card_free(card);
> card = NULL;
> }
> return 0;
> }
> static const struct kernel_param_ops free_ops = { .set = free_set };
> module_param_cb(free, &free_ops, NULL, 0200);
>
> static void card_private_free(struct snd_card *c)
> {
> pr_info("card private_free: kfree(compr=%p)\n", compr);
> kfree(compr);
> compr = NULL;
> }
>
> static int __init sndcore_compress_init(void)
> {
> int err;
>
> err = sndcore_card_new(&card, "sndcore_compress");
> if (err < 0)
> return err;
>
> compr = kzalloc(sizeof(*compr), GFP_KERNEL);
> if (!compr) {
> snd_card_free(card);
> card = NULL;
> sndcore_parent_put();
> return -ENOMEM;
> }
> compr->ops = &compr_ops;
> card->private_free = card_private_free;
>
> err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
> if (err < 0) {
> kfree(compr);
> compr = NULL;
> snd_card_free(card);
> card = NULL;
> sndcore_parent_put();
> return err;
> }
> err = snd_card_register(card);
> if (err < 0) {
> snd_card_free(card);
> card = NULL;
> sndcore_parent_put();
> return err;
> }
> pr_info("compress card registered\n");
> return 0;
> }
>
> static void __exit sndcore_compress_exit(void)
> {
> if (card) {
> snd_card_free(card);
> card = NULL;
> }
> sndcore_parent_put();
> }
>
> module_init(sndcore_compress_init);
> module_exit(sndcore_compress_exit);
> MODULE_LICENSE("GPL");
> MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
Thanks for the report.
But, as I already requested in your previous reports, could you rather
submit a fix patch along with the report? I suppose you're working
with AI, so it's just a matter of asking it to the model.
Takashi
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
2026-11-22 8:07 ` Takashi Iwai
@ 2026-11-25 12:44 ` 徐晗翔
0 siblings, 0 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:44 UTC (permalink / raw)
To: Takashi Iwai
Cc: vkoul, perex, tiwai, linux-sound, linux-kernel, lgirdwood,
broonie
snd_compr_open() dropped the lookup reference before returning and
took neither a card reference nor a module reference, and kept no
per-fd node: the card could be unbound and freed while a compress
fd was still open, and the next ioctl/read/write/poll/close
dereferenced freed struct snd_compr and snd_soc_pcm_runtime
objects (KASAN slab-use-after-free in snd_compr_ioctl()).
Restore the open-file lifetime: snd_card_file_add() (which also
puts the fd on card->files_list so snd_card_disconnect_sync() waits
for it) plus try_module_get() at open; a data->list node linked into
compr->open_list under compr->lock; list_del_init() + module_put() +
snd_card_file_remove() at free; and a dev_disconnect callback that
walks open_list, stops RUNNING/DRAINING/PAUSED streams, sets
SNDRV_PCM_STATE_DISCONNECTED and wakes the poll/read waiters.
---
sound/core/compress_offload.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
include/sound/compress_driver.h | 3 +++
2 files changed, 70 insertions(+)
diff --git a/sound/core/compress_offload.c b/sound/core/compress_offload.c
--- a/sound/core/compress_offload.c
+++ b/sound/core/compress_offload.c
@@ -44,6 +44,10 @@
struct snd_compr_file {
unsigned long caps;
struct snd_compr_stream stream;
+ /* open lifetime: linked into compr->open_list so the card
+ * disconnect callback can find and stop this stream, and so the
+ * fd pins the card and the module while it is open */
+ struct list_head list;
};
static void error_delayed_work(struct work_struct *work);
@@ -137,7 +141,38 @@
if (ret) {
kfree(runtime);
kfree(data);
+ snd_card_unref(compr->card);
+ return ret;
}
+
+ /* Open lifetime: pin the card against removal (snd_card_file_add
+ * also links the file into card->files_list, so the card teardown
+ * waits for this fd) and pin the module, and make the fd visible
+ * to the disconnect callback via compr->open_list. Without this
+ * the card could be unbound and freed while the fd stays open,
+ * leaving ioctl/read/write/poll/close to dereference freed
+ * snd_compr / snd_soc_pcm_runtime objects. */
+ INIT_LIST_HEAD(&data->list);
+ ret = snd_card_file_add(compr->card, f);
+ if (ret)
+ goto err_card_file;
+ if (!try_module_get(compr->card->module)) {
+ ret = -ENODEV;
+ goto err_module;
+ }
+ scoped_guard(mutex, &compr->lock)
+ list_add_tail(&data->list, &compr->open_list);
+
+ snd_card_unref(compr->card);
+ return ret;
+
+ err_module:
+ snd_card_file_remove(compr->card, f);
+ err_card_file:
+ scoped_guard(mutex, &compr->lock)
+ data->stream.ops->free(&data->stream);
+ kfree(runtime);
+ kfree(data);
snd_card_unref(compr->card);
return ret;
}
@@ -145,10 +180,16 @@
static int snd_compr_free(struct inode *inode, struct file *f)
{
struct snd_compr_file *data = f->private_data;
+ struct snd_compr *compr = data->stream.device;
struct snd_compr_runtime *runtime = data->stream.runtime;
cancel_delayed_work_sync(&data->stream.error_work);
+ /* unlink from the open list first, so the disconnect callback
+ * cannot walk this stream while it is being freed */
+ scoped_guard(mutex, &compr->lock)
+ list_del_init(&data->list);
+
switch (runtime->state) {
case SNDRV_PCM_STATE_RUNNING:
case SNDRV_PCM_STATE_DRAINING:
@@ -166,6 +207,11 @@
kfree(data->stream.runtime->buffer);
kfree(data->stream.runtime);
kfree(data);
+
+ /* drop the references taken at open; the file object is released
+ * by the caller afterwards, so this is the last possible point */
+ module_put(compr->card->module);
+ snd_card_file_remove(compr->card, f);
return 0;
}
@@ -1432,8 +1478,28 @@
static int snd_compress_dev_disconnect(struct snd_device *device)
{
struct snd_compr *compr;
+ struct snd_compr_file *compr_file;
+ struct snd_compr_stream *stream;
compr = device->device_data;
+
+ /* stop the streams of still-open fds: the card core disconnect no
+ * longer waits only for the files_list (which our fds are on via
+ * snd_card_file_add()), but the streams must also be told that the
+ * device went away, or a blocked read/poll would never wake up */
+ scoped_guard(mutex, &compr->lock) {
+ list_for_each_entry(compr_file, &compr->open_list, list) {
+ stream = &compr_file->stream;
+ if (stream->runtime->state != SNDRV_PCM_STATE_RUNNING &&
+ stream->runtime->state != SNDRV_PCM_STATE_DRAINING &&
+ stream->runtime->state != SNDRV_PCM_STATE_PAUSED)
+ continue;
+ compr->ops->trigger(stream, SNDRV_PCM_TRIGGER_STOP);
+ stream->runtime->state = SNDRV_PCM_STATE_DISCONNECTED;
+ wake_up(&stream->runtime->sleep);
+ }
+ }
+
snd_unregister_device(compr->dev);
return 0;
}
@@ -1541,6 +1607,7 @@
compr->device = device;
compr->direction = dirn;
mutex_init(&compr->lock);
+ INIT_LIST_HEAD(&compr->open_list);
snd_compress_set_id(compr, id);
diff --git a/include/sound/compress_driver.h b/include/sound/compress_driver.h
--- a/include/sound/compress_driver.h
+++ b/include/sound/compress_driver.h
@@ -188,6 +188,8 @@
* @card: sound card pointer
* @direction: Playback or capture direction
* @lock: device lock
+ * @open_list: list of open fds, protected by @lock; the disconnect
+ * callback walks it to stop the streams of files that are still open
* @device: device id
* @use_pause_in_draining: allow pause in draining, true when set
*/
@@ -199,6 +201,7 @@
struct snd_card *card;
unsigned int direction;
struct mutex lock;
+ struct list_head open_list; /* list of open fds (snd_compr_file.list) */
int device;
bool use_pause_in_draining;
#ifdef CONFIG_SND_VERBOSE_PROCFS
> -----原始邮件-----
> 发件人: "Takashi Iwai" <tiwai@suse.de>
> 发送时间:2026-11-22 16:07:00 (星期日)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> 抄送: vkoul@kernel.org, perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org, lgirdwood@gmail.com, broonie@kernel.org
> 主题: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
>
> On Sun, 22 Nov 2026 08:43:32 +0100,
> 徐晗翔 wrote:
> >
> > snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
> > card->files_list, without taking a persistent card device reference and
> > without taking a module reference; it even drops the lookup reference
> > with snd_card_unref() before returning. The ASoC card can therefore be
> > unbound and freed while the compress fd is still open, after which
> > ioctl/read/write/poll/close dereference freed struct snd_compr and
> > snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
> > kernel with a small test module: open the compress device, call
> > snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
> > already reports slab-use-after-free in mutex_lock(&stream->device->lock)
> > inside snd_compr_ioctl().
> >
> > This is not a theoretical lost-reference issue. The upstream compress
> > offload code has an explicit open-file lifetime: snd_card_file_add() plus
> > try_module_get() at open, a data->list node linked into compr->open_list,
> > list_del_init() + module_put() + snd_card_file_remove() at free, and a
> > dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
> > PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
> > The current tree removed all of it at the structure level: struct
> > snd_compr_file no longer has a list node and struct snd_compr no longer
> > has open_list. Consequently snd_card_disconnect_sync(), which waits for
> > card->files_list to drain, returns immediately with the compress fd still
> > open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
> > frees the objects the fd still points to.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> > vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
> > The only build-time changes were temporary Kconfig prompts to build
> > snd-compress.ko and snd-rawmidi.ko as modules; no functional source
> > change was made for this case. The exact version line is in
> > evidence/kernel-version.txt.
> >
> > * Root cause and object lifetime
> >
> > The open path, sound/core/compress_offload.c:75-143, does only:
> >
> > compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
> > ...
> > data = kzalloc_obj(*data);
> > runtime = kzalloc_obj(*runtime);
> > data->stream.device = compr;
> > f->private_data = data;
> > scoped_guard(mutex, &compr->lock)
> > ret = compr->ops->open(&data->stream);
> > snd_card_unref(compr->card);
> >
> > There is no snd_card_file_add(compr->card, f), no
> > try_module_get(compr->card->module), and no list_add_tail() into an
> > open list. The structure definitions were changed too:
> > sound/core/compress_offload.c:44-49 has
> >
> > struct snd_compr_file {
> > unsigned long caps;
> > struct snd_compr_stream stream;
> > };
> >
> > while include/sound/compress_driver.h:194-210 has no open_list member
> > in struct snd_compr.
> >
> > The free path, sound/core/compress_offload.c:145-170, calls
> > cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
> > ops->free() and kfree() -- but no list_del_init(), no module_put() and
> > no snd_card_file_remove().
> >
> > The disconnect callback, sound/core/compress_offload.c:1432-1447, is
> > only:
> >
> > compr = device->device_data;
> > snd_unregister_device(compr->dev);
> > return 0;
> >
> > It does not walk open streams, does not stop them, does not set
> > SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
> >
> > Upstream by contrast has all of these: snd_card_file_add() and
> > try_module_get() in snd_compr_open(), data->list linked into
> > compr->open_list, matching list_del_init()/module_put()/
> > snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
> > takes compr->lock, stops active streams and sets DISCONNECTED.
> >
> > * Why card removal reaches the freed objects
> >
> > The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
> > soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
> > then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
> > snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
> > (sound/core/init.c:571-582) waits under files_lock for files_list to
> > become empty. A compress fd is not in files_list, so this wait is a
> > no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
> > device_unregister(rtd->dev), while the fd still has
> > data->stream.device = compr and data->stream.private_data = rtd.
> > snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
> > snd_compr_poll() all begin with
> > guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
> > freed struct snd_compr before looking at stream->runtime.
> >
> > * Trigger model
> >
> > - A compress offload device must exist (real ASoC compress driver, or
> > the attached test module);
> > - a user with access to /dev/snd/comprC*D* opens it;
> > - the card is removed/unbound (driver unbind, card unregister, module
> > unload, or the test module's free parameter);
> > - the same fd is used again (ioctl/read/write/poll) or closed.
> >
> > The card-removal step normally needs a privileged action, but the fd
> > and the removal can belong to different processes and the kernel must
> > not free objects that an open file still references. No hardware is
> > required for the reproducer.
> >
> > * Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
> >
> > sndcore_compress.c registers one card with one compress device and a
> > minimal struct snd_compr_ops; the card private_free function kfree()s
> > the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
> > userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
> > module's "free" parameter to call snd_card_free(), then calls ioctl()
> > on the stale fd.
> >
> > Observed (evidence/mr03-kasan-uaf.log):
> >
> > free: calling snd_card_free(...)
> > BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
> > Write of size 8 at addr ... by task sndcore_test/88
> > Call Trace:
> > mutex_lock+0x72/0xe0
> > snd_compr_ioctl+0xd2/0xff0 [snd_compress]
> > ...
> > BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
> > snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
> > KASAN bug count: 2
> >
> > The bug count is the number of KASAN reports collected in that run;
> > the first report is the mutex_lock() inside the ioctl entry.
> >
> >
> >
> > * Suggested direction
> >
> > Restore the upstream lifetime in one series:
> > - snd_compr_open(): snd_card_file_add(), try_module_get(), link
> > data->list into compr->open_list;
> > - snd_compr_free(): list_del_init(), module_put() and
> > snd_card_file_remove(), with the error paths undoing in reverse;
> > - snd_compress_dev_disconnect(): walk compr->open_list under
> > compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
> > SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
> > - restore struct snd_compr_file.list and struct snd_compr.open_list.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
> > // SPDX-License-Identifier: GPL-2.0
> > #define _GNU_SOURCE
> > #include <stdio.h>
> > #include <stdlib.h>
> > #include <string.h>
> > #include <fcntl.h>
> > #include <unistd.h>
> > #include <errno.h>
> > #include <pthread.h>
> > #include <sys/ioctl.h>
> > #include <sound/asound.h>
> >
> > static int write_free(const char *mod)
> > {
> > char path[256];
> > int fd;
> >
> > snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
> > fd = open(path, O_WRONLY);
> > if (fd < 0) {
> > fprintf(stderr, "open %s: %s\n", path, strerror(errno));
> > return -1;
> > }
> > if (write(fd, "1\n", 2) != 2)
> > fprintf(stderr, "write %s: %s\n", path, strerror(errno));
> > close(fd);
> > return 0;
> > }
> >
> > static int do_hwdep(void)
> > {
> > struct snd_hwdep_dsp_image img;
> > int fd;
> >
> > fd = open("/dev/snd/hwC0D0", O_RDWR);
> > if (fd < 0) {
> > fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> > return 1;
> > }
> > memset(&img, 0, sizeof(img));
> > img.index = 0;
> > img.length = 0;
> > img.image = 0;
> > for (int i = 0; i < 4; i++) {
> > if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
> > fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
> > }
> > close(fd);
> > printf("HWDEP: ioctl done (max_active should be >= 2)\n");
> > sleep(1);
> > return 0;
> > }
> >
> > static void *hwdep_thread(void *arg)
> > {
> > int fd = *(int *)arg;
> > struct snd_hwdep_dsp_image img;
> >
> > memset(&img, 0, sizeof(img));
> > img.index = 0;
> > ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
> > return NULL;
> > }
> >
> > static int do_hwdep_race(void)
> > {
> > pthread_t th[4];
> > int fd;
> >
> > fd = open("/dev/snd/hwC0D0", O_RDWR);
> > if (fd < 0) {
> > fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> > return 1;
> > }
> > for (int i = 0; i < 4; i++)
> > pthread_create(&th[i], NULL, hwdep_thread, &fd);
> > for (int i = 0; i < 4; i++)
> > pthread_join(th[i], NULL);
> > close(fd);
> > printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
> > sleep(1);
> > return 0;
> > }
> >
> > static int do_compress(void)
> > {
> > int fd;
> >
> > fd = open("/dev/snd/comprC0D0", O_WRONLY);
> > if (fd < 0) {
> > fprintf(stderr, "open compress: %s\n", strerror(errno));
> > return 1;
> > }
> > printf("COMPRESS: fd open, freeing card\n");
> > write_free("sndcore_compress");
> > printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
> > if (ioctl(fd, 0x4300, 0) < 0)
> > fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
> > printf("COMPRESS: ioctl returned without KASAN report\n");
> > close(fd);
> > sleep(1);
> > return 0;
> > }
> >
> > static int do_rawmidi(void)
> > {
> > int fd;
> >
> > fd = open("/dev/snd/midiC0D0", O_RDONLY);
> > if (fd < 0) {
> > fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
> > return 1;
> > }
> > printf("RAWMIDI: fd open, letting flood thread run\n");
> > sleep(2);
> > printf("RAWMIDI: closing (trigger/cancel/free window)\n");
> > close(fd);
> > sleep(3);
> > printf("RAWMIDI: close returned, freeing card\n");
> > write_free("sndcore_rawmidi");
> > sleep(1);
> > return 0;
> > }
> >
> > int main(int argc, char **argv)
> > {
> > if (argc < 2) {
> > fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
> > return 2;
> > }
> > if (!strcmp(argv[1], "jackfree"))
> > return write_free("sndcore_jack");
> > if (!strcmp(argv[1], "compress"))
> > return do_compress();
> > if (!strcmp(argv[1], "rawmidi"))
> > return do_rawmidi();
> > if (!strcmp(argv[1], "hwdep"))
> > return do_hwdep();
> > if (!strcmp(argv[1], "hwdep-race"))
> > return do_hwdep_race();
> > fprintf(stderr, "unknown mode %s\n", argv[1]);
> > return 2;
> > }
> >
> > // SPDX-License-Identifier: GPL-2.0
> > #include <linux/module.h>
> > #include <linux/kernel.h>
> > #include <linux/slab.h>
> > #include <sound/core.h>
> > #include <sound/compress_driver.h>
> > #include "sndcore_parent.h"
> >
> > static struct snd_card *card;
> > static struct snd_compr *compr;
> >
> > static int c_open(struct snd_compr_stream *stream) { return 0; }
> > static int c_free(struct snd_compr_stream *stream) { return 0; }
> > static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
> >
> > static struct snd_compr_ops compr_ops = {
> > .open = c_open,
> > .free = c_free,
> > .trigger = c_trigger,
> > };
> >
> > static int free_set(const char *val, const struct kernel_param *kp)
> > {
> > if (card) {
> > pr_info("free: calling snd_card_free(%p)\n", card);
> > snd_card_free(card);
> > card = NULL;
> > }
> > return 0;
> > }
> > static const struct kernel_param_ops free_ops = { .set = free_set };
> > module_param_cb(free, &free_ops, NULL, 0200);
> >
> > static void card_private_free(struct snd_card *c)
> > {
> > pr_info("card private_free: kfree(compr=%p)\n", compr);
> > kfree(compr);
> > compr = NULL;
> > }
> >
> > static int __init sndcore_compress_init(void)
> > {
> > int err;
> >
> > err = sndcore_card_new(&card, "sndcore_compress");
> > if (err < 0)
> > return err;
> >
> > compr = kzalloc(sizeof(*compr), GFP_KERNEL);
> > if (!compr) {
> > snd_card_free(card);
> > card = NULL;
> > sndcore_parent_put();
> > return -ENOMEM;
> > }
> > compr->ops = &compr_ops;
> > card->private_free = card_private_free;
> >
> > err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
> > if (err < 0) {
> > kfree(compr);
> > compr = NULL;
> > snd_card_free(card);
> > card = NULL;
> > sndcore_parent_put();
> > return err;
> > }
> > err = snd_card_register(card);
> > if (err < 0) {
> > snd_card_free(card);
> > card = NULL;
> > sndcore_parent_put();
> > return err;
> > }
> > pr_info("compress card registered\n");
> > return 0;
> > }
> >
> > static void __exit sndcore_compress_exit(void)
> > {
> > if (card) {
> > snd_card_free(card);
> > card = NULL;
> > }
> > sndcore_parent_put();
> > }
> >
> > module_init(sndcore_compress_init);
> > module_exit(sndcore_compress_exit);
> > MODULE_LICENSE("GPL");
> > MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
>
> Thanks for the report.
>
> But, as I already requested in your previous reports, could you rather
> submit a fix patch along with the report? I suppose you're working
> with AI, so it's just a matter of asking it to the model.
>
>
> Takashi
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (7 preceding siblings ...)
2026-11-22 7:43 ` sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF) 徐晗翔
@ 2026-11-22 7:48 ` 徐晗翔
2026-11-24 9:39 ` Sreeraj S Kurup
2026-11-22 7:50 ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
` (4 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel, lgirdwood, broonie
[-- Attachment #1: Type: text/plain, Size: 6270 bytes --]
snd_jack_kctl_new() publishes a new snd_kcontrol with snd_ctl_add() and
only then allocates the private struct snd_jack_kctl. If that allocation
fails, the error path calls snd_ctl_free_one(kctl) although the control
is still linked in card->controls and card->ctl_hash; snd_ctl_free_one()
does not take controls_rwsem, does not list_del() and does not
remove_hash_entries(). The result is a freed snd_kcontrol that remains
reachable from the card's control list and hash table, so a concurrent
control read (snd_ctl_elem_list(), or the lockless fast path of
snd_ctl_find_id()) can read freed memory and card teardown
(snd_ctl_dev_free() -> __snd_ctl_remove()) will list_del()/kfree() it
again. Upstream's error branch is snd_ctl_remove(card, kctl), not
snd_ctl_free_one(); this tree changed exactly that line.
The same failure-rollback bug has a deterministic companion path:
snd_jack_new() can fail after snd_ctl_add() has already published the
kcontrol (for example, when its subsequent kstrdup() of the jack id
fails), and it also does not undo the publication. On card teardown the
kcontrol's private_free function then runs snd_jack_kctl_private_free()
on a zero-initialized jack_kctl->list and executes list_del() on the
zero page. I reproduced that companion path on Linux 7.3 with KASAN and
a small test module: snd_jack_new() with a 64 MB id returns -ENOMEM after
publishing the kcontrol, and snd_card_free() reports a
null-ptr-deref in snd_jack_kctl_private_free() from
__snd_ctl_remove()/snd_ctl_dev_free().
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source tree, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
CONFIG_SND_JACK=y and CONFIG_SND_JACK_INPUT_DEV=y. Version line in
evidence/kernel-version.txt.
* Root cause
sound/core/jack.c:426-456 (snd_jack_kctl_new):
kctl = snd_kctl_jack_new(name, card);
if (!kctl)
return NULL;
err = snd_ctl_add(card, kctl); /* publishes into card->controls */
if (err < 0)
return NULL; /* snd_ctl_add already freed it */
jack_kctl = kzalloc_obj(*jack_kctl);
if (!jack_kctl)
goto error; /* kctl is already published */
...
return jack_kctl;
error:
snd_ctl_free_one(kctl); /* no snd_ctl_remove() */
return NULL;
snd_ctl_free_one() (sound/core/control.c:326-334) only calls
private_free and kfree(); its own comment says "Don't call this after
the control was added to the card." The correct primitive,
snd_ctl_remove() (control.c:621-627) / __snd_ctl_remove()
(control.c:581-601), takes controls_rwsem for writing, removes the
hash entries, list_del()s the node and only then frees the object.
Upstream jack.c has snd_ctl_remove(card, kctl) in this error branch.
The second half is in snd_jack_new() (jack.c:480-570): after
snd_jack_kctl_new() has published the kcontrol, later failures
(jack allocation, jack->id kstrdup, input device allocation,
snd_device_new) return without removing it; the kcontrol stays in
card->controls with snd_jack_kctl_private_free installed but with a
never-linked (zeroed) jack_kctl->list.
* Consequences
- Dangling list/hash node: card->controls still contains kctl and
card->ctl_hash still maps its id to it after kfree(kctl).
- Concurrent reader: snd_ctl_elem_list() walks card->controls under
controls_rwsem and reads kctl->id; snd_ctl_find_id()'s fast path
(CONFIG_SND_CTL_FAST_LOOKUP) does xa_load() and elem_id_matches()
without the lock. Either can read freed memory.
- Card teardown: snd_ctl_dev_free() (control.c:2457-2479) walks
card->controls and calls __snd_ctl_remove() on the freed node:
list_del() on freed memory and a second kfree().
- Companion path: snd_jack_new() failure leaves the kcontrol with a
zeroed jack_kctl->list; the card teardown runs
snd_jack_kctl_private_free() -> list_del(&jack_kctl->list), which
writes to address 0x8 and crashes deterministically.
* Trigger model
Primary MR-02 branch: memory allocation failure of
kzalloc_obj(*jack_kctl) after a successful snd_ctl_add(). This can be
induced by memory pressure or fault injection; once it happens, the
damage is persistent (no concurrency needed for the teardown crash).
A concurrent control read/remove widens the impact to UAF before
teardown.
Companion branch: any snd_jack_new() caller (ASoC jack, HDA, test
module) whose later allocation fails; the failure returns an error to
the driver but leaves the published kcontrol behind.
* Reproducer (attached) and results on 7.3
sndcore_jack.c creates a card and calls snd_jack_new() with a 64 MB id
string; snd_jack_kctl_new() publishes the kcontrol, then kstrdup()
fails with -ENOMEM. sndcore_test.c writes the module's "free"
parameter to trigger snd_card_free(). Observed
(evidence/mr02-kasan-null-deref.log):
snd_jack_new(huge id) returned -12 (expected -ENOMEM)
BUG: KASAN: null-ptr-deref in snd_jack_kctl_private_free+0x44/0x80
Write of size 8 at addr 0000000000000008
Call Trace:
snd_jack_kctl_private_free+0x44/0x80
__snd_ctl_remove+0x106/0x140
snd_ctl_dev_free+0x53/0xb0
__snd_device_free+0x86/0x150
snd_device_free_all+0xaa/0xd0
release_card_device+0x4a/0x120
KASAN bug count: 1
This is the companion failure path, not the exact
kzalloc_obj(*jack_kctl) branch; the latter is covered by the static
analysis above and by the upstream-vs-tree diff (upstream uses
snd_ctl_remove()). I state this distinction explicitly rather than
claiming the exact branch was forced.
* Suggested direction
- In snd_jack_kctl_new(), replace the error-path
snd_ctl_free_one(kctl) with snd_ctl_remove(card, kctl), restoring
the upstream behavior.
- In snd_jack_new(), add rollback for every failure after the
snd_jack_kctl_new() call (remove the kcontrol or allocate all
resources before publishing).
- Optionally add a debug check in snd_ctl_free_one() that the control
is not linked, to catch this class of API misuse.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_jack.c --]
[-- Type: text/plain, Size: 1662 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <sound/core.h>
#include <sound/jack.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
pr_info("free: calling snd_card_free(%p)\n", card);
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
static int __init sndcore_jack_init(void)
{
struct snd_jack *jack = NULL;
char *big;
int err;
err = sndcore_card_new(&card, "sndcore_jack");
if (err < 0)
return err;
big = kvmalloc(64 * 1024 * 1024, GFP_KERNEL);
if (!big) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return -ENOMEM;
}
memset(big, 'A', 64 * 1024 * 1024 - 1);
big[64 * 1024 * 1024 - 1] = 0;
err = snd_jack_new(card, big, SND_JACK_HEADPHONE, &jack, true, false);
pr_info("snd_jack_new(huge id) returned %d (expected -ENOMEM)\n", err);
if (!err)
pr_warn("unexpected success: jack=%p\n", jack);
kvfree(big);
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("card registered, kcontrol is published but jack is NULL\n");
return 0;
}
static void __exit sndcore_jack_exit(void)
{
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_jack_init);
module_exit(sndcore_jack_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-02 jack failure-rollback verifier");
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
2026-11-22 7:48 ` sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref) 徐晗翔
@ 2026-11-24 9:39 ` Sreeraj S Kurup
2026-11-25 12:43 ` 徐晗翔
0 siblings, 1 reply; 41+ messages in thread
From: Sreeraj S Kurup @ 2026-11-24 9:39 UTC (permalink / raw)
To: xuhx; +Cc: broonie, lgirdwood, linux-kernel, linux-sound, perex, tiwai
Hi Hanxiang,
Thanks for the detailed report and the KASAN reproducer.
> The same failure-rollback bug has a deterministic companion path:
> snd_jack_new() can fail after snd_ctl_add() has already published the
> kcontrol (for example, when its subsequent kstrdup() of the jack id
> fails), and it also does not undo the publication.
The companion failure path in snd_jack_new() was already fixed by my upstream commit:
commit ebce20196346906cfa33a84a021ce8f9bd91880c
ALSA: jack: Fix jack control cleanup on error paths
https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/commit/?id=ebce20196346906cfa33a84a021ce8f9bd91880c
The patch initializes jack_kctl->list and routes the failure paths in snd_jack_new() through common
cleanup, ensuring that the previously created kcontrol is removed using snd_ctl_remove().
Could you check whether your reproducer still triggers the issue with this commit applied?
Thanks for reporting this.
Regards,
Sreeraj
^ permalink raw reply [flat|nested] 41+ messages in thread
* Re: Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
2026-11-24 9:39 ` Sreeraj S Kurup
@ 2026-11-25 12:43 ` 徐晗翔
0 siblings, 0 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:43 UTC (permalink / raw)
To: Sreeraj S Kurup
Cc: broonie, lgirdwood, linux-kernel, linux-sound, perex, tiwai
That patch does work, thanks.
> -----原始邮件-----
> 发件人: "Sreeraj S Kurup" <sreekuttan2156239@gmail.com>
> 发送时间:2026-11-24 17:39:42 (星期二)
> 收件人: xuhx@hust.edu.cn
> 抄送: broonie@kernel.org, lgirdwood@gmail.com, linux-kernel@vger.kernel.org, linux-sound@vger.kernel.org, perex@perex.cz, tiwai@suse.com
> 主题: Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
>
> Hi Hanxiang,
>
> Thanks for the detailed report and the KASAN reproducer.
>
> > The same failure-rollback bug has a deterministic companion path:
> > snd_jack_new() can fail after snd_ctl_add() has already published the
> > kcontrol (for example, when its subsequent kstrdup() of the jack id
> > fails), and it also does not undo the publication.
>
> The companion failure path in snd_jack_new() was already fixed by my upstream commit:
>
> commit ebce20196346906cfa33a84a021ce8f9bd91880c
> ALSA: jack: Fix jack control cleanup on error paths
>
> https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/commit/?id=ebce20196346906cfa33a84a021ce8f9bd91880c
>
> The patch initializes jack_kctl->list and routes the failure paths in snd_jack_new() through common
> cleanup, ensuring that the previously created kcontrol is removed using snd_ctl_remove().
>
> Could you check whether your reproducer still triggers the issue with this commit applied?
>
> Thanks for reporting this.
>
> Regards,
> Sreeraj
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (8 preceding siblings ...)
2026-11-22 7:48 ` sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref) 徐晗翔
@ 2026-11-22 7:50 ` 徐晗翔
2026-11-24 14:52 ` Krzysztof Kozlowski
2026-11-22 7:52 ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
` (3 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:50 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 6160 bytes --]
Closing a RawMIDI input stream can leave a work item queued after the
runtime object it uses has been freed. close_substream() calls
snd_rawmidi_input_trigger(substream, 0) first; that function calls the
driver's trigger(0), then cancel_work_sync(&runtime->event_work) -- but
it does not hold substream->lock and it runs while substream->opened is
still 1. Only afterwards does close_substream() take substream->lock,
set opened = 0, call ops->close() and snd_rawmidi_runtime_free(), which
kfree()s struct snd_rawmidi_runtime.
In the window between cancel_work_sync() returning and opened becoming 0
on another CPU, a driver can still call snd_rawmidi_receive(). receive()
takes substream->lock, sees opened == 1, queues data and executes
schedule_work(&runtime->event_work). The work is then pending again, the
runtime is freed, and when the worker runs it dereferences
runtime->event and runtime->substream -- a use-after-free. Upstream
closes this window with a second cancel_work_sync() after opened is
cleared (the comment says "Drain input work queued after the earlier
cancellation"), and also marks the substream disconnected in
snd_rawmidi_dev_disconnect(). Both protections are missing here.
I reproduced the UAF on Linux 7.3 with KASAN. A test module registers a
rawmidi input stream and a kthread keeps calling snd_rawmidi_receive();
the user program opens /dev/snd/midiC0D0, closes it and frees the card.
The close path re-queues event_work after the first cancellation and the
work reports slab-use-after-free in snd_rawmidi_input_event_work()
(16 KASAN reports in the run). To make the timing deterministic I added
verification-only mdelay() calls in the patched snd-rawmidi.ko: 100 ms
after cancel_work_sync() and 3000 ms at the start of the work. They
widen the window but do not change the ordering; the patch is attached
so the claim can be audited and reverted.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source with KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
CONFIG_SND_RAWMIDI=m was enabled for the test; the only functional
source change is the verification-only mdelay instrumentation in
sound/core/rawmidi.c (patch attached). Version line in
evidence/kernel-version.txt.
* Root cause
sound/core/rawmidi.c:216-224:
static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
if (!substream->opened)
return;
substream->ops->trigger(substream, up);
if (!up)
cancel_work_sync(&substream->runtime->event_work);
}
No substream->lock is held across the opened check, trigger and cancel.
sound/core/rawmidi.c:533-565 (close_substream):
if (cleanup) {
if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
snd_rawmidi_input_trigger(substream, 0);
...
}
scoped_guard(spinlock_irq, &substream->lock) {
substream->opened = 0;
substream->append = 0;
}
substream->ops->close(substream);
...
snd_rawmidi_runtime_free(substream); /* kfree(runtime) */
sound/core/rawmidi.c:1146-1218 (snd_rawmidi_receive):
guard(spinlock_irqsave)(&substream->lock);
if (!substream->opened)
return -EBADFD;
...
if (result > 0) {
if (runtime->event)
schedule_work(&runtime->event_work);
...
}
Because receive() serializes with the opened=0 store but not with the
earlier cancel_work_sync(), it can queue the work after cancel and
before opened is cleared. snd_rawmidi_runtime_free() does not cancel
the work and does not re-check it.
Upstream has an additional cancel_work_sync() after opened is cleared
in close_substream(), plus a disconnected flag and cancel in
snd_rawmidi_dev_disconnect(); this tree has neither.
* Trigger model
- An input RawMIDI stream is open and has runtime->event set (the
sequencer's snd_midi_input_event(), or a driver using the RawMIDI
input API);
- the stream is closed while the driver can still deliver input (for
example a serial UART whose receive path checks its own
"input open" mode bit until input_close(), or any driver that calls
snd_rawmidi_receive() from its RX path);
- receive() queues event_work after cancel_work_sync() and before
opened=0; runtime is freed; the worker runs.
The attached test module does not require special hardware: its kthread
plays the role of a driver delivering input.
* Reproducer (attached) and results on 7.3
sndcore_rawmidi.c creates a card + rawmidi input stream, installs a
runtime->event callback and starts a kthread that loops:
reset runtime->avail under substream->lock, then call
snd_rawmidi_receive() with one byte. sndcore_test.c opens
/dev/snd/midiC0D0, sleeps, closes the fd, waits and frees the card.
Observed :
event callback entered n=3 opened=0
BUG: KASAN: slab-use-after-free in snd_rawmidi_input_event_work+0x2d/0x60 [snd_rawmidi]
Workqueue: events snd_rawmidi_input_event_work [snd_rawmidi]
Call Trace:
snd_rawmidi_input_event_work+0x2d/0x60 [snd_rawmidi]
test_event+0x3f/0x60 [sndcore_rawmidi]
process_one_work+...
Allocated by task ...:
open_substream+...
Freed by task ...:
close_substream.part.0+...
Last potentially related work creation:
snd_rawmidi_receive+0x31b/0x5a0 [snd_rawmidi]
flood_fn+...
KASAN bug count: 16
The "opened=0" in the callback is the value observed after the UAF;
the work ran after close, on the freed runtime.
* Suggested direction
- In close_substream(), after opened is cleared, do a second
cancel_work_sync(&runtime->event_work) for the input stream, as
upstream does.
- Restore the per-substream disconnected flag and the receive/trigger
checks, and cancel the work in snd_rawmidi_dev_disconnect().
- Consider taking substream->lock consistently around the opened
check and cancellation, or document the lock ordering.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_rawmidi.c --]
[-- Type: text/plain, Size: 3693 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <sound/core.h>
#include <sound/rawmidi.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static struct snd_rawmidi *rmidi;
static struct task_struct *flood;
static struct snd_rawmidi_substream *in_sub;
static atomic_t events = ATOMIC_INIT(0);
static unsigned char byte = 0x5a;
static int rm_open(struct snd_rawmidi_substream *s) { return 0; }
static int rm_close(struct snd_rawmidi_substream *s) { return 0; }
static void rm_trigger(struct snd_rawmidi_substream *s, int up) { }
static void rm_drain(struct snd_rawmidi_substream *s) { }
static const struct snd_rawmidi_ops rm_ops = {
.open = rm_open,
.close = rm_close,
.trigger = rm_trigger,
.drain = rm_drain,
};
static void test_event(struct snd_rawmidi_substream *s)
{
int n = atomic_inc_return(&events);
if (n < 8)
pr_info("event callback entered n=%d opened=%d\n", n, s->opened);
}
static int flood_fn(void *unused)
{
int i;
in_sub = list_first_entry(&rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substreams,
struct snd_rawmidi_substream, list);
for (i = 0; i < 4000 && !kthread_should_stop(); i++) {
if (READ_ONCE(in_sub->opened))
break;
msleep(5);
}
if (!READ_ONCE(in_sub->opened))
return 0;
if (in_sub->runtime)
in_sub->runtime->event = test_event;
pr_info("flood start: opened=%d runtime=%p\n", in_sub->opened, in_sub->runtime);
while (!kthread_should_stop() && READ_ONCE(in_sub->opened)) {
unsigned long flags;
if (in_sub->runtime) {
spin_lock_irqsave(&in_sub->lock, flags);
if (in_sub->runtime)
in_sub->runtime->avail = 0;
spin_unlock_irqrestore(&in_sub->lock, flags);
}
snd_rawmidi_receive(in_sub, &byte, 1);
cond_resched();
}
pr_info("flood stop: opened=%d events=%d\n", in_sub->opened, atomic_read(&events));
return 0;
}
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
pr_info("free: calling snd_card_free(%p)\n", card);
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
static int __init sndcore_rawmidi_init(void)
{
int err;
err = sndcore_card_new(&card, "sndcore_rawmidi");
if (err < 0)
return err;
pr_info("card=%p module=%p this=%p\n", card, card->module, THIS_MODULE);
if (card->module) {
pr_info("try_module_get(card->module)=%d\n", try_module_get(card->module));
module_put(card->module);
}
err = snd_rawmidi_new(card, "sndcore", 0, 0, 1, &rmidi);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
rmidi->info_flags = SNDRV_RAWMIDI_INFO_INPUT;
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &rm_ops);
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
flood = kthread_run(flood_fn, NULL, "sndcore_flood");
if (IS_ERR(flood)) {
err = PTR_ERR(flood);
flood = NULL;
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("rawmidi card registered: dev=%s devt=%u:%u\n",
dev_name(rmidi->dev), MAJOR(rmidi->dev->devt), MINOR(rmidi->dev->devt));
return 0;
}
static void __exit sndcore_rawmidi_exit(void)
{
if (flood) {
kthread_stop(flood);
flood = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_rawmidi_init);
module_exit(sndcore_rawmidi_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-04 rawmidi event_work verifier");
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
2026-11-22 7:50 ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
@ 2026-11-24 14:52 ` Krzysztof Kozlowski
2026-11-25 12:45 ` [PATCH] Re: " 徐晗翔
0 siblings, 1 reply; 41+ messages in thread
From: Krzysztof Kozlowski @ 2026-11-24 14:52 UTC (permalink / raw)
To: 徐晗翔, perex, tiwai; +Cc: linux-sound, linux-kernel
On 22/11/2026 08:50, 徐晗翔 wrote:
>
> Please keep me in Cc; I am not subscribed to the lists.
Why? You never responded to any other query we asked for the last month!
Best regards,
Krzysztof
^ permalink raw reply [flat|nested] 41+ messages in thread
* [PATCH] Re: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
2026-11-24 14:52 ` Krzysztof Kozlowski
@ 2026-11-25 12:45 ` 徐晗翔
0 siblings, 0 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:45 UTC (permalink / raw)
To: Krzysztof Kozlowski; +Cc: perex, tiwai, linux-sound, linux-kernel
close_substream() cancelled the input event work before clearing
substream->opened, but snd_rawmidi_receive() serializes only against
the opened store: a driver that delivers input in that window
re-queued event_work after the cancellation, and the work then ran
on the runtime freed by snd_rawmidi_runtime_free() (KASAN UAF in
snd_rawmidi_input_event_work()).
Cancel the work a second time after opened is cleared and before
the runtime is freed. Also restore the per-substream disconnected
flag: snd_rawmidi_dev_disconnect() marks input substreams
disconnected under substream->lock and drains the event work, so a
driver that keeps calling snd_rawmidi_receive() after the
disconnect cannot re-queue the work either (snd_rawmidi_receive()
and snd_rawmidi_input_trigger() check the flag).
---
sound/core/rawmidi.c | 23 +++++++++++++++++++++--
include/sound/rawmidi.h | 1 +
2 files changed, 22 insertions(+), 2 deletions(-)
diff --git a/sound/core/rawmidi.c b/sound/core/rawmidi.c
--- a/sound/core/rawmidi.c
+++ b/sound/core/rawmidi.c
@@ -215,7 +215,7 @@
static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
- if (!substream->opened)
+ if (!substream->opened || substream->disconnected)
return;
substream->ops->trigger(substream, up);
if (!up)
@@ -557,6 +557,14 @@
substream->opened = 0;
substream->append = 0;
}
+ /* Drain the input event work that a racing snd_rawmidi_receive()
+ * may have queued after the earlier cancellation in
+ * snd_rawmidi_input_trigger(): receive() serializes only against
+ * the opened=0 store above, not against the earlier cancel, so the
+ * work can be pending again here. It must not outlive the runtime
+ * free below. */
+ if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
+ cancel_work_sync(&substream->runtime->event_work);
substream->ops->close(substream);
if (substream->runtime->private_free)
substream->runtime->private_free(substream);
@@ -1151,7 +1159,7 @@
struct snd_rawmidi_runtime *runtime;
guard(spinlock_irqsave)(&substream->lock);
- if (!substream->opened)
+ if (!substream->opened || substream->disconnected)
return -EBADFD;
runtime = substream->runtime;
if (!runtime || !runtime->buffer) {
@@ -2065,6 +2073,17 @@
list_for_each_entry(s, &rmidi->streams[dir].substreams, list) {
if (s->runtime)
wake_up(&s->runtime->sleep);
+ /* mark input substreams disconnected and drain the
+ * event work: a driver that keeps calling
+ * snd_rawmidi_receive() after the disconnect must
+ * not re-queue the work on a runtime that the close
+ * path is about to free */
+ if (s->stream == SNDRV_RAWMIDI_STREAM_INPUT) {
+ scoped_guard(spinlock_irqsave, &s->lock)
+ s->disconnected = true;
+ if (s->runtime)
+ cancel_work_sync(&s->runtime->event_work);
+ }
}
}
diff --git a/include/sound/rawmidi.h b/include/sound/rawmidi.h
--- a/include/sound/rawmidi.h
+++ b/include/sound/rawmidi.h
@@ -84,6 +84,7 @@
int stream; /* direction */
int number; /* substream number */
bool opened; /* open flag */
+ bool disconnected; /* device disconnected flag */
bool append; /* append flag (merge more streams) */
bool active_sensing; /* send active sensing when close */
unsigned int framing; /* whether to frame input data */
--
> -----原始邮件-----
> 发件人: "Krzysztof Kozlowski" <krzk@kernel.org>
> 发送时间:2026-11-24 22:52:58 (星期二)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>, perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
>
> On 22/11/2026 08:50, 徐晗翔 wrote:
> >
> > Please keep me in Cc; I am not subscribed to the lists.
>
>
> Why? You never responded to any other query we asked for the last month!
>
>
> Best regards,
> Krzysztof
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (9 preceding siblings ...)
2026-11-22 7:50 ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
@ 2026-11-22 7:52 ` 徐晗翔
2026-11-25 12:46 ` [PATCH] " 徐晗翔
2026-11-22 7:55 ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
` (2 subsequent siblings)
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:52 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 4919 bytes --]
snd_hwdep_dsp_load() in sound/core/hwdep.c checks the
hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a
lock. Two threads that share the same hwdep file descriptor (dup() or
fork()) can both pass the check and run the driver's dsp_load callback
concurrently; both then set the same bit. Upstream serializes the whole
check-and-load operation with a per-device dsp_mutex, which this tree
does not have at all: struct snd_hwdep has no dsp_mutex field,
snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no
guard.
The driver callback is not required to be thread-safe. In-tree, the
usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices()
for index 1; that path registers ALSA devices and initializes URBs, and
usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic
WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act.
Concurrent DSP_LOAD can therefore duplicate device registration and
allocate/overwrite the same buffer/URB pointers, with double-free or
use-after-free consequences in the driver.
I reproduced the unlocked check on Linux 7.3 with a test hwdep device
whose dsp_load callback sleeps 300 ms and tracks concurrency. Four
threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows
active=1,2,3,4 in the callback (max_active=4). hw->exclusive only
guards open(), not concurrent ioctl() on an already-open fd. This run
did not produce a KASAN report because the callback is synthetic; the
proven claim is the broken mutual exclusion, with the usx2y consequence
argued from code.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.
* Root cause
sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):
if (hw->dsp_loaded & (1u << index))
return -EBUSY;
err = hw->ops.dsp_load(hw, &info);
if (err < 0)
return err;
hw->dsp_loaded |= (1u << index);
No lock covers the test, the callback and the bit update. Upstream
has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct
snd_hwdep contains dsp_mutex; in this tree the field, the
mutex_init() in snd_hwdep_new() and the guard are all absent.
The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex
around snd_hwdep_dsp_load(); open_mutex is held only by
snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a
one-time open() check, not a per-ioctl lock, and dup()/fork() share
the same struct file and hw->used without re-running open().
* Consequence in usx2y
sound/usb/usx2y/usX2Yhwdep.c:174-213
(snd_usx2y_hwdep_dsp_load) loads firmware images by index; for
index == 1 it calls usx2y_create_alsa_devices(hw->card), which
registers ALSA devices and starts the USB streams.
sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and
:299-334 (usx2y_in04_init) allocate buffers/URBs and use
WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a
check-then-act guard; WARN_ON does not serialize. Two concurrent
index-1 loads can both allocate and overwrite these fields, and
usx2y_unlinkseq()/cleanup can then double-free or UAF them.
* Trigger model
- A hwdep device whose DSP load is performed by userspace (usx2y is
the in-tree example);
- a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
- two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
same index;
- both pass the bit check and enter the driver callback.
No hardware is needed to demonstrate the unlocked check; the attached
test module does it.
* Reproducer (attached) and results on 7.3
sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1
and a dsp_load callback that does:
atomic_inc(&active); update max_active; msleep(300); atomic_dec().
sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue
SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.
Observed :
dsp_load enter: index=0 active=1 entered=1 ...
dsp_load enter: index=0 active=2 entered=2 ...
dsp_load enter: index=0 active=3 entered=3 ...
dsp_load enter: index=0 active=4 entered=4 ...
HWDEP: 4 concurrent DSP_LOAD issued
KASAN bug count: 0
active=4 proves all four callbacks ran concurrently despite the
dsp_loaded check; the absence of KASAN is expected for a synthetic
callback and is stated as such.
* Suggested direction
Restore the upstream per-device dsp_mutex:
- add struct mutex dsp_mutex to struct snd_hwdep;
- mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
- hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit
update in snd_hwdep_dsp_load().
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_hwdep.c --]
[-- Type: text/plain, Size: 2074 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <sound/core.h>
#include <sound/hwdep.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static struct snd_hwdep *hw;
static atomic_t active = ATOMIC_INIT(0);
static atomic_t entered = ATOMIC_INIT(0);
static int max_active;
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
module_param(max_active, int, 0444);
static void update_max(int v)
{
int old = READ_ONCE(max_active);
while (v > old && cmpxchg(&max_active, old, v) != old)
old = READ_ONCE(max_active);
}
static int test_dsp_load(struct snd_hwdep *h,
struct snd_hwdep_dsp_image *image)
{
int a = atomic_inc_return(&active);
int n = atomic_inc_return(&entered);
update_max(a);
pr_info("dsp_load enter: index=%u active=%d entered=%d image=%px len=%zu\n",
image->index, a, n, image->image, image->length);
msleep(300);
pr_info("dsp_load leave: index=%u active=%d\n", image->index, a);
atomic_dec(&active);
return 0;
}
static int __init sndcore_hwdep_init(void)
{
int err;
err = sndcore_card_new(&card, "sndcore_hwdep");
if (err < 0)
return err;
err = snd_hwdep_new(card, "sndcore", 0, &hw);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
hw->ops.dsp_load = test_dsp_load;
hw->exclusive = 1;
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("hwdep card registered\n");
return 0;
}
static void __exit sndcore_hwdep_exit(void)
{
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_hwdep_init);
module_exit(sndcore_hwdep_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-06 hwdep DSP_LOAD mutex verifier");
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
2026-11-22 7:52 ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
@ 2026-11-25 12:46 ` 徐晗翔
0 siblings, 0 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:46 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_hwdep_dsp_load() checked hw->dsp_loaded, ran the driver
callback and updated the bit with no lock; two threads sharing one
hwdep fd (dup()/fork()) could both pass the check and run
hw->ops.dsp_load() concurrently -- the callback is not required to
be thread-safe (in-tree usx2y registers ALSA devices and allocates
URBs under non-atomic WARN_ON() check-then-act guards), with
double-registration / double-free / UAF consequences.
Restore the upstream per-device dsp_mutex: add the field to struct
snd_hwdep, initialize it in snd_hwdep_new() and hold it across the
dsp_loaded check, the dsp_load() callback and the bit update.
hw->exclusive only guards open(), not concurrent ioctls on an
already-open fd.
---
sound/core/hwdep.c | 11 ++++++++++-
include/sound/hwdep.h | 2 ++
2 files changed, 12 insertions(+), 1 deletion(-)
diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
--- a/sound/core/hwdep.c
+++ b/sound/core/hwdep.c
@@ -207,11 +207,19 @@
struct snd_hwdep_dsp_image *info)
{
int err;
-
+
if (! hw->ops.dsp_load)
return -ENXIO;
if (info->index >= 32)
return -EINVAL;
+ /* Serialize the whole check-and-load sequence: two threads sharing
+ * one hwdep fd (dup()/fork()) must not both pass the dsp_loaded
+ * check and run the driver callback concurrently -- the callback
+ * is not required to be thread-safe (in-tree usx2y registers
+ * devices and allocates URBs with non-atomic check-then-act
+ * guards), and both would set the same bit. hw->exclusive only
+ * guards open(), not concurrent ioctls on an already-open fd. */
+ guard(mutex)(&hw->dsp_mutex);
/* check whether the dsp was already loaded */
if (hw->dsp_loaded & (1u << info->index))
return -EBUSY;
@@ -380,6 +388,7 @@
init_waitqueue_head(&hwdep->open_wait);
mutex_init(&hwdep->open_mutex);
+ mutex_init(&hwdep->dsp_mutex);
hwdep->card = card;
hwdep->device = device;
if (id)
diff --git a/include/sound/hwdep.h b/include/sound/hwdep.h
--- a/include/sound/hwdep.h
+++ b/include/sound/hwdep.h
@@ -56,6 +56,8 @@
struct device *dev;
struct mutex open_mutex;
+ struct mutex dsp_mutex; /* serializes the DSP_LOAD
+ * check-and-load sequence */
int used; /* reference counter */
unsigned int dsp_loaded; /* bit fields of loaded dsp indices */
unsigned int exclusive:1; /* exclusive access mode */
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:52:51 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
>
> snd_hwdep_dsp_load() in sound/core/hwdep.c checks the
> hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a
> lock. Two threads that share the same hwdep file descriptor (dup() or
> fork()) can both pass the check and run the driver's dsp_load callback
> concurrently; both then set the same bit. Upstream serializes the whole
> check-and-load operation with a per-device dsp_mutex, which this tree
> does not have at all: struct snd_hwdep has no dsp_mutex field,
> snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no
> guard.
>
> The driver callback is not required to be thread-safe. In-tree, the
> usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices()
> for index 1; that path registers ALSA devices and initializes URBs, and
> usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic
> WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act.
> Concurrent DSP_LOAD can therefore duplicate device registration and
> allocate/overwrite the same buffer/URB pointers, with double-free or
> use-after-free consequences in the driver.
>
> I reproduced the unlocked check on Linux 7.3 with a test hwdep device
> whose dsp_load callback sleeps 300 ms and tracks concurrency. Four
> threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows
> active=1,2,3,4 in the callback (max_active=4). hw->exclusive only
> guards open(), not concurrent ioctl() on an already-open fd. This run
> did not produce a KASAN report because the callback is synthetic; the
> proven claim is the broken mutual exclusion, with the usx2y consequence
> argued from code.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
> CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.
>
> * Root cause
>
> sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):
>
> if (hw->dsp_loaded & (1u << index))
> return -EBUSY;
>
> err = hw->ops.dsp_load(hw, &info);
> if (err < 0)
> return err;
> hw->dsp_loaded |= (1u << index);
>
> No lock covers the test, the callback and the bit update. Upstream
> has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct
> snd_hwdep contains dsp_mutex; in this tree the field, the
> mutex_init() in snd_hwdep_new() and the guard are all absent.
>
> The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex
> around snd_hwdep_dsp_load(); open_mutex is held only by
> snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a
> one-time open() check, not a per-ioctl lock, and dup()/fork() share
> the same struct file and hw->used without re-running open().
>
> * Consequence in usx2y
>
> sound/usb/usx2y/usX2Yhwdep.c:174-213
> (snd_usx2y_hwdep_dsp_load) loads firmware images by index; for
> index == 1 it calls usx2y_create_alsa_devices(hw->card), which
> registers ALSA devices and starts the USB streams.
>
> sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and
> :299-334 (usx2y_in04_init) allocate buffers/URBs and use
> WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a
> check-then-act guard; WARN_ON does not serialize. Two concurrent
> index-1 loads can both allocate and overwrite these fields, and
> usx2y_unlinkseq()/cleanup can then double-free or UAF them.
>
> * Trigger model
>
> - A hwdep device whose DSP load is performed by userspace (usx2y is
> the in-tree example);
> - a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
> - two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
> same index;
> - both pass the bit check and enter the driver callback.
>
> No hardware is needed to demonstrate the unlocked check; the attached
> test module does it.
>
> * Reproducer (attached) and results on 7.3
>
> sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1
> and a dsp_load callback that does:
> atomic_inc(&active); update max_active; msleep(300); atomic_dec().
> sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue
> SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.
>
> Observed :
>
> dsp_load enter: index=0 active=1 entered=1 ...
> dsp_load enter: index=0 active=2 entered=2 ...
> dsp_load enter: index=0 active=3 entered=3 ...
> dsp_load enter: index=0 active=4 entered=4 ...
> HWDEP: 4 concurrent DSP_LOAD issued
> KASAN bug count: 0
>
> active=4 proves all four callbacks ran concurrently despite the
> dsp_loaded check; the absence of KASAN is expected for a synthetic
> callback and is stated as such.
>
>
>
> * Suggested direction
>
> Restore the upstream per-device dsp_mutex:
> - add struct mutex dsp_mutex to struct snd_hwdep;
> - mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
> - hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit
> update in snd_hwdep_dsp_load().
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (10 preceding siblings ...)
2026-11-22 7:52 ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
@ 2026-11-22 7:55 ` 徐晗翔
2026-11-25 12:46 ` [PATCH] " 徐晗翔
2026-11-22 7:56 ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
2026-11-22 7:57 ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:55 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
get_available_index() in sound/core/ctljack.c walks the control id space
by calling snd_ctl_find_id() in a loop, but it does not hold
card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the
candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write
side of controls_rwsem, removes the hash entries, list_del()s the node
and kfree()s the kcontrol. get_available_index() can therefore load a
kcontrol that is being freed and read its id after the free -- a
use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem)
around the loop in snd_kctl_jack_new(); this tree has no lock there.
This is a static report: I have a complete code path and an upstream
diff, but I did not build a dynamic reproducer for this particular
window. I am reporting it because the missing lock is unambiguous and
the required concurrent operations are reachable from userspace.
The detailed description:
* Test environment / affected version
Source analysis against mainline 7.3; no dynamic reproducer was run
for this case. The related sound/core report was produced on a 7.3
KASAN kernel, but that run does not cover MR-05.
* Root cause
sound/core/ctljack.c:31-46 (get_available_index):
static int get_available_index(struct snd_card *card, const char *name)
{
struct snd_ctl_elem_id sid;
memset(&sid, 0, sizeof(sid));
sid.index = 0;
sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strscpy(sid.name, name, sizeof(sid.name));
while (snd_ctl_find_id(card, &sid)) { /* no controls_rwsem */
sid.index++;
sid.numid = 0;
}
return sid.index;
}
sound/core/control.c:843-868 (snd_ctl_find_id) documents that it
takes card->controls_rwlock internally, but the
CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
elem_id_matches() without taking it; only the fallback list walk takes
read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs
under controls_rwsem write, calls remove_hash_entries(card, kcontrol),
then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless
xa_load() can observe a kcontrol that is about to be freed, and
elem_id_matches() can read it afterwards.
Upstream snd_kctl_jack_new() has:
guard(rwsem_read)(&card->controls_rwsem);
before calling get_available_index(); the current tree removed it.
* Reachability
- get_available_index() is called from snd_kctl_jack_new()
(ctljack.c:62-77), which is called by snd_jack_kctl_new()
(jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
- Runtime caller: sound/soc/ti/ams-delta.c:361 calls
snd_soc_jack_add_pins() from the tty line discipline receive path;
snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
snd_jack_add_new_kctl() after the card is registered.
- A user with write access to /dev/snd/controlC* can add and remove
SNDRV_CTL_ELEM_ACCESS_USER controls with iface
SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name
(snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678).
A control with the same name as the jack kcontrol is the concurrent
object.
Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk
holds the read lock and the UAF does not apply); a runtime jack-pin
addition path; a concurrent control add/remove with a colliding name.
The race window is small, but the missing lock makes it a kernel bug
regardless of reproducibility.
* Impact
elem_id_matches() reads kcontrol->id.name/iface/index from freed
memory: KASAN use-after-free read, potential crash or limited
information exposure. A second, non-memory-safety symptom is two
jack kcontrols choosing the same index; the later snd_ctl_add()
returns -EBUSY, so jack creation fails.
* Suggested direction
Hold controls_rwsem for reading across the get_available_index() loop,
e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must
be released before snd_ctl_add(), which takes the write side).
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
2026-11-22 7:55 ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
@ 2026-11-25 12:46 ` 徐晗翔
2026-11-25 12:51 ` sashiko-bot
0 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:46 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
get_available_index() walked the control id space via
snd_ctl_find_id() without holding card->controls_rwsem; the
CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
elem_id_matches() without any lock, so a concurrent
snd_ctl_remove() (rwsem write, remove_hash_entries, list_del,
kfree) could free the kcontrol between the xa_load() and the id
read -- a use-after-free.
Restore the upstream guard: hold controls_rwsem for reading across
the index loop in snd_kctl_jack_new(); the read side is released
before the caller's snd_ctl_add(), which takes the write side.
---
sound/core/ctljack.c | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/sound/core/ctljack.c b/sound/core/ctljack.c
--- a/sound/core/ctljack.c
+++ b/sound/core/ctljack.c
@@ -73,7 +73,15 @@
return NULL;
jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
- kctl->id.index = get_available_index(card, kctl->id.name);
+ /* get_available_index() walks the control id space through
+ * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
+ * reads the candidate kcontrol's id without any lock of its own.
+ * Hold controls_rwsem for reading across the loop so a concurrent
+ * snd_ctl_remove() cannot remove and kfree() the kcontrol between
+ * the xa_load() and the id read. The read side is released before
+ * the caller's snd_ctl_add(), which takes the write side. */
+ scoped_guard(rwsem_read, &card->controls_rwsem)
+ kctl->id.index = get_available_index(card, kctl->id.name);
kctl->private_value = 0;
return kctl;
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:55:11 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
>
> get_available_index() in sound/core/ctljack.c walks the control id space
> by calling snd_ctl_find_id() in a loop, but it does not hold
> card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
> it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the
> candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write
> side of controls_rwsem, removes the hash entries, list_del()s the node
> and kfree()s the kcontrol. get_available_index() can therefore load a
> kcontrol that is being freed and read its id after the free -- a
> use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem)
> around the loop in snd_kctl_jack_new(); this tree has no lock there.
>
> This is a static report: I have a complete code path and an upstream
> diff, but I did not build a dynamic reproducer for this particular
> window. I am reporting it because the missing lock is unambiguous and
> the required concurrent operations are reachable from userspace.
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against mainline 7.3; no dynamic reproducer was run
> for this case. The related sound/core report was produced on a 7.3
> KASAN kernel, but that run does not cover MR-05.
>
> * Root cause
>
> sound/core/ctljack.c:31-46 (get_available_index):
>
> static int get_available_index(struct snd_card *card, const char *name)
> {
> struct snd_ctl_elem_id sid;
> memset(&sid, 0, sizeof(sid));
> sid.index = 0;
> sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
> strscpy(sid.name, name, sizeof(sid.name));
>
> while (snd_ctl_find_id(card, &sid)) { /* no controls_rwsem */
> sid.index++;
> sid.numid = 0;
> }
> return sid.index;
> }
>
> sound/core/control.c:843-868 (snd_ctl_find_id) documents that it
> takes card->controls_rwlock internally, but the
> CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
> elem_id_matches() without taking it; only the fallback list walk takes
> read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs
> under controls_rwsem write, calls remove_hash_entries(card, kcontrol),
> then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless
> xa_load() can observe a kcontrol that is about to be freed, and
> elem_id_matches() can read it afterwards.
>
> Upstream snd_kctl_jack_new() has:
>
> guard(rwsem_read)(&card->controls_rwsem);
>
> before calling get_available_index(); the current tree removed it.
>
> * Reachability
>
> - get_available_index() is called from snd_kctl_jack_new()
> (ctljack.c:62-77), which is called by snd_jack_kctl_new()
> (jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
> - Runtime caller: sound/soc/ti/ams-delta.c:361 calls
> snd_soc_jack_add_pins() from the tty line discipline receive path;
> snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
> snd_jack_add_new_kctl() after the card is registered.
> - A user with write access to /dev/snd/controlC* can add and remove
> SNDRV_CTL_ELEM_ACCESS_USER controls with iface
> SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name
> (snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678).
> A control with the same name as the jack kcontrol is the concurrent
> object.
>
> Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk
> holds the read lock and the UAF does not apply); a runtime jack-pin
> addition path; a concurrent control add/remove with a colliding name.
> The race window is small, but the missing lock makes it a kernel bug
> regardless of reproducibility.
>
> * Impact
>
> elem_id_matches() reads kcontrol->id.name/iface/index from freed
> memory: KASAN use-after-free read, potential crash or limited
> information exposure. A second, non-memory-safety symptom is two
> jack kcontrols choosing the same index; the later snd_ctl_add()
> returns -EBUSY, so jack creation fails.
>
> * Suggested direction
>
> Hold controls_rwsem for reading across the get_available_index() loop,
> e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must
> be released before snd_ctl_add(), which takes the write side).
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* Re: [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
2026-11-25 12:46 ` [PATCH] " 徐晗翔
@ 2026-11-25 12:51 ` sashiko-bot
0 siblings, 0 replies; 41+ messages in thread
From: sashiko-bot @ 2026-11-25 12:51 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [High] ALSA: jack: recursive controls_rwsem down_read() in
snd_kctl_jack_new()
- [High] sound: core: missing Signed-off-by trailer in commit message
--
commit 59c1eb09f555d07cbd4068c80f23a3bf865c7b34
Author: 徐晗翔 <xuhx@hust.edu.cn>
> sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
>
> get_available_index() walked the control id space via
> snd_ctl_find_id() without holding card->controls_rwsem; the
> CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
> elem_id_matches() without any lock, so a concurrent
> snd_ctl_remove() (rwsem write, remove_hash_entries, list_del,
> kfree) could free the kcontrol between the xa_load() and the id
> read -- a use-after-free.
>
> Restore the upstream guard: hold controls_rwsem for reading across
> the index loop in snd_kctl_jack_new(); the read side is released
> before the caller's snd_ctl_add(), which takes the write side.
[Severity: High]
The commit message is missing a Signed-off-by trailer.
> diff --git a/sound/core/ctljack.c b/sound/core/ctljack.c
> index 36700fda79f3c..f0c7fcd663474 100644
> --- a/sound/core/ctljack.c
> +++ b/sound/core/ctljack.c
> @@ -74,7 +74,15 @@ snd_kctl_jack_new(const char *name, struct snd_card *card)
> return NULL;
>
> jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
> - kctl->id.index = get_available_index(card, kctl->id.name);
> + /* get_available_index() walks the control id space through
> + * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
> + * reads the candidate kcontrol's id without any lock of its own.
> + * Hold controls_rwsem for reading across the loop so a concurrent
> + * snd_ctl_remove() cannot remove and kfree() the kcontrol between
> + * the xa_load() and the id read. The read side is released before
> + * the caller's snd_ctl_add(), which takes the write side. */
> + scoped_guard(rwsem_read, &card->controls_rwsem)
> + kctl->id.index = get_available_index(card, kctl->id.name);
> kctl->private_value = 0;
> return kctl;
> }
[Severity: High]
Does this acquire card->controls_rwsem for reading a second time inside
get_available_index()?
Commit ba8c3d5fc27a ("ALSA: jack: Protect the index scan against control
removal") already added the read guard to get_available_index():
sound/core/ctljack.c:get_available_index() {
...
guard(rwsem_read)(&card->controls_rwsem);
while (snd_ctl_find_id(card, &sid)) {
...
}
Because down_read() is not recursive, every snd_kctl_jack_new() call
triggers a lockdep recursive-locking warning and deadlocks if a writer
queues between the two down_read() calls:
CPU0 CPU1
snd_kctl_jack_new()
down_read(&card->controls_rwsem)
snd_ctl_add()
down_write(&card->controls_rwsem)
get_available_index()
down_read(&card->controls_rwsem) <-- deadlocks behind waiting writer
--
Sashiko AI review · https://sashiko.dev/#/patchset/35a9af21.56c.1a212be1cb2.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (11 preceding siblings ...)
2026-11-22 7:55 ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
@ 2026-11-22 7:56 ` 徐晗翔
2026-11-25 12:47 ` [PATCH] " 徐晗翔
2026-11-22 7:57 ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:56 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_mixer_oss_notify_callback is a bare exported function pointer. The
card core calls it from snd_card_register(), snd_card_disconnect() and
snd_card_do_free() without any mutex and without taking a reference to
the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL
and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees
card->mixer_oss. A card thread can read the non-NULL pointer, be
preempted, let rmmod finish unloading the module, and then call the old
function pointer -- executing code from the unloaded module. The same
lack of serialization allows the module's exit FREE walk and the card's
do_free FREE callback to race and double-free card->mixer_oss.
Upstream avoids this with a static mixer_oss_notify_mutex plus
snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path
clears the pointer under that mutex, so in-flight callbacks (including
their final module_put()) finish before unload. This tree exports the
raw pointer and calls it directly in three places.
This is a static report: the race is plain in the source, but I did not
build a dynamic reproducer for it. The requirement is
CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.
The detailed description:
* Test environment / affected version
Source analysis against mainline 7.3; no dynamic reproducer was run
for this case.
* Root cause
sound/core/init.c:85-86:
int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
direct calls:
- init.c:533-535 in snd_card_disconnect():
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
- init.c:590-591 in snd_card_do_free():
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
- init.c:935-936 in snd_card_register():
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
module side:
- sound/core/oss/mixer_oss.c:1370:
snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
- mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
snd_mixer_oss_notify_callback = NULL;
for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);
The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees
it and sets card->mixer_oss = NULL. There is no lock around the
pointer read/call or around the mixer_oss pointer, and no module
reference is taken by the callback path. snd_mixer_oss_open()
(mixer_oss.c:57/73) takes try_module_get(card->module), not this
module; the OSS mixer file's .owner may pin the module only while such
an fd is open, so rmmod is possible with no OSS fd.
* Failure modes
1. Unloaded-code execution: card thread reads a non-NULL callback,
preempted; rmmod runs exit, sets NULL, unloads; card thread resumes
and calls into unmapped module text.
2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both
invoke the FREE callback for the same card. Both can read
card->mixer_oss before either sets it NULL and kfree() the same
object; or one frees while the other is inside the handler.
3. Card register/disconnect during rmmod can leave the pointer
cleared but a concurrent call already in flight with no completion
wait.
* Trigger model
- CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
- one thread registers/disconnects/frees a card, another thread runs
rmmod snd-mixer-oss;
- the card thread must read the callback before the exit store and
reach the indirect call after unload, or both threads must reach the
FREE path concurrently.
Hotplug/unbind plus module unload is a realistic administration
sequence. It is a narrow but real race; the upstream mutex exists for
exactly this reason.
* Impact
- call into unloaded module text: UAF execution, kernel crash,
potential code execution if the address is reused;
- double free of card->mixer_oss: heap corruption;
- at minimum rmmod/hotplug crash.
* Suggested direction
Restore the upstream synchronization: a static mixer_oss_notify_mutex,
snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the
pointer, and snd_mixer_oss_set_notify() used by the module init/exit to
install/clear the pointer under the same mutex. Ensure the exit path
waits for in-flight callbacks (including their module_put()) before
the module text is freed.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
2026-11-22 7:56 ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
@ 2026-11-25 12:47 ` 徐晗翔
0 siblings, 0 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:47 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_mixer_oss_notify_callback is a bare exported function pointer
called by the card core without any mutex and without pinning the
snd-mixer-oss module: a card thread could read the non-NULL
pointer, be preempted, let rmmod clear it and unload, and then call
into unloaded module text; and the module exit FREE walk could race
snd_card_do_free()'s FREE callback into a double free of
card->mixer_oss.
Restore the upstream synchronization: a static
mixer_oss_notify_mutex, an internal snd_mixer_oss_notify(card, cmd)
that takes the mutex and checks the pointer (used by the
register/disconnect/free paths), and an exported
snd_mixer_oss_set_notify() that the module uses to install/clear
the callback under the same mutex -- so the exit path waits for
in-flight callbacks (including their module_put()) before the
module text is freed.
---
sound/core/init.c | 38 ++++++++++++++++++++++++++++++--------
include/sound/core.h | 5 ++++-
sound/core/oss/mixer_oss.c | 11 +++++++++--
3 files changed, 43 insertions(+), 11 deletions(-)
diff --git a/sound/core/init.c b/sound/core/init.c
--- a/sound/core/init.c
+++ b/sound/core/init.c
@@ -82,8 +82,33 @@
}
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
-EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
+/*
+ * The mixer-oss notify callback is invoked from the card core paths
+ * (register, disconnect, free) with no other serialization available.
+ * Call it through snd_mixer_oss_notify(), which takes a static mutex and
+ * checks the pointer under it: this keeps a callback in flight until it
+ * completes, so the snd-mixer-oss module can clear the pointer and wait
+ * for in-flight callbacks in its exit path instead of racing rmmod
+ * (call into unloaded module text) and double FREE walks
+ * (double free of card->mixer_oss).
+ */
+static DEFINE_MUTEX(mixer_oss_notify_mutex);
+static int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+
+static int snd_mixer_oss_notify(struct snd_card *card, int cmd)
+{
+ guard(mutex)(&mixer_oss_notify_mutex);
+ if (snd_mixer_oss_notify_callback)
+ return snd_mixer_oss_notify_callback(card, cmd);
+ return 0;
+}
+
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd))
+{
+ guard(mutex)(&mixer_oss_notify_mutex);
+ snd_mixer_oss_notify_callback = callback;
+}
+EXPORT_SYMBOL_GPL(snd_mixer_oss_set_notify);
#endif
static int check_empty_slot(struct module *module, int slot)
@@ -530,8 +555,7 @@
/* at this point, they cannot respond to any calls except release() */
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
- if (snd_mixer_oss_notify_callback)
- snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
+ snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
#endif
/* notify all devices that we are disconnected */
@@ -587,8 +611,7 @@
card->releasing = true;
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
- if (snd_mixer_oss_notify_callback)
- snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
+ snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE);
#endif
snd_device_free_all(card);
kfree(card->components);
@@ -932,8 +955,7 @@
return err;
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
- if (snd_mixer_oss_notify_callback)
- snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
+ snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER);
#endif
return 0;
}
diff --git a/include/sound/core.h b/include/sound/core.h
--- a/include/sound/core.h
+++ b/include/sound/core.h
@@ -300,7 +300,10 @@
#define SND_MIXER_OSS_NOTIFY_REGISTER 0
#define SND_MIXER_OSS_NOTIFY_DISCONNECT 1
#define SND_MIXER_OSS_NOTIFY_FREE 2
-extern int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+/* install/clear the mixer-oss notify callback; the core serializes all
+ * callbacks through a static mutex, so the module's exit path can wait
+ * for in-flight callbacks before its text is unloaded */
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd));
#endif
int snd_card_new(struct device *parent, int idx, const char *xid,
diff --git a/sound/core/oss/mixer_oss.c b/sound/core/oss/mixer_oss.c
--- a/sound/core/oss/mixer_oss.c
+++ b/sound/core/oss/mixer_oss.c
@@ -1367,7 +1367,7 @@
struct snd_card *card;
int idx;
- snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
+ snd_mixer_oss_set_notify(snd_mixer_oss_notify_handler);
for (idx = 0; idx < SNDRV_CARDS; idx++) {
card = snd_card_ref(idx);
if (card) {
@@ -1383,7 +1383,14 @@
struct snd_card *card;
int idx;
- snd_mixer_oss_notify_callback = NULL;
+ /* clear the callback through the core helper: it stores NULL under
+ * the notify mutex, so any in-flight callback (which holds the
+ * same mutex) has completed before we proceed, and the card core
+ * can no longer call into this module while it is being unloaded.
+ * This also makes the FREE walk below the only FREE invocation,
+ * instead of racing the card core's snd_card_do_free() on the same
+ * card->mixer_oss (double free). */
+ snd_mixer_oss_set_notify(NULL);
for (idx = 0; idx < SNDRV_CARDS; idx++) {
card = snd_card_ref(idx);
if (card) {
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:56:37 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
>
> snd_mixer_oss_notify_callback is a bare exported function pointer. The
> card core calls it from snd_card_register(), snd_card_disconnect() and
> snd_card_do_free() without any mutex and without taking a reference to
> the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL
> and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees
> card->mixer_oss. A card thread can read the non-NULL pointer, be
> preempted, let rmmod finish unloading the module, and then call the old
> function pointer -- executing code from the unloaded module. The same
> lack of serialization allows the module's exit FREE walk and the card's
> do_free FREE callback to race and double-free card->mixer_oss.
>
> Upstream avoids this with a static mixer_oss_notify_mutex plus
> snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path
> clears the pointer under that mutex, so in-flight callbacks (including
> their final module_put()) finish before unload. This tree exports the
> raw pointer and calls it directly in three places.
>
> This is a static report: the race is plain in the source, but I did not
> build a dynamic reproducer for it. The requirement is
> CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against mainline 7.3; no dynamic reproducer was run
> for this case.
>
> * Root cause
>
> sound/core/init.c:85-86:
>
> int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
> EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
>
> direct calls:
>
> - init.c:533-535 in snd_card_disconnect():
> if (snd_mixer_oss_notify_callback)
> snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
> - init.c:590-591 in snd_card_do_free():
> if (snd_mixer_oss_notify_callback)
> snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
> - init.c:935-936 in snd_card_register():
> if (snd_mixer_oss_notify_callback)
> snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
>
> module side:
>
> - sound/core/oss/mixer_oss.c:1370:
> snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
> - mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
> snd_mixer_oss_notify_callback = NULL;
> for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);
>
> The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees
> it and sets card->mixer_oss = NULL. There is no lock around the
> pointer read/call or around the mixer_oss pointer, and no module
> reference is taken by the callback path. snd_mixer_oss_open()
> (mixer_oss.c:57/73) takes try_module_get(card->module), not this
> module; the OSS mixer file's .owner may pin the module only while such
> an fd is open, so rmmod is possible with no OSS fd.
>
> * Failure modes
>
> 1. Unloaded-code execution: card thread reads a non-NULL callback,
> preempted; rmmod runs exit, sets NULL, unloads; card thread resumes
> and calls into unmapped module text.
> 2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both
> invoke the FREE callback for the same card. Both can read
> card->mixer_oss before either sets it NULL and kfree() the same
> object; or one frees while the other is inside the handler.
> 3. Card register/disconnect during rmmod can leave the pointer
> cleared but a concurrent call already in flight with no completion
> wait.
>
> * Trigger model
>
> - CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
> - one thread registers/disconnects/frees a card, another thread runs
> rmmod snd-mixer-oss;
> - the card thread must read the callback before the exit store and
> reach the indirect call after unload, or both threads must reach the
> FREE path concurrently.
>
> Hotplug/unbind plus module unload is a realistic administration
> sequence. It is a narrow but real race; the upstream mutex exists for
> exactly this reason.
>
> * Impact
>
> - call into unloaded module text: UAF execution, kernel crash,
> potential code execution if the address is reused;
> - double free of card->mixer_oss: heap corruption;
> - at minimum rmmod/hotplug crash.
>
> * Suggested direction
>
> Restore the upstream synchronization: a static mixer_oss_notify_mutex,
> snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the
> pointer, and snd_mixer_oss_set_notify() used by the module init/exit to
> install/clear the pointer under the same mutex. Ensure the exit path
> waits for in-flight callbacks (including their module_put()) before
> the module text is freed.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread
* sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (12 preceding siblings ...)
2026-11-22 7:56 ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
@ 2026-11-22 7:57 ` 徐晗翔
2026-11-25 12:48 ` [PATCH] " 徐晗翔
13 siblings, 1 reply; 41+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:57 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an
anonymous inode fd whose file_operations is snd_utimer_fops. That
structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls
try_module_get(fops->owner) when owner is non-NULL, so the fd does not
hold a reference to the snd-timer module. The module can be unloaded
while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or
close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded
module text.
The module field does not save this path: utimer->timer->module is set
to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by
snd_timer_open(), and a utimer fd never goes through snd_timer_open().
snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card ==
NULL it does not go through snd_device_new(); snd_timer_global_register()
(timer.c:1188-1194) only does the device-list insertion and takes no
module reference.
This is a static report: the missing .owner and the anon_inode lifetime
are unambiguous, but I did not build a dynamic reproducer (it requires
CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).
The detailed description:
* Test environment / affected version
Source analysis against mainline 7.3; no dynamic reproducer was run
for this case.
* Root cause
sound/core/timer.c:2175-2179:
static const struct file_operations snd_utimer_fops = {
.llseek = noop_llseek,
.release = snd_utimer_release,
.unlocked_ioctl = snd_utimer_ioctl,
};
Missing .owner = THIS_MODULE.
sound/core/timer.c:2298:
timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
O_RDWR | O_CLOEXEC);
fs/anon_inodes.c:141-142:
if (fops->owner && !try_module_get(fops->owner))
return ERR_PTR(-ENOENT);
owner == NULL -> no module reference. utimer->timer->module =
THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(),
which the fd does not use; snd_timer_global_register() is just
list_add_tail() and does not take a module reference.
Upstream snd_utimer_fops has .owner = THIS_MODULE.
* Failure model
1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->
anon_inode_getfd() with the ownerless fops;
2. no other snd-timer user -> rmmod snd-timer succeeds;
3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
module, and dereference utimer->timer / call snd_timer_interrupt().
This is a module-lifetime race, not a data race on a shared field; the
concurrency is rmmod vs fd operation.
* Trigger model
- CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
- a user creates a utimer fd via /dev/snd/timer;
- the module is unloaded before the fd is closed;
- the fd is used (trigger ioctl) or closed.
Requires local access to /dev/snd/timer; no hardware.
* Impact
- execution of unloaded module code: UAF execution, crash;
- if the module address range is reused, potential code execution;
- at minimum a local DoS / module-unload race.
* Suggested direction
Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the
anon-inode path should hold an explicit module reference for clarity;
.owner is the standard fix and matches upstream.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread* [PATCH] Re: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
2026-11-22 7:57 ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
@ 2026-11-25 12:48 ` 徐晗翔
0 siblings, 0 replies; 41+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_utimer_fops had no .owner, so the anonymous-inode fd created by
SNDRV_TIMER_IOCTL_CREATE did not hold a reference to the snd-timer
module: the module could be unloaded while the fd was open, and a
later SNDRV_TIMER_IOCTL_TRIGGER or close(fd) executed
snd_utimer_trigger()/snd_utimer_release() from unloaded module
text. (utimer->timer->module is only consulted by snd_timer_open(),
which the fd never goes through.)
Add .owner = THIS_MODULE so anon_inode_getfile() pins the module
for the lifetime of the fd, as upstream does.
---
sound/core/timer.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/sound/core/timer.c b/sound/core/timer.c
--- a/sound/core/timer.c
+++ b/sound/core/timer.c
@@ -2173,6 +2173,7 @@
}
static const struct file_operations snd_utimer_fops = {
+ .owner = THIS_MODULE,
.llseek = noop_llseek,
.release = snd_utimer_release,
.unlocked_ioctl = snd_utimer_ioctl,
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:57:29 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
>
> SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an
> anonymous inode fd whose file_operations is snd_utimer_fops. That
> structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls
> try_module_get(fops->owner) when owner is non-NULL, so the fd does not
> hold a reference to the snd-timer module. The module can be unloaded
> while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or
> close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded
> module text.
>
> The module field does not save this path: utimer->timer->module is set
> to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by
> snd_timer_open(), and a utimer fd never goes through snd_timer_open().
> snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card ==
> NULL it does not go through snd_device_new(); snd_timer_global_register()
> (timer.c:1188-1194) only does the device-list insertion and takes no
> module reference.
>
> This is a static report: the missing .owner and the anon_inode lifetime
> are unambiguous, but I did not build a dynamic reproducer (it requires
> CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against mainline 7.3; no dynamic reproducer was run
> for this case.
>
> * Root cause
>
> sound/core/timer.c:2175-2179:
>
> static const struct file_operations snd_utimer_fops = {
> .llseek = noop_llseek,
> .release = snd_utimer_release,
> .unlocked_ioctl = snd_utimer_ioctl,
> };
>
> Missing .owner = THIS_MODULE.
>
> sound/core/timer.c:2298:
>
> timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
> O_RDWR | O_CLOEXEC);
>
> fs/anon_inodes.c:141-142:
>
> if (fops->owner && !try_module_get(fops->owner))
> return ERR_PTR(-ENOENT);
>
> owner == NULL -> no module reference. utimer->timer->module =
> THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(),
> which the fd does not use; snd_timer_global_register() is just
> list_add_tail() and does not take a module reference.
>
> Upstream snd_utimer_fops has .owner = THIS_MODULE.
>
> * Failure model
>
> 1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->
> anon_inode_getfd() with the ownerless fops;
> 2. no other snd-timer user -> rmmod snd-timer succeeds;
> 3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
> 4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
> module, and dereference utimer->timer / call snd_timer_interrupt().
>
> This is a module-lifetime race, not a data race on a shared field; the
> concurrency is rmmod vs fd operation.
>
> * Trigger model
>
> - CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
> - a user creates a utimer fd via /dev/snd/timer;
> - the module is unloaded before the fd is closed;
> - the fd is used (trigger ioctl) or closed.
>
> Requires local access to /dev/snd/timer; no hardware.
>
> * Impact
>
> - execution of unloaded module code: UAF execution, crash;
> - if the module address range is reused, potential code execution;
> - at minimum a local DoS / module-unload race.
>
> * Suggested direction
>
> Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the
> anon-inode path should hold an explicit module reference for clarity;
> .owner is the standard fix and matches upstream.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 41+ messages in thread