[PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF)

From: 徐晗翔

Date: Mon Nov 30 2026 - 22:24:01 EST


Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
sub-driver) pins only the base-card module (try_module_get of
hw->card->module in snd_hwdep_open()); the emux sub-driver module is
not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
list (snd_sf_free()) and the struct snd_emux itself -- while the fd
stays open with file->private_data pointing at the freed hwdep and
in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
hwdep->used nor replaces f_op the way a whole-card disconnect does).
Verified on mainline 7.3 with a KASAN kernel and the real in-tree
snd-emux-synth module (harness attached): one hundred slab-use-after-free
reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
and, with rmmod, the module text can additionally be unloaded while
those callbacks are still running (snd_hwdep_f_ops.owner pins the
snd-hwdep module, not the emux one). Needs the synth sub-driver
probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables,
mutex objects) and execution of unloaded module text -- crashes and a
controlled indirect-call surface.

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 mainline 7.3 tree, unmodified sources; KASAN enabled,
QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
sound/core/rawmidi.c are byte-identical between the tested tree and
the report baseline.

* Mechanism

- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
hwdep registers no ops.open/ops.release hooks
(emux_hwdep.c:126-131), so nothing increments snd_emux usage for
hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
open both go through snd_emux_inc_count(), which also pins
emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
without holding hw->open_mutex; the emux ioctl touches
hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
- The sub-driver removal path snd_emux_free() (emux.c:124-143)
performs snd_emux_delete_hwdep() -> snd_device_free() ->
snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
(hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
kfree(emu) -- none of it waits for hwdep->used to drop.
- Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
replaces open fds' f_op with snd_shutdown_f_ops and the teardown
waits for all files to close before the free sequence runs. The
sub-driver independent removal bypasses that protocol entirely --
that bypass is the defect.

The same shape exists for the emux virtual rawmidi devices
(snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
snd_rawmidi_open() likewise only pins the card module and
snd_rawmidi_free() kfrees unconditionally), and for the probe error
path of snd_emux_register() (init_hwdep registers the device, then a
later init_seq failure frees everything through snd_emux_free()).
This patch fixes the hwdep fd face; the rawmidi face is mentioned
for completeness and needs the equivalent treatment.

* Trigger model

emu10k1/emu8000 hardware with the synth sub-driver probed
(hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
fd open and issues ioctls; another (root, or hot-unplug hardware
event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer
table hw->ops, hw->used decrement), struct snd_emux, struct
snd_sf_list (presets_mutex operations on freed memory) and the
portptrs targets, plus execution of already-unloaded module text in
the rmmod case.

* Reproducer and results on 7.3

synthrace.c registers the real in-tree emux on a virtual card
(snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
writing 1 to the module's "free" parameter runs the real
snd_emux_free() (the sub-driver remove body) under the hammer.

Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
portptrs accesses, including a UAF write) and
snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
disabled stays clean.

* Fix

Give hwdep fds the same user accounting the sequencer and OSS paths
already have, and make the sub-driver removal wait for them:

- register hw->ops.open / hw->ops.release calling
snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
try_module_get()s emu->ops.owner (the sub-driver module), so an
open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
- count open fds additionally in a new atomic emu->hwdep_users and
make snd_emux_free() wait for it to drain (at the top, before any
sub-structure is torn down, so in-flight ioctls cannot observe
partially freed state either).

sysfs unbind bypasses module refcounts, which is why the drain wait
is needed in addition to the refcount. This matches the semantics
the whole-card path already provides (snd_card_disconnect() waits
for open files before anything is freed).

The patch is a suggested direction, written against 7.3 and reviewed
by inspection; it has not been runtime-validated (the reported
reproduction used the unpatched kernel). Happy to test any
counter-proposal.

* Patch

[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures

snd_emux_free() (the sub-driver remove path, reachable via
rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
the soundfont list and the struct snd_emux without waiting for open
hwdep file descriptors: hwdep fds pin only the base-card module, the
emux hwdep registers no open/release hooks, and an in-flight
snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
later operation on the stale fd hits freed memory. KASAN on 7.3 shows
100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
interleave.

Register hwdep open/release hooks that take snd_emux_inc_count()
(also pinning emu->ops.owner against rmmod, like the sequencer and
OSS-sequencer paths already do), count them in a new emu->hwdep_users,
and make snd_emux_free() wait for that count to drain before tearing
anything down -- mirroring the drain that snd_card_disconnect()
performs for whole-card removal. Note that sysfs unbind is not
covered by module refcounts, which is why the drain wait is required
in addition to the refcount.

--- a/include/sound/emux_synth.h
+++ b/include/sound/emux_synth.h
@@ -99,6 +99,8 @@ struct snd_emux {
int use_time; /* allocation counter */
spinlock_t voice_lock; /* Lock for voice access */
struct mutex register_mutex;
+ atomic_t hwdep_users; /* open hwdep fds */
+ wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
int client; /* For the sequencer client */
int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
spin_lock_init(&emu->voice_lock);
mutex_init(&emu->register_mutex);
+ atomic_set(&emu->hwdep_users, 0);
+ init_waitqueue_head(&emu->free_wait);
emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
if (! emu)
return -EINVAL;

timer_shutdown_sync(&emu->tlist);
+


+ wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));

snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);
--- a/sound/synth/emux/emux_hwdep.c
+++ b/sound/synth/emux/emux_hwdep.c
@@ (before snd_emux_hwdep_ioctl)


+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;
--
2.47.1


Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
xuhx@xxxxxxxxxxx
// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops
* snd_emux_note_on() on the real emux port while another kernel
* kthread loops the REAL snd_soundfont_remove_unlocked() /
* snd_soundfont_remove_samples() (the hwdep ioctl bodies).
* The soundfont itself is loaded from userspace through the real
* hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
* mr01ctl - SYNTH-MR-01 controlled window: kprobe post_handler on
* snd_soundfont_search_zone stalls the note_on thread right at
* the start of its unprotected table[] window; one
* snd_soundfont_remove_unlocked() runs and frees zone/sample/
* block underneath; release -> cascaded UAF.
* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;

/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */

static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);

static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
int i;

/*
* mr01ctl controlled window: parked mid note_on, AFTER table[] was
* filled by snd_soundfont_search_zone() and INSIDE the voice_lock
* configuration section, i.e. exactly inside the audited
* "search returned -> last table[]/vp->zone/vp->block use" span
* (emux_synth.c:63-114). Removing zone/sample/block underneath and
* then resuming replays the SYNTH-MR-01 interleaving end-to-end.
*/
if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
unsigned long deadline = jiffies + msecs_to_jiffies(20000);

pr_info("mr01ctl: note_on parked mid-configuration "
"(table[] window open)\n");
while (atomic_read(&mr01_armed) &&
time_before(jiffies, deadline))
cpu_relax();
pr_info("mr01ctl: note_on resuming\n");
}

for (i = 0; i < e->max_voices; i++) {
struct snd_emux_voice *vp = &e->voices[i];

if (vp->ch < 0) {
vp->ch = i;
e->num_voices++;
return vp;
}
}
/* recycle voice 0 so the hammering never starves */
if (e->max_voices > 0) {
e->voices[0].ch = 0;
return &e->voices[0];
}
return NULL;
}

/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk).
*/
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);

static int sr_start_voice(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;

atomic_inc(&sr_start_calls);
if (b)
b->offset++; /* UAF write on freed memblk */
return 0;
}

static void sr_trigger(struct snd_emux_voice *vp) {}
static void sr_release(struct snd_emux_voice *vp) {}
static void sr_update(struct snd_emux_voice *vp, int update) {}

/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */
static void sr_terminate(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;

if (b) {
unsigned int t = b->size; /* UAF read on freed memblk */

(void)t;
}
}

static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
if (!sp->block)
return -ENOMEM;
return 0;
}

static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}

static void sr_sample_reset(struct snd_emux *e)
{
snd_emux_terminate_all(e); /* same as snd_emu8000_sample_reset() */
}

/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset).
*/
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);

static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};

/* ---- shared setup/teardown ---- */

/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes.
*/
typedef void (*sr_note_on_t)(void *port, int note, int vel,
struct snd_midi_channel *chan);
typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);

static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;

static void *sr_kallsym(const char *name)
{
struct kprobe kp;
void *addr;

memset(&kp, 0, sizeof(kp));
kp.symbol_name = name;
if (register_kprobe(&kp) < 0) {
pr_err("kallsym(%s) failed\n", name);
return NULL;
}
addr = kp.addr;
unregister_kprobe(&kp);
return addr;
}

static int sr_resolve_syms(void)
{
sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
sr_remove_unlocked =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
sr_remove_samples =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
0 : -ENOENT;
}

static int sr_emux_setup(void)
{
int err;

err = snd_emux_new(&emu);
if (err < 0)
return err;

emu->ops = sr_ops;
if (sample_reset_en)
emu->ops.sample_reset = sr_sample_reset;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 0; /* skip virmidi: not needed for these cases */
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}

err = snd_emux_register(emu, card, 0, "synthrace");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
/*
* The real emu10k1 flow nests snd_emux_register() inside the outer
* snd_card_register() (seq-device probe), which then registers the
* emux proc entry created above. Replicate that final registration.
*/
snd_card_register(card);
pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
emu->sflist);
return 0;
}

static void sr_card_new(void)
{
int err;

parent = root_device_register("synthrace");
if (IS_ERR(parent)) {
parent = NULL;
return;
}
err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
if (err < 0) {
pr_err("snd_card_new failed: %d\n", err);
root_device_unregister(parent);
parent = NULL;
card = NULL;
}
}

/* ---- MR-01 natural hammering ---- */

static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);

static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;

static int noteon_fn(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
unsigned long until = jiffies + nat_secs * HZ;

port = emu->portptrs[0];
if (!port) {
pr_err("mr01nat: no port\n");
return 0;
}
chan = &port->chset.channels[0];
pr_info("mr01nat: note_on hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
sr_note_on(port, 60, 100, chan);
cond_resched();
}
pr_info("mr01nat: note_on hammer done\n");
return 0;
}

static int remove_fn(void *arg)
{
unsigned long until = jiffies + nat_secs * HZ;
int n = 0;

pr_info("mr01nat: remove hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
/* these are the exact bodies of the hwdep ioctls
* SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
*
* Throttled to ~2.5k/s: at unthrottled rates the removal
* outpaces the userspace loader and the soundfont spends its
* life empty, starving note_on of zones (see first mr01nat
* run: 5.5M removes, 0 collisions). The audit race needs the
* font alive while note_on is inside its table[] window.
*/
/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
* (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
* intact so the userspace loader can keep re-arming the font,
* while still freeing the very zone/sample/block trio of the
* audited SYNTH-MR-01 chain */
sr_remove_unlocked(emu->sflist);
n++;
usleep_range(200, 500);
}
pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
return 0;
}

static int mr01nat_set(const char *val, const struct kernel_param *kp)
{
if (!emu || !emu->portptrs[0])
return -ENODEV;
noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
return 0;
}
static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set };
module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);

/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */

static struct completion mr01_done;

static int mr01_noteon_once(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;

port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
sr_note_on(port, mr01_note, mr01_vel, chan);
pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
complete(&mr01_done);
return 0;
}

static int mr01ctl_set(const char *val, const struct kernel_param *kp)
{
struct task_struct *t;
int rc;

if (!emu || !emu->portptrs[0])
return -ENODEV;
if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
return -ENOENT;

init_completion(&mr01_done);
atomic_set(&mr01_stalled, 0);
atomic_set(&mr01_armed, 1);

t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
if (IS_ERR(t)) {
atomic_set(&mr01_armed, 0);
return PTR_ERR(t);
}
/* wait until the note_on thread is actually parked mid-window */
{
unsigned long deadline = jiffies + msecs_to_jiffies(8000);

while (!atomic_read(&mr01_stalled) &&
time_before(jiffies, deadline))
msleep(1);
}
if (!atomic_read(&mr01_stalled)) {
atomic_set(&mr01_armed, 0);
wait_for_completion_timeout(&mr01_done,
msecs_to_jiffies(2000));
pr_err("mr01ctl: note_on never parked; aborted\n");
return -EIO;
}
/* free zone/sample/block underneath the parked note_on */
pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
rc = sr_remove_unlocked(emu->sflist);
pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
msleep(50);
atomic_set(&mr01_armed, 0); /* release: cascaded UAF now */
wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
pr_info("mr01ctl: done\n");
return 0;
}
static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set };
module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);

static int probe_set(const char *val, const struct kernel_param *kp)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;

if (!emu || !emu->portptrs[0])
return -ENODEV;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
emu->sflist->presets_locked, emu->sflist->fonts_size,
emu->sflist->zone_counter);
sr_note_on(port, 60, 100, chan);
pr_info("probe: note_on done, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
return 0;
}
static const struct kernel_param_ops probe_ops = { .set = probe_set };
module_param_cb(probe, &probe_ops, NULL, 0200);

/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */

static int free_set(const char *val, const struct kernel_param *kp)
{
if (!emu)
return -ENODEV;
pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
snd_emux_free(emu);
emu = NULL;
pr_info("free: done\n");
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);

/* ---- module plumbing ---- */

static int __init synthrace_init(void)
{
int ret;

ret = sr_resolve_syms();
if (ret < 0)
return ret;
sr_card_new();
if (!card)
return -ENODEV;
return sr_emux_setup();
}

static void __exit synthrace_exit(void)
{
if (noteon_thr)
kthread_stop(noteon_thr);
if (remove_thr)
kthread_stop(remove_thr);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}

module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");
// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness.
*
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the
* REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
* (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
* fd open. Writes /tmp/synth_loaded when done.
* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */

static void patch_hdr(unsigned char *p, int type, int len, int optarg)
{
struct soundfont_patch_info h;

memset(&h, 0, sizeof(h));
h.key = SNDRV_OSS_SOUNDFONT_PATCH;
h.device_no = 0;
h.sf_id = 0;
h.optarg = optarg;
h.len = len;
h.type = type;
memcpy(p, &h, sizeof(h));
}

static int sf_load(int fd)
{
unsigned char buf[512];
struct soundfont_open_parm parm;
struct soundfont_sample_info si;
struct soundfont_voice_rec_hdr rh;
struct soundfont_voice_info vi;
int rc;

/* OPEN_PATCH */
memset(&parm, 0, sizeof(parm));
parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
strcpy(parm.name, "synthrace");
patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
/* font already open from an earlier round */
if (errno == EBUSY)
return 0;
fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
return -1;
}

/* LOAD_DATA: 1 sample, 64 s16le frames */
memset(&si, 0, sizeof(si));
si.sample = 1;
si.start = 0;
si.end = 64;
si.loopstart = 8;
si.loopend = 56;
si.size = 64;
si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
si.size * 2);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
return -1;
}

/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
* exclusiveClass = 1, tied to sample 1 */
memset(&vi, 0, sizeof(vi));
vi.sf_id = 0;
vi.sample = 1;
vi.root = 60;
vi.high = 127;
vi.velhigh = 127;
vi.fixkey = -1;
vi.fixvel = -1;
vi.fixpan = -1;
vi.pan = -1;
vi.amplitude = 127;
vi.scaleTuning = 100;
vi.exclusiveClass = 1;
memset(&rh, 0, sizeof(rh));
rh.bank = 0;
rh.instr = 0;
rh.nvoices = 1;
rh.write_mode = SNDRV_SFNT_WR_APPEND;
patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
sizeof(rh) + sizeof(vi), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
&vi, sizeof(vi));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
return -1;
}

/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
* LOAD_INFO only enter the preset table at close time (this is the
* real sfxload sequence), so note_on's search_zones() can find them */
patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
return -1;
}
return 0;
}

static int plan_load(int secs, int reload)
{
int fd, n = 0;
unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);

fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
if (sf_load(fd) < 0) {
close(fd);
return 1;
}
printf("LOAD: font ready\n");
fflush(stdout);
int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (tf >= 0)
close(tf);

while (reload && (unsigned long)time(NULL) < until) {
/* re-load data+info; kernel-side hammer eats the font */
if (sf_load(fd) < 0)
break;
n++;
usleep(2000);
}
printf("LOAD: done (%d reloads)\n", n);
/* keep the fd open until the plan ends (exclusive hwdep) */
sleep(secs > 0 ? secs : 30);
close(fd);
return 0;
}

static int plan_mr03(int iters)
{
int fd, i;
struct snd_emux_misc_mode mm;
unsigned int ver = 0;
int avail = 0;

fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03: hammering %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
if ((i % 128) == 0) {
printf("MR03: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR03: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR)); /* delayed variant: reopen */
printf("MR03: done\n");
return 0;
}

static int plan_mr04(int iters)
{
int i;

printf("MR04: hammering %d proc-read iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
char buf[4096];
int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);

if (fd >= 0) {
ssize_t r = read(fd, buf, sizeof(buf));

(void)r;
close(fd);
}
if ((i % 128) == 0) {
printf("MR04: iter %d\n", i);
fflush(stdout);
}
usleep(500);
}
printf("MR04: done\n");
return 0;
}

static int plan_mr04hold(void)
{
char buf[4096];
int fd;

fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open proc: %s\n", strerror(errno));
return 1;
}
printf("MR04HOLD: fd open, reading once\n");
fflush(stdout);
read(fd, buf, sizeof(buf));
printf("MR04HOLD: holding fd for 4s (free happens now)\n");
fflush(stdout);
sleep(4);
off_t ls = lseek(fd, 0, SEEK_SET);
printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
fflush(stdout);
ssize_t rr = read(fd, buf, sizeof(buf));
printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
fflush(stdout);
printf("MR04HOLD: done\n");
close(fd);
return 0;
}

static int plan_mr05(void)
{
int fd, tries;
struct snd_emux_misc_mode mm;

for (tries = 0; tries < 5000; tries++) {
struct stat st;

if (stat("/dev/snd/hwC0D0", &st) == 0)
break;
usleep(1000);
}
if (tries >= 5000) {
fprintf(stderr, "MR05: hwC0D0 never appeared\n");
return 1;
}
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "MR05: open: %s\n", strerror(errno));
return 1;
}
printf("MR05: opened inside probe window, issuing MISC_MODE\n");
fflush(stdout);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
fflush(stdout);
close(fd);
return 0;
}

int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: synth_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "load"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
if (!strcmp(argv[1], "reload"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
if (!strcmp(argv[1], "mr03"))
return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
if (!strcmp(argv[1], "mr04"))
return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
if (!strcmp(argv[1], "mr04hold"))
return plan_mr04hold();
if (!strcmp(argv[1], "mr05"))
return plan_mr05();
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}