Skip to contentSkip to conversation

rust: add basic serial device bus abstractions

PATCH Superseded Markus Probst 3 participants 14 messages May 30 – Jun 1

Subsystems (4)

v11 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

v11 cover rust: add basic serial device bus abstractions

This patch series adds the serdev device bus rust abstraction into the kernel.

This abstraction will be used by a driver, which targets the MCU devices in Synology devices.

Kari Argillander also messaged me, stating that he wants to write a watchdog driver with this abstraction (needing initial device data).

This series depends on [1] and [2].

[1]
https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/

---
Changes in v11:
- redo changes from v9 with the following fixes:
- fix memory leak on probe failure
- fix possible access of dropped drvdata from receive_buf
- Link to v10: https://patch.msgid.link/[email protected]

Changes in v10:
- revert everything from v9, except BoundInternal
- use mutex to ensure receive_buf won't be called on a dropped drvdata.
- Link to v9: https://patch.msgid.link/[email protected]

Changes in v9:
- make use of BoundInternal
- use PrivateData wrapper and drop rust_private_data field
- use non-devm version of serdev_device_open
- Link to v8: https://patch.msgid.link/[email protected]

Changes in v8:
- adapted to driver-lifetime v5 patch series
- add MAINTAINERS file patch
- Link to v7: https://patch.msgid.link/[email protected]

Changes in v7:
- adapted to driver-lifetime patch series
- Link to v6: https://patch.msgid.link/[email protected]

Changes in v6:
- rebased onto v7.1-rc1
- Link to v5: https://patch.msgid.link/[email protected]

Changes in v5:
- fix typo in documentation
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- fixed not selecting rust serdev abstraction in sample
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- fix vertical import style
- add Kconfig entry for the rust abstraction
- fix documentation in include/linux/serdev.h
- rename private_data to rust_private_data
- fix complete_all <-> wait_for_completion typo
- move drvdata_borrow call after the completion
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- fix documentation in serdev::Driver::write and serdev::Driver::write_all
- remove use of dev_info in probe from the sample
- remove properties_parse from the sample
- add optional baudrate property to the sample
- remove 1. patch
- remove TryFrom<&device::Device<Ctx>> for &serdev::Device<Ctx> implementation
- fix import style
- add patch to return reference in devres::register to fix safety
issue
- add patch to add private data to serdev_device, to fix Device.drvdata() from failing
- simplify abstraction by removing ability to receive the initial transmission. It may be added later in a separate patch series if needed.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Markus Probst (3):
rust: add basic serial device bus abstractions
samples: rust: add Rust serial device bus sample device driver
MAINTAINERS: serdev: Add self for serdev

 MAINTAINERS                        |   5 +-
 drivers/tty/serdev/Kconfig         |   7 +
 rust/bindings/bindings_helper.h    |   1 +
 rust/helpers/helpers.c             |   1 +
 rust/helpers/serdev.c              |  22 ++
 rust/kernel/lib.rs                 |   2 +
 rust/kernel/serdev.rs              | 590 +++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig               |  11 +
 samples/rust/Makefile              |   1 +
 samples/rust/rust_driver_serdev.rs |  91 ++++++
 10 files changed, 730 insertions(+), 1 deletion(-)

---
base-commit: 9e171fc1d7d7ab847a750c03571c87ac3c17bd84
change-id: 20251217-rust_serdev-ee5481e9085c
prerequisite-message-id: [email protected]
prerequisite-patch-id: d2aebf69b153c039bbed1d0ed26906708fd22534
prerequisite-patch-id: 84b28da2f5de20fc1785095c647b2ffc35d969a5
prerequisite-patch-id: 67318671a5eed5fb4ad23a450f1cf0e442bf8ca2
prerequisite-message-id: [email protected]
prerequisite-patch-id: b84db329d4372a175cb8d49e4e88c3eecf7eb228
prerequisite-patch-id: 2c30303f409cc8288cc87e241920219f5ddd8390
prerequisite-patch-id: 4e4f0ad370d763ad00b0f75b91fa216f2cc95953
prerequisite-patch-id: 5bcd6b37f3498feebda275dfef78136eba34004e
prerequisite-patch-id: 872b0982f3e5e7d1698d9df3b325e4cd27b27789
prerequisite-patch-id: 3a3c7749e017d9335f58497404d1350e96caf471
prerequisite-patch-id: 3526c9154f581497a11465b936d83ef61a875454
prerequisite-patch-id: 65d8c757b52475c2acc7d22ddc92cd3f0152b55d
prerequisite-patch-id: 4bd31f1414d5248dc080884caadf5f21684a8427
prerequisite-patch-id: 7beadbb0da3e589ed86d12f512d1c83427dd82b4
prerequisite-patch-id: 12cd0f67ffd27347f90c065db491945908206b7f
prerequisite-patch-id: 4642e31f66331f6c3b579377111ea733dbb3a11c
prerequisite-patch-id: 52d67b40b4396c741e2222d6a5bc7927abcb77aa
prerequisite-patch-id: 74ca82ff26cf9c7a993757c87db8be62006e820f
prerequisite-patch-id: 466fb9fa7febbffd8ef51b311c7d9893c11fc0f0
prerequisite-patch-id: e515cd98b06e26721cbbe6a4fbacd251d0073b63
prerequisite-patch-id: 8dc8e75d9f6499a554ef7e474bbacdbf3660a9f2
prerequisite-patch-id: 5fdb9f71dca2f44dd293760a60db125b770f1f55
prerequisite-patch-id: c766a24c2d5064f5ec09daada0b8e8fba862d3aa
prerequisite-patch-id: b768f6456d35fa7a80c015e34bbdba6082dbd593
prerequisite-patch-id: 6a8b17234f12f7084e6e2ce843a7031b0a891ce4
prerequisite-patch-id: 98b2deb9e60c1f28f90c5ee34fd608aaa9fd9420
prerequisite-patch-id: 774b29be66e641ee50cedb4704cf49d8b9fabf50
prerequisite-patch-id: cf95dc936cfc4b3a7a363435a51a48d9009645b3
prerequisite-message-id: [email protected]
prerequisite-patch-id: 310c6bee038ca3909a8e5e58ec12b74f7189b869
prerequisite-patch-id: 92812c3d42b29504838e6dc66c307ff5c035bb5e

author maintainer
#1 lore raw

PATCH v11 1/3 rust: add basic serial device bus abstractions

Implement the basic serial device bus abstractions required to write a serial device bus device driver with or without the need for initial device data. This includes the following data structures:

The serdev::Driver trait represents the interface to the driver.

The serdev::Device abstraction represents a struct serdev_device.

In order to provide the Serdev specific parts to a generic driver::Registration the driver::RegistrationOps trait is implemented by serdev::Adapter.

---
 MAINTAINERS                     |   2 +
 drivers/tty/serdev/Kconfig      |   7 +
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/helpers.c          |   1 +
 rust/helpers/serdev.c           |  22 ++
 rust/kernel/lib.rs              |   2 +
 rust/kernel/serdev.rs           | 590 ++++++++++++++++++++++++++++++++++++++++
 7 files changed, 625 insertions(+)
MAINTAINERS +2 -0
index 4e118f704699..d2f608ff8ca0 100644
@@ -24276,6 +24276,8 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/serial/serial.yaml
 F:	drivers/tty/serdev/
 F:	include/linux/serdev.h
+F:	rust/helpers/serdev.c
+F:	rust/kernel/serdev.rs
 
 SERIAL IR RECEIVER
 M:	Sean Young <[email protected]>
drivers/tty/serdev/Kconfig +7 -0
index 46ae732bfc68..e6dfe949ad01 100644
@@ -9,6 +9,13 @@ menuconfig SERIAL_DEV_BUS
 
 	  Note that you typically also want to enable TTY port controller support.
 
+config RUST_SERIAL_DEV_BUS_ABSTRACTIONS
+	bool "Rust Serial device bus abstractions"
+	depends on RUST
+	select SERIAL_DEV_BUS
+	help
+	  This enables the Rust abstraction for the serial device bus API.
+
 if SERIAL_DEV_BUS
 
 config SERIAL_DEV_CTRL_TTYPORT
rust/bindings/bindings_helper.h +1 -0
index 446dbeaf0866..4e42635b8607 100644
@@ -84,6 +84,7 @@
 #include <linux/regulator/consumer.h>
 #include <linux/sched.h>
 #include <linux/security.h>
+#include <linux/serdev.h>
 #include <linux/slab.h>
 #include <linux/sys_soc.h>
 #include <linux/task_work.h>
rust/helpers/helpers.c +1 -0
index 38b34518eff1..2fb8506a748a 100644
@@ -86,6 +86,7 @@
 #include "regulator.c"
 #include "scatterlist.c"
 #include "security.c"
+#include "serdev.c"
 #include "signal.c"
 #include "slab.c"
 #include "spinlock.c"
rust/helpers/serdev.c new file +22 -0
new file mode 100644
index 000000000000..c52b78ca3fc7
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/serdev.h>
+
+__rust_helper
+void rust_helper_serdev_device_driver_unregister(struct serdev_device_driver *sdrv)
+{
+	serdev_device_driver_unregister(sdrv);
+}
+
+__rust_helper
+void rust_helper_serdev_device_put(struct serdev_device *serdev)
+{
+	serdev_device_put(serdev);
+}
+
+__rust_helper
+void rust_helper_serdev_device_set_client_ops(struct serdev_device *serdev,
+					      const struct serdev_device_ops *ops)
+{
+	serdev_device_set_client_ops(serdev, ops);
+}
rust/kernel/lib.rs +2 -0
index b72b2fbe046d..83bc2c312241 100644
@@ -118,6 +118,8 @@
 pub mod scatterlist;
 pub mod security;
 pub mod seq_file;
+#[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
+pub mod serdev;
 pub mod sizes;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
rust/kernel/serdev.rs new file +590 -0

590 lines not on this page · raw message

Signature · 1 line
2.53.0
maintainer
#2 lore raw
Quoted 10 lines · On Sun May 31, 2026 at 12:51 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +10 -0
+#[pinned_drop]
+impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
+    fn drop(self: Pin<&mut Self>) {
+        let mut active = self.active.lock();
+        if *active {
+            // SAFETY:
+            // - We have exclusive access to `self.driver`.
+            // - `self.driver` is guaranteed to be initialized.
+            unsafe { (*self.driver.get()).assume_init_drop() };
+            *active = false;

rust/kernel/serdev.rs line 158

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        }
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}

Just in case it came across otherwise, I did not mean to push for you to go for this approach. We just kept discussing it because it let to the (to me more interesting) discussion around the LED class device abstraction.

While this approach gets us rid of an extra allocation and the rust_private_data pointer in struct serdev_device it also turns out a bit more convoluted.

That said, both are correct, and I won't object either one; up to you and the serdev / tty maintainers.

Please wait a bit before resending, so other people can comment on this as well.

rust/kernel/serdev.rs line 255

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };

CoreInternal snuck back in, should be BoundInternal.

rust/kernel/serdev.rs line 261

Quoted 6 lines
rust/kernel/serdev.rs new file +6 -0
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();

I think SRCU would be a much better fit, but the code didn't land yet, so the mutex seems fine for now. But I'd probably add a TODO.

Quoted 19 lines
rust/kernel/serdev.rs new file +19 -0
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
reviewer
#3 lore raw
Quoted 54 lines · On Sun, 31 May 2026 01:51:08 +0200 Danilo Krummrich <[email protected]> wrote:
Quoted 10 lines · On Sun May 31, 2026 at 12:51 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +10 -0
+#[pinned_drop]
+impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
+    fn drop(self: Pin<&mut Self>) {
+        let mut active = self.active.lock();
+        if *active {
+            // SAFETY:
+            // - We have exclusive access to `self.driver`.
+            // - `self.driver` is guaranteed to be initialized.
+            unsafe { (*self.driver.get()).assume_init_drop() };
+            *active = false;

rust/kernel/serdev.rs line 158

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        }
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}

Just in case it came across otherwise, I did not mean to push for you to go for this approach. We just kept discussing it because it let to the (to me more interesting) discussion around the LED class device abstraction.

While this approach gets us rid of an extra allocation and the rust_private_data pointer in struct serdev_device it also turns out a bit more convoluted.

That said, both are correct, and I won't object either one; up to you and the serdev / tty maintainers.

Please wait a bit before resending, so other people can comment on this as well.

rust/kernel/serdev.rs line 255

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };

CoreInternal snuck back in, should be BoundInternal.

rust/kernel/serdev.rs line 261

Quoted 6 lines
rust/kernel/serdev.rs new file +6 -0
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();
Quoted 3 lines

I think SRCU would be a much better fit, but the code didn't land yet, so the mutex seems fine for now. But I'd probably add a TODO.

Jfyi v9 is on the list [1] and I would say we are pretty close on taking that.

Thanks,
Onur

[1]: https://lore.kernel.org/rust-for-linux/[email protected]

Quoted 19 lines
Quoted 19 lines
rust/kernel/serdev.rs new file +19 -0
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
reviewer
#4 lore raw
Quoted 61 lines · On Sun, 31 May 2026 09:58:34 +0300 Onur Özkan <[email protected]> wrote:
Quoted 54 lines · On Sun, 31 May 2026 01:51:08 +0200 Danilo Krummrich <[email protected]> wrote:
Quoted 10 lines · On Sun May 31, 2026 at 12:51 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +10 -0
+#[pinned_drop]
+impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
+    fn drop(self: Pin<&mut Self>) {
+        let mut active = self.active.lock();
+        if *active {
+            // SAFETY:
+            // - We have exclusive access to `self.driver`.
+            // - `self.driver` is guaranteed to be initialized.
+            unsafe { (*self.driver.get()).assume_init_drop() };
+            *active = false;

rust/kernel/serdev.rs line 158

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        }
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}

Just in case it came across otherwise, I did not mean to push for you to go for this approach. We just kept discussing it because it let to the (to me more interesting) discussion around the LED class device abstraction.

While this approach gets us rid of an extra allocation and the rust_private_data pointer in struct serdev_device it also turns out a bit more convoluted.

That said, both are correct, and I won't object either one; up to you and the serdev / tty maintainers.

Please wait a bit before resending, so other people can comment on this as well.

rust/kernel/serdev.rs line 255

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };

CoreInternal snuck back in, should be BoundInternal.

rust/kernel/serdev.rs line 261

Quoted 6 lines
rust/kernel/serdev.rs new file +6 -0
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();
Quoted 3 lines

I think SRCU would be a much better fit, but the code didn't land yet, so the mutex seems fine for now. But I'd probably add a TODO.

Quoted 7 lines

Jfyi v9 is on the list [1] and I would say we are pretty close on taking that.

Thanks,
Onur

[1]: https://lore.kernel.org/rust-for-linux/[email protected]

I pasted the wrong link, sorry.

It should have been this instead:

https://lore.kernel.org/all/[email protected]

Quoted 19 lines
Quoted 19 lines
Quoted 19 lines
rust/kernel/serdev.rs new file +19 -0
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
author maintainer
#5 lore raw
In reply to Onur Özkan
Quoted 57 lines · Onur Özkan
Quoted 54 lines · On Sun, 31 May 2026 01:51:08 +0200 Danilo Krummrich <[email protected]> wrote:
Quoted 10 lines · On Sun May 31, 2026 at 12:51 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +10 -0
+#[pinned_drop]
+impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
+    fn drop(self: Pin<&mut Self>) {
+        let mut active = self.active.lock();
+        if *active {
+            // SAFETY:
+            // - We have exclusive access to `self.driver`.
+            // - `self.driver` is guaranteed to be initialized.
+            unsafe { (*self.driver.get()).assume_init_drop() };
+            *active = false;

rust/kernel/serdev.rs line 158

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        }
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}

Just in case it came across otherwise, I did not mean to push for you to go for this approach. We just kept discussing it because it let to the (to me more interesting) discussion around the LED class device abstraction.

While this approach gets us rid of an extra allocation and the rust_private_data pointer in struct serdev_device it also turns out a bit more convoluted.

That said, both are correct, and I won't object either one; up to you and the serdev / tty maintainers.

Please wait a bit before resending, so other people can comment on this as well.

rust/kernel/serdev.rs line 255

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };

CoreInternal snuck back in, should be BoundInternal.

Quoted 6 lines
rust/kernel/serdev.rs new file +6 -0
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();
Quoted 5 lines
Quoted 3 lines

I think SRCU would be a much better fit, but the code didn't land yet, so the mutex seems fine for now. But I'd probably add a TODO.

Jfyi v9 is on the list [1] and I would say we are pretty close on taking that.

How close? Should I rebase this patch on top of the srcu patch series?

Thanks
- Markus Probst

Quoted 25 lines

Thanks,
Onur

[1]: https://lore.kernel.org/rust-for-linux/[email protected]

Quoted 19 lines
Quoted 19 lines
rust/kernel/serdev.rs new file +19 -0
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
maintainer
#6 lore raw
Quoted 1 line · Markus Probst

How close? Should I rebase this patch on top of the srcu patch series?

Since it isn't blocking you, it would only make sense if SRCU makes it this cycle, but this series does not.

author maintainer
#7 lore raw
In reply to Danilo Krummrich
Quoted 54 lines · Danilo Krummrich
Quoted 10 lines · On Sun May 31, 2026 at 12:51 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +10 -0
+#[pinned_drop]
+impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
+    fn drop(self: Pin<&mut Self>) {
+        let mut active = self.active.lock();
+        if *active {
+            // SAFETY:
+            // - We have exclusive access to `self.driver`.
+            // - `self.driver` is guaranteed to be initialized.
+            unsafe { (*self.driver.get()).assume_init_drop() };
+            *active = false;

rust/kernel/serdev.rs line 158

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        }
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}

Just in case it came across otherwise, I did not mean to push for you to go for this approach. We just kept discussing it because it let to the (to me more interesting) discussion around the LED class device abstraction.

While this approach gets us rid of an extra allocation and the rust_private_data pointer in struct serdev_device it also turns out a bit more convoluted.

That said, both are correct, and I won't object either one; up to you and the serdev / tty maintainers.

Please wait a bit before resending, so other people can comment on this as well.

rust/kernel/serdev.rs line 255

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };

CoreInternal snuck back in, should be BoundInternal.

rust/kernel/serdev.rs line 261

Quoted 6 lines
rust/kernel/serdev.rs new file +6 -0
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();
Quoted 2 lines

I think SRCU would be a much better fit, but the code didn't land yet, so the mutex seems fine for now. But I'd probably add a TODO.

I just noticed, is it even possible to use SRCU here? Currently the mutex not only ensures that no drvdata access happens after drvdata drop, but also that the receive_buf waits for the probe to complete, as the drvdata hasn't been initialized yet.

(drvdata refers to PrivateData.driver in this context, not the whole PrivateData)

Thanks
- Markus Probst

Quoted 20 lines
Quoted 20 lines
rust/kernel/serdev.rs new file +19 -0
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
maintainer
#8 lore raw
Quoted 4 lines · Markus Probst

I just noticed, is it even possible to use SRCU here? Currently the mutex not only ensures that no drvdata access happens after drvdata drop, but also that the receive_buf waits for the probe to complete, as the drvdata hasn't been initialized yet.

Yeah, if you drop the completion, you need the mutex.

(In case it wasn't discussed in previous versions already, there is also the option to just attach separate private data to the receive callback, which would avoid this synchonization problem in the first place.

You could have serdev::Device<Core>::open(), which takes its own private data and a corresponding close(), this way you'd allow drivers to control whether they want the serial line "open" or not. You just need to make sure it is closed eventually.)

That said, I don't know what turns out to be the better approach. And maybe it simply isn't something this initial series has to tackle? I think your driver does not implement the receive callback?

author maintainer
#9 lore raw
Quoted 7 lines · Danilo Krummrich
Quoted 4 lines · Markus Probst

I just noticed, is it even possible to use SRCU here? Currently the mutex not only ensures that no drvdata access happens after drvdata drop, but also that the receive_buf waits for the probe to complete, as the drvdata hasn't been initialized yet.

Yeah, if you drop the completion, you need the mutex.

Is the performance impact on an mutex or on srcu + completion higher?

Quoted 9 lines

(In case it wasn't discussed in previous versions already, there is also the option to just attach separate private data to the receive callback, which would avoid this synchonization problem in the first place.

You could have serdev::Device<Core>::open(), which takes its own private data and a corresponding close(), this way you'd allow drivers to control whether they want the serial line "open" or not. You just need to make sure it is closed eventually.)

This would add complexity with types, as we need to ensure that write, set_baudrate, set_parity etc. does not run when closed.

Quoted 4 lines

That said, I don't know what turns out to be the better approach. And maybe it simply isn't something this initial series has to tackle? I think your driver does not implement the receive callback?

The initial driver with only leds: no.

That changes once the driver also takes care of hwmon (ADC sensor and fan failure) and input (power button and possibly other buttons).

Thanks
- Markus Probst

maintainer
#10 lore raw
Quoted 9 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 4 lines · Markus Probst

I just noticed, is it even possible to use SRCU here? Currently the mutex not only ensures that no drvdata access happens after drvdata drop, but also that the receive_buf waits for the probe to complete, as the drvdata hasn't been initialized yet.

Yeah, if you drop the completion, you need the mutex.

Is the performance impact on an mutex or on srcu + completion higher?

Weighing in the completion, the mutex probably wins as it will always be uncontested under normal operation.

Quoted 11 lines
Quoted 9 lines

(In case it wasn't discussed in previous versions already, there is also the option to just attach separate private data to the receive callback, which would avoid this synchonization problem in the first place.

You could have serdev::Device<Core>::open(), which takes its own private data and a corresponding close(), this way you'd allow drivers to control whether they want the serial line "open" or not. You just need to make sure it is closed eventually.)

This would add complexity with types, as we need to ensure that write, set_baudrate, set_parity etc. does not run when closed.

Right, but looking at a few serdev drivers, there seem to be a few cases where drivers need to close and re-open.

Quoted 7 lines
Quoted 3 lines

That said, I don't know what turns out to be the better approach. And maybe it simply isn't something this initial series has to tackle? I think your driver does not implement the receive callback?

The initial driver with only leds: no.

That changes once the driver also takes care of hwmon (ADC sensor and fan failure) and input (power button and possibly other buttons).

Maybe drop it from this initial series then and revisit with the first user?

author maintainer
#11 lore raw
Quoted 23 lines · Danilo Krummrich
Quoted 9 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 4 lines · Markus Probst

I just noticed, is it even possible to use SRCU here? Currently the mutex not only ensures that no drvdata access happens after drvdata drop, but also that the receive_buf waits for the probe to complete, as the drvdata hasn't been initialized yet.

Yeah, if you drop the completion, you need the mutex.

Is the performance impact on an mutex or on srcu + completion higher?

Weighing in the completion, the mutex probably wins as it will always be uncontested under normal operation.

Quoted 9 lines
Quoted 9 lines

(In case it wasn't discussed in previous versions already, there is also the option to just attach separate private data to the receive callback, which would avoid this synchonization problem in the first place.

You could have serdev::Device<Core>::open(), which takes its own private data and a corresponding close(), this way you'd allow drivers to control whether they want the serial line "open" or not. You just need to make sure it is closed eventually.)

Quoted 5 lines
Quoted 2 lines

This would add complexity with types, as we need to ensure that write, set_baudrate, set_parity etc. does not run when closed.

Right, but looking at a few serdev drivers, there seem to be a few cases where drivers need to close and re-open.

That is something we could consider once there is a user.

I am certain it would make it more complex, not less.

Quoted 10 lines
Quoted 8 lines
Quoted 4 lines

That said, I don't know what turns out to be the better approach. And maybe it simply isn't something this initial series has to tackle? I think your driver does not implement the receive callback?

The initial driver with only leds: no.

That changes once the driver also takes care of hwmon (ADC sensor and fan failure) and input (power button and possibly other buttons).

Maybe drop it from this initial series then and revisit with the first user?

I would prefer it with this series.

Except for probe and remove there should be no overhead if receive_buf is not implemented.

As it will be needed eventually and it is basic serdev functionality, I don't see a reason to not include it now.

Thanks
- Markus Probst

author maintainer
#12 lore raw

PATCH v11 2/3 samples: rust: add Rust serial device bus sample device driver

In reply to Markus Probst

Add a sample Rust serial device bus device driver illustrating the usage of the serial device bus abstractions.

This drivers probes through either a match of device / driver name or a match within the OF ID table.

---
 MAINTAINERS                        |  1 +
 samples/rust/Kconfig               | 11 +++++
 samples/rust/Makefile              |  1 +
 samples/rust/rust_driver_serdev.rs | 91 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 104 insertions(+)
MAINTAINERS +1 -0
index d2f608ff8ca0..fa3f20f0cc4f 100644
@@ -24278,6 +24278,7 @@ F:	drivers/tty/serdev/
 F:	include/linux/serdev.h
 F:	rust/helpers/serdev.c
 F:	rust/kernel/serdev.rs
+F:	samples/rust/rust_driver_serdev.rs
 
 SERIAL IR RECEIVER
 M:	Sean Young <[email protected]>
samples/rust/Kconfig +11 -0
index c49ab9106345..31d62533ef25 100644
@@ -161,6 +161,17 @@ config SAMPLE_RUST_DRIVER_AUXILIARY
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DRIVER_SERDEV
+	tristate "Serial Device Bus Device Driver"
+	select RUST_SERIAL_DEV_BUS_ABSTRACTIONS
+	help
+	  This option builds the Rust serial device bus driver sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_driver_serdev.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_SOC
 	tristate "SoC Driver"
 	select SOC_BUS
samples/rust/Makefile +1 -0
index 6c0aaa58cccc..b986b681cde5 100644
@@ -14,6 +14,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_USB)		+= rust_driver_usb.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY)	+= rust_driver_auxiliary.o
+obj-$(CONFIG_SAMPLE_RUST_DRIVER_SERDEV)		+= rust_driver_serdev.o
 obj-$(CONFIG_SAMPLE_RUST_CONFIGFS)		+= rust_configfs.o
 obj-$(CONFIG_SAMPLE_RUST_SOC)			+= rust_soc.o
 
samples/rust/rust_driver_serdev.rs new file +91 -0

91 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#13 lore raw

PATCH v11 3/3 MAINTAINERS: serdev: Add self for serdev

In reply to Markus Probst

Rob mentioned he needs to find someone else to maintain serdev.

---
 MAINTAINERS | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
MAINTAINERS +1 -1
index fa3f20f0cc4f..58db6aedf45a 100644
@@ -24270,7 +24270,7 @@ F:	drivers/iio/chemical/sps30_i2c.c
 F:	drivers/iio/chemical/sps30_serial.c
 
 SERIAL DEVICE BUS
-M:	Rob Herring <[email protected]>
+M:	Markus Probst <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/devicetree/bindings/serial/serial.yaml
Signature · 1 line
2.53.0