--- midi.c.orig 2022-01-10 10:38:43.659213000 +0900 +++ midi.c 2022-01-10 10:55:01.655948000 +0900 @@ -60,6 +60,7 @@ #include #include #include +#include #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" @@ -265,8 +266,8 @@ */ /* - * Register a new rmidi device. cls midi_if interface unit == 0 means - * auto-assign new unit number unit != 0 already assigned a unit number, eg. + * Register a new rmidi device. cls midi_if interface unit == -1 means + * auto-assign new unit number unit >= 0 already assigned a unit number, eg. * not the first channel provided by this device. channel, sub-unit * cookie is passed back on MPU calls Typical device drivers will call with * unit=0, channel=1..(number of channels) and cookie=soft_c and won't care @@ -291,26 +292,32 @@ * Protect against call with existing unit/channel or auto-allocate a * new unit number. */ - i = -1; - TAILQ_FOREACH(m, &midi_devs, link) { - mtx_lock(&m->lock); - if (unit != 0) { - if (m->unit == unit && m->channel == channel) { - mtx_unlock(&m->lock); - goto err0; - } - } else { + if( unit < 0 ) { + i = -1; + TAILQ_FOREACH(m, &midi_devs, link) { + mtx_lock(&m->lock); /* * Find a better unit number */ if (m->unit > i) i = m->unit; + mtx_unlock(&m->lock); } - mtx_unlock(&m->lock); - } - - if (unit == 0) + if( i == INT_MAX ) { + goto err0; + } unit = i + 1; + } + else { + TAILQ_FOREACH(m, &midi_devs, link) { + mtx_lock(&m->lock); + if (m->unit == unit && m->channel == channel) { + mtx_unlock(&m->lock); + goto err0; + } + mtx_unlock(&m->lock); + } + } MIDI_DEBUG(1, printf("midiinit #2: unit %d/%d.\n", unit, channel)); m = malloc(sizeof(*m), M_MIDI, M_WAITOK | M_ZERO); --- midi.h.orig 2022-01-10 10:39:11.196563000 +0900 +++ midi.h 2022-01-10 10:39:48.935932000 +0900 @@ -43,6 +43,8 @@ #define MIDI_TYPE unsigned char +#define MIDI_UNIT_AUTO_ALLOC (-1) + struct snd_midi; struct snd_midi * --- mpu401.c.orig 2022-01-10 10:39:04.555631000 +0900 +++ mpu401.c 2022-01-10 10:40:13.074777000 +0900 @@ -193,7 +193,7 @@ m->cookie = cookie; m->flags = 0; - m->mid = midi_init(&mpu401_class, 0, 0, m); + m->mid = midi_init(&mpu401_class, MIDI_UNIT_AUTO_ALLOC, 0, m); if (!m->mid) goto err; *cb = mpu401_intr;