git: 3dfca118f979 - main - sound: Busy the device in sysctl_dev_pcm_mode()

From: Christos Margiolis <christos_at_FreeBSD.org>
Date: Wed, 18 Nov 2026 10:24:37 UTC
The branch main has been updated by christos:

URL: https://cgit.FreeBSD.org/src/commit/?id=3dfca118f9796fbb0b23d7a09baf1867d3c2fabe

commit 3dfca118f9796fbb0b23d7a09baf1867d3c2fabe
Author:     Christos Margiolis <christos@FreeBSD.org>
AuthorDate: 2026-11-18 10:19:04 +0000
Commit:     Christos Margiolis <christos@FreeBSD.org>
CommitDate: 2026-11-18 10:19:04 +0000

    sound: Busy the device in sysctl_dev_pcm_mode()
    
    PCM_LOCK does not keep the device alive, so it does not protect this
    handler racing with pcm_unregister(). The sysctl is registered in the
    device's newbus context which outlives pcm_unregister().
    
    Busy the device instead, as the other handlers do, and hold the topology
    lock across the registration check so that the device cannot start
    detaching between the check and the busy.
    
    MFC after:      2 weeks
    Sponsored by:   The FreeBSD Foundation
    Differential Revision:  https://reviews.freebsd.org/D60509
---
 sys/dev/sound/pcm/sound.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/sys/dev/sound/pcm/sound.c b/sys/dev/sound/pcm/sound.c
index 3438b03d1ef1..22a9c25436ff 100644
--- a/sys/dev/sound/pcm/sound.c
+++ b/sys/dev/sound/pcm/sound.c
@@ -265,17 +265,25 @@ sysctl_dev_pcm_mode(SYSCTL_HANDLER_ARGS)
 	int mode = 0;
 
 	d = oidp->oid_arg1;
-	if (!PCM_REGISTERED(d))
+	bus_topo_lock();
+	if (!PCM_REGISTERED(d)) {
+		bus_topo_unlock();
 		return (ENODEV);
+	}
+	/*
+	 * Do not give up the topology lock until the device is busied, or it
+	 * might detach between unlocking and busying.
+	 */
+	PCM_ACQUIRE(d);
+	bus_topo_unlock();
 
-	PCM_LOCK(d);
 	if (d->playcount > 0)
 		mode |= PCM_MODE_PLAY;
 	if (d->reccount > 0)
 		mode |= PCM_MODE_REC;
 	if (d->mixer != NULL)
 		mode |= PCM_MODE_MIXER;
-	PCM_UNLOCK(d);
+	PCM_RELEASE(d);
 
 	return (sysctl_handle_int(oidp, &mode, 0, req));
 }