Skip to contentSkip to conversation

rust: snd: Introduce experimental ALSA rawmidi abstractions

RFC PATCH In review Tristan de Cacqueray 3 participants 7 messages Oct 11 – Oct 14

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover rust: snd: Introduce experimental ALSA rawmidi abstractions

Hi Takashi and the Rust for Linux maintainers.

I just noticed your mail about an early Rust prototype for the sound subsystem right before I was about to submit this RFC!
https://lore.kernel.org/alsa-devel/[email protected]/

Nevertheless, please allow me to share what I had in mind through this small proof of concept for the rawmidi API. I am looking for feedback on the scope, coordination, and the ownership model rather than a detailed review for merging.

My use case is a new hardware controller using a custom serial protocol. While developing its Rust driver, I needed an interface to ALSA rawmidi. I'm particularly interested in handling rawmidi substream safely to avoid issues like the one fixed by
221253723dc5 ("ALSA: bcd2000: Fix race between rawmidi and disconnect")

So, I wrote some bindings to see how that would look like. This series adds experimental snd_card and snd_rawmidi wrappers, input/output callback traits, and a sample rawmidi faux device using delayed work to simulate incoming MIDI data.

This is not merge-ready. In particular, the prototype does not yet enforce the devres lifetime of the card or the lifetime of its rawmidi wrapper. The substream helper also relies on the driver clearing it before close returns.

Here are my questions:

1. Does this rawmidi experiment overlaps with your prototype? If so, I would be happy to coordinate or adapt this experiment to it.
2. Is rawmidi a useful initial target for ALSA Rust abstraction?
3. Does your prototype mirror the C API 1:1, or for example, does it hide the substream lifecycle? That's the design choice I'm least sure about.

Testing:
- build with CONFIG_RUST=y and CONFIG_SAMPLE_RUST_MIDI_DEVICE=m.
- Run amidi client to receive events from Rust:
amidi -l # to get the hw number
amidi -d -S "424344" -p hw:1,0
- Modprobe/rmmod works, but I haven't reproduced the race between rawmidi substream and disconnect.

Base: rust-next at 2dee3d3adcad

This is my first contribution to the kernel, suggestions on routing or RFC scope are welcome.

Thanks!
-Tristan

---
Tristan de Cacqueray (3):
rust: snd: Add initial snd_card binding
rust: snd: Add snd_rawmidi binding
rust: snd: Add active rawmidi_substream helper

 rust/bindings/bindings_helper.h  |   2 +
 rust/kernel/lib.rs               |   2 +
 rust/kernel/snd.rs               | 403 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig             |  11 +++
 samples/rust/Makefile            |   1 +
 samples/rust/rust_midi_device.rs | 159 ++++++++++++++++++++++++++++++++++++++++
 6 files changed, 578 insertions(+)

---
base-commit: 2dee3d3adcadcc57d62ba6608cd02f50b0c10264
change-id: 20261011-rust-snd-c5e596867624

Best regards,

Signature · 1 line
Tristan de Cacqueray <[email protected]>
#1 lore raw

RFC PATCH 1/3 rust: snd: Add initial snd_card binding

Add minimal abstraction to create a snd_card in Rust.

---
 rust/bindings/bindings_helper.h  |  1 +
 rust/kernel/lib.rs               |  2 ++
 rust/kernel/snd.rs               | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig             | 11 +++++++++++
 samples/rust/Makefile            |  1 +
 samples/rust/rust_midi_device.rs | 41 +++++++++++++++++++++++++++++++++++++++++
 6 files changed, 145 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index c706dda5b5ca..c624f073db04 100644
@@ -97,6 +97,7 @@
 #include <linux/xarray.h>
 #include <net/genetlink.h>
 #include <net/netlink.h>
+#include <sound/core.h>
 #include <trace/events/rust_sample.h>
 
 /*
rust/kernel/lib.rs +2 -0
index 7225abc64084..974b3e5ce7ac 100644
@@ -130,6 +130,8 @@
 #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
 pub mod serdev;
 pub mod sizes;
+#[cfg(CONFIG_SND)]
+pub mod snd;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
 #[doc(hidden)]
rust/kernel/snd.rs new file +89 -0

89 lines not on this page · raw message

samples/rust/Kconfig +11 -0
index 31d62533ef25..1cf8cf18cd2d 100644
@@ -31,6 +31,17 @@ config SAMPLE_RUST_MINIMAL
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_MIDI_DEVICE
+	tristate "MIDI device"
+	depends on SND_RAWMIDI
+	help
+	  This option builds the Rust MIDI device.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_midi_device.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_MISC_DEVICE
 	tristate "Misc device"
 	help
samples/rust/Makefile +1 -0
index b986b681cde5..170b7e3e5590 100644
@@ -2,6 +2,7 @@
 ccflags-y += -I$(src)				# needed for trace events
 
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
+obj-$(CONFIG_SAMPLE_RUST_MIDI_DEVICE)		+= rust_midi_device.o
 obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
 obj-$(CONFIG_SAMPLE_RUST_DEBUGFS)		+= rust_debugfs.o
samples/rust/rust_midi_device.rs new file +41 -0

41 lines not on this page · raw message

Signature · 1 line
2.56.0
#2 lore raw

Re: [PATCH RFC 1/3] rust: snd: Add initial snd_card binding

kernel test robot noticed the following build errors:

Hi Tristan,

[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:

[auto build test ERROR on 2dee3d3adcadcc57d62ba6608cd02f50b0c10264]

url:    https://github.com/intel-lab-lkp/linux/commits/Tristan-de-Cacqueray/rust-snd-Add-initial-snd_card-binding/20261011-130217
base:   2dee3d3adcadcc57d62ba6608cd02f50b0c10264
patch link:    https://lore.kernel.org/r/20261011-rust-snd-v1-1-7974ecdcd345%40midirus.com
patch subject: [PATCH RFC 1/3] rust: snd: Add initial snd_card binding
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20261015/[email protected]/config)
compiler: clang version 22.1.8 (https://github.com/llvm/llvm-project ca7933e47d3a3451d81e72ac174dcb5aa28b59d1)
rustc: rustc 1.96.0 (ac68faa20 2026-05-25)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261015/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> ld.lld: error: undefined symbol: snd_devm_card_new
   >>> referenced by snd.rs:29 (rust/kernel/snd.rs:29)
   >>>               vmlinux.o:(<kernel::snd::SoundCard>::new)
--
>> ld.lld: error: undefined symbol: snd_card_register
   >>> referenced by snd.rs:63 (rust/kernel/snd.rs:63)
   >>>               vmlinux.o:(<kernel::snd::SoundCard>::register)

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#3 lore raw

RFC PATCH 2/3 rust: snd: Add snd_rawmidi binding

In reply to Tristan de Cacqueray

Add minimal abstraction to create a snd_rawmidi along with the input/output ops in Rust.

---
 rust/bindings/bindings_helper.h  |   1 +
 rust/kernel/snd.rs               | 253 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 samples/rust/rust_midi_device.rs |  33 +++++++++++++
 3 files changed, 286 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +1 -0
index c624f073db04..71999651aebf 100644
@@ -98,6 +98,7 @@
 #include <net/genetlink.h>
 #include <net/netlink.h>
 #include <sound/core.h>
+#include <sound/rawmidi.h>
 #include <trace/events/rust_sample.h>
 
 /*
rust/kernel/snd.rs +252 -1

266 lines not on this page · raw message

samples/rust/rust_midi_device.rs +33 -0
index 5561a0437b59..1465ba9544d6 100644
@@ -1,15 +1,44 @@
 // SPDX-License-Identifier: GPL-2.0
 
 //! Rust MIDI minimal sample.
+//!
+//! This driver demonstrates usage of the kernel::snd subsystem:
+//! - Create a rawmidi device
+//! - Print received event
 
 use kernel::{
     faux,
     prelude::*,
     snd,
+    sync::Arc,
 };
 
+struct RustMidiDevice;
+
+impl snd::RawMidiInput for RustMidiDevice {
+    fn trigger(&self, _substream: &snd::RawMidiSubstream, up: bool) {
+        pr_debug!("input trigger up:{up}!\n");
+    }
+}
+
+// Implement midi output ops: just display transmitted event.
+impl snd::RawMidiOutput for RustMidiDevice {
+    fn trigger(&self, substream: &snd::RawMidiSubstream, up: bool) {
+        pr_debug!("output trigger up:{up}!\n");
+        if up {
+            let mut buf = [0; 64];
+            match substream.transmit(&mut buf) {
+                Ok(count) => pr_info!("transmit got: {:?}\n", buf[..count]),
+                Err(err) => pr_err!("transmit failed: {err:?}"),
+            };
+        }
+    }
+}
+
 impl kernel::Module for RustMidiDeviceModule {
     fn init(_module: &'static ThisModule) -> Result<Self> {
+        let state = Arc::new(RustMidiDevice, GFP_KERNEL)?;
+
         pr_debug!("Initializing sound card\n");
         let reg = faux::Registration::new(c"rust-midi-device", None)?;
         let fdev = reg.as_ref();
@@ -21,6 +50,10 @@ fn init(_module: &'static ThisModule) -> Result<Self> {
         card.set_driver(c"rust-midi")?;
         card.set_shortname(c"RustMIDI")?;
 
+        pr_debug!("Initializing rawmidi card\n");
+        let mut rmidi = snd::RawMidi::new(&card, c"RustRMIDI", 0, 1, 1, state.clone())?;
+        rmidi.set_name(c"RustRMIDI")?;
+
         // Register the sndcard to ALSA.
         card.register()?;
 
Signature · 1 line
2.56.0
#4 lore raw

RFC PATCH 3/3 rust: snd: Add active rawmidi_substream helper

In reply to Tristan de Cacqueray

Add helper to share the substream across execution contexts in Rust.

---
 rust/kernel/snd.rs               | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 samples/rust/rust_midi_device.rs | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
 2 files changed, 154 insertions(+), 6 deletions(-)
rust/kernel/snd.rs +65 -2
index 7285575c6257..d9df5af155b9 100644
@@ -7,13 +7,13 @@
 //!
 //! C header: [`include/sound/core.h`](srctree/include/sound/core.h)
 
-use core::marker::PhantomData;
+use core::{marker::PhantomData, ptr::NonNull};
 use kernel::{
     bindings,
     device::Device,
     error::{to_result, Result},
     prelude::*,
-    sync::Arc,
+    sync::{Arc, SpinLockIrq},
     types::ForeignOwnable,
 };
 
@@ -338,3 +338,66 @@ pub fn set_name(&mut self, name: &CStr) -> Result<()> {
         copy_to_c_buf(&mut rmidi.name, name)
     }
 }
+
+/// A thread-safe helper for sharing ALSA substream across execution contexts.
+///
+/// # Safety
+///
+/// Implementations MUST clear any [`ActiveMidiSubstream`] before `close` returns.
+/// TODO: enforce in framework.
+#[pin_data(PinnedDrop)]
+pub struct ActiveMidiSubstream {
+    #[pin]
+    ptr: SpinLockIrq<Option<NonNull<bindings::snd_rawmidi_substream>>>,
+}
+
+impl ActiveMidiSubstream {
+    /// Creates a new initialiser for an empty substream.
+    pub fn new() -> impl PinInit<Self> {
+        pin_init!(Self {
+            ptr <- kernel::sync::new_spinlock_irq!(None),
+        })
+    }
+
+    /// Stores the given substream reference as the active target.
+    pub fn store(&self, substream: &RawMidiSubstream) {
+        let mut guard = self.ptr.lock();
+        *guard = NonNull::new(substream.ptr);
+    }
+
+    /// Clears the tracked substream reference.
+    pub fn clear(&self) {
+        let mut guard = self.ptr.lock();
+        *guard = None;
+    }
+
+    /// Executes a closure while holding the spinlock with a temporary reference
+    /// to the active substream, if present.
+    ///
+    /// Returns `None` if no stream is currently active.
+    pub fn with_active<F, R>(&self, f: F) -> Option<R>
+    where
+        F: FnOnce(&RawMidiSubstream) -> R,
+    {
+        let guard = self.ptr.lock();
+        let nn_ptr = (*guard)?;
+        // SAFETY: The raw ptr can only be stored using a valid rawmidi_substream.
+        let safe_substream = unsafe { RawMidiSubstream::from_raw(nn_ptr.as_ptr()) };
+
+        Some(f(&safe_substream))
+    }
+}
+
+#[pinned_drop]
+impl PinnedDrop for ActiveMidiSubstream {
+    fn drop(self: Pin<&mut Self>) {
+        self.clear()
+    }
+}
+
+// SAFETY: snd_rawmidi_substream is accessed only under the SpinLockIrq and it is
+// only ever valid between the ALSA `open` and `close` callbacks, during
+// which the ALSA core guarantees the substream is alive (see the type docs).
+unsafe impl Send for ActiveMidiSubstream {}
+// SAFETY: snd_rawmidi_substream is accessed only under the SpinLockIrq. See above.
+unsafe impl Sync for ActiveMidiSubstream {}
samples/rust/rust_midi_device.rs +89 -4

129 lines not on this page · raw message

Signature · 1 line
2.56.0
#5 lore raw
In reply to Tristan de Cacqueray
Quoted 28 lines · Tristan de Cacqueray

Hi Takashi and the Rust for Linux maintainers.

I just noticed your mail about an early Rust prototype for the sound subsystem right before I was about to submit this RFC!
https://lore.kernel.org/alsa-devel/[email protected]/

Nevertheless, please allow me to share what I had in mind through this small proof of concept for the rawmidi API. I am looking for feedback on the scope, coordination, and the ownership model rather than a detailed review for merging.

My use case is a new hardware controller using a custom serial protocol. While developing its Rust driver, I needed an interface to ALSA rawmidi. I'm particularly interested in handling rawmidi substream safely to avoid issues like the one fixed by
221253723dc5 ("ALSA: bcd2000: Fix race between rawmidi and disconnect")

So, I wrote some bindings to see how that would look like. This series adds experimental snd_card and snd_rawmidi wrappers, input/output callback traits, and a sample rawmidi faux device using delayed work to simulate incoming MIDI data.

This is not merge-ready. In particular, the prototype does not yet enforce the devres lifetime of the card or the lifetime of its rawmidi wrapper. The substream helper also relies on the driver clearing it before close returns.

Quoted 4 lines

Here are my questions:

1. Does this rawmidi experiment overlaps with your prototype? If so, I would be happy to coordinate or adapt this experiment to it.

No, my patchset doesn't contain rawmidi support yet.
The sound card abstraction would conflict quite, sure, but it wouldn't be too hard to adapt, I guess.

Quoted 1 line

2. Is rawmidi a useful initial target for ALSA Rust abstraction?

Sure, why not, if it's actually needed? :)

Quoted 2 lines

3. Does your prototype mirror the C API 1:1, or for example, does it hide the substream lifecycle? That's the design choice I'm least sure about.

It's mostly a straightforward wrapping of C API, but there are a few twists to adapt Rust-way. The card can be managed in RAII style, too, for example.

I haven't prepared for submission, but you can find the current changes in test/sound-rust branch of sound git tree (either kernel.org or github.com):
https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/log/?h=test/sound-rust
https://github.com/tiwai/sound/tree/test/sound-rust

Those are over 50 commits on top of 7.3-rc5, and I'll likely rebase a bit to rearrange before submission, so beware of changes in future.

The commits begin with a few Rust kernel changes for fixing and addition for the sound support, including the PM support from Beata Michalska (just took what have been posted), followed by ALSA core abstractions for the card, PCM and controls.

Then it continues to the implementations of 3 actual sound drivers for PCM/control: the dummy driver (with platform and hrtimer), and the ens1370 and intel8x0 drivers for PCI devices to be run on VM.

After that, the extension to USB abstraction follows, including the isochronous support patches by Colin Braun, and then the USB-audio driver implementation (that can run on an actual bare metal), as well as the USB runtime PM support.

BTW, until now, I haven't planned for any serious consideration to merge Rust stuff yet. Partly because the above was a pure experiment for me, but another big obstacle is that the whole Rust C binding is limited to built-in vmlinux. With a distribution kernel maintainer hat on, this is absolutely NO-GO -- we really want to avoid built-in. (Graphics is a kind of exception nowadays because of boot support, though.) Can this be worked out soon...?

thanks,

Takashi

#6 lore raw
Quoted 30 lines · On Mon, Oct 12, 2026 at 14:23 Takashi Iwai wrote:
Quoted 28 lines · Tristan de Cacqueray

Hi Takashi and the Rust for Linux maintainers.

I just noticed your mail about an early Rust prototype for the sound subsystem right before I was about to submit this RFC!
https://lore.kernel.org/alsa-devel/[email protected]/

Nevertheless, please allow me to share what I had in mind through this small proof of concept for the rawmidi API. I am looking for feedback on the scope, coordination, and the ownership model rather than a detailed review for merging.

My use case is a new hardware controller using a custom serial protocol. While developing its Rust driver, I needed an interface to ALSA rawmidi. I'm particularly interested in handling rawmidi substream safely to avoid issues like the one fixed by
221253723dc5 ("ALSA: bcd2000: Fix race between rawmidi and disconnect")

So, I wrote some bindings to see how that would look like. This series adds experimental snd_card and snd_rawmidi wrappers, input/output callback traits, and a sample rawmidi faux device using delayed work to simulate incoming MIDI data.

This is not merge-ready. In particular, the prototype does not yet enforce the devres lifetime of the card or the lifetime of its rawmidi wrapper. The substream helper also relies on the driver clearing it before close returns.

Quoted 9 lines
Quoted 4 lines

Here are my questions:

1. Does this rawmidi experiment overlaps with your prototype? If so, I would be happy to coordinate or adapt this experiment to it.

No, my patchset doesn't contain rawmidi support yet.
The sound card abstraction would conflict quite, sure, but it wouldn't be too hard to adapt, I guess.

That's great, I can rebase my rawmidi abstraction onto your branch.

Quoted 4 lines
Quoted 1 line

2. Is rawmidi a useful initial target for ALSA Rust abstraction?

Sure, why not, if it's actually needed? :)

I think Rust could help make midi_ops implementation safer. Would it make sense to port the virmidi driver as a demonstration, or would you recommend a different driver as a starting point?

Quoted 21 lines
Quoted 2 lines

3. Does your prototype mirror the C API 1:1, or for example, does it hide the substream lifecycle? That's the design choice I'm least sure about.

It's mostly a straightforward wrapping of C API, but there are a few twists to adapt Rust-way. The card can be managed in RAII style, too, for example.

I haven't prepared for submission, but you can find the current changes in test/sound-rust branch of sound git tree (either kernel.org or github.com):
https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/log/?h=test/sound-rust
https://github.com/tiwai/sound/tree/test/sound-rust

Those are over 50 commits on top of 7.3-rc5, and I'll likely rebase a bit to rearrange before submission, so beware of changes in future.

The commits begin with a few Rust kernel changes for fixing and addition for the sound support, including the PM support from Beata Michalska (just took what have been posted), followed by ALSA core abstractions for the card, PCM and controls.

Quoted 9 lines

Then it continues to the implementations of 3 actual sound drivers for PCM/control: the dummy driver (with platform and hrtimer), and the ens1370 and intel8x0 drivers for PCI devices to be run on VM.

After that, the extension to USB abstraction follows, including the isochronous support patches by Colin Braun, and then the USB-audio driver implementation (that can run on an actual bare metal), as well as the USB runtime PM support.

Thank you for sharing the branch. I'll take a look.

Quoted 9 lines

BTW, until now, I haven't planned for any serious consideration to merge Rust stuff yet. Partly because the above was a pure experiment for me, but another big obstacle is that the whole Rust C binding is limited to built-in vmlinux. With a distribution kernel maintainer hat on, this is absolutely NO-GO -- we really want to avoid built-in. (Graphics is a kind of exception nowadays because of boot support, though.) Can this be worked out soon...?

Wow, that sounds like a major limitation that I wasn't aware of. I'm not familiar with the status of this issue, but I'd be happy to help if there's something I can contribute.

Thank you for the prompt reply Takashi. I really appreciate it! -Tristan