git: ab9bdb417b41 - main - sound/midi: Centralize snd_midi cleanup

From: Christos Margiolis <christos_at_FreeBSD.org>
Date: Thu, 12 Nov 2026 16:38:18 UTC
The branch main has been updated by christos:

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

commit ab9bdb417b41b853e3ec668796e42ff65ccfcedb
Author:     Christos Margiolis <christos@FreeBSD.org>
AuthorDate: 2026-11-12 10:28:52 +0000
Commit:     Christos Margiolis <christos@FreeBSD.org>
CommitDate: 2026-11-12 16:35:49 +0000

    sound/midi: Centralize snd_midi cleanup
    
    midi_init()'s error path leaked both unit numbers and duplicated
    existing code.
    
    While here, drop the locking in midi_init(), because nothing can reach m
    before make_dev() publishes it.
    
    MFC after:      1 week
    Sponsored by:   The FreeBSD Foundation
---
 sys/dev/sound/midi/midi.c | 45 +++++++++++++++++++++------------------------
 1 file changed, 21 insertions(+), 24 deletions(-)

diff --git a/sys/dev/sound/midi/midi.c b/sys/dev/sound/midi/midi.c
index f812ef0f0253..694df4ef6aa7 100644
--- a/sys/dev/sound/midi/midi.c
+++ b/sys/dev/sound/midi/midi.c
@@ -126,6 +126,17 @@ midi_queue_deq(struct midi_queue *q, uint8_t *dst, size_t n)
 	memmove(q->buf, q->buf + n, q->used);
 }
 
+static void
+midi_destroy(struct snd_midi *m)
+{
+	free_unr(dev_unr, m->unit);
+	free_unr(chn_unr, m->channel);
+	free(m->inq.buf, M_MIDI);
+	free(m->outq.buf, M_MIDI);
+	mtx_destroy(&m->lock);
+	free(m, M_MIDI);
+}
+
 /*
  * Register a new midi device.
  *
@@ -145,8 +156,10 @@ midi_init(kobj_class_t cls, void *cookie)
 	inqsize = MPU_INQSIZE(m, cookie);
 	outqsize = MPU_OUTQSIZE(m, cookie);
 
-	if (!inqsize && !outqsize)
-		goto err1;
+	if (!inqsize && !outqsize) {
+		free(m, M_MIDI);
+		return (NULL);
+	}
 
 	mtx_init(&m->lock, "raw midi", NULL, 0);
 
@@ -155,8 +168,6 @@ midi_init(kobj_class_t cls, void *cookie)
 	if (outqsize)
 		obuf = malloc(outqsize, M_MIDI, M_WAITOK);
 
-	mtx_lock(&m->lock);
-
 	m->hiwat = outqsize / 2;
 
 	m->inq.buf = ibuf;
@@ -168,25 +179,16 @@ midi_init(kobj_class_t cls, void *cookie)
 	m->channel = alloc_unr(chn_unr);
 	m->cookie = cookie;
 
-	if (MPU_INIT(m, cookie))
-		goto err2;
-
-	mtx_unlock(&m->lock);
+	if (MPU_INIT(m, cookie)) {
+		midi_destroy(m);
+		return (NULL);
+	}
 
 	m->dev = make_dev(&midi_cdevsw, m->unit, UID_ROOT, GID_AUDIO, 0660,
 	    "midi%d.%d", m->unit, m->channel);
 	m->dev->si_drv1 = m;
 
-	return m;
-
-err2:
-	mtx_destroy(&m->lock);
-
-	free(m->inq.buf, M_MIDI);
-	free(m->outq.buf, M_MIDI);
-err1:
-	free(m, M_MIDI);
-	return NULL;
+	return (m);
 }
 
 int
@@ -204,12 +206,7 @@ midi_uninit(struct snd_midi *m)
 	mtx_unlock(&m->lock);
 	MPU_UNINIT(m, m->cookie);
 	destroy_dev(m->dev);
-	free_unr(dev_unr, m->unit);
-	free_unr(chn_unr, m->channel);
-	free(m->inq.buf, M_MIDI);
-	free(m->outq.buf, M_MIDI);
-	mtx_destroy(&m->lock);
-	free(m, M_MIDI);
+	midi_destroy(m);
 
 	return (0);
 }