Skip to contentSkip to conversation

rust: add basic serial device bus abstractions

PATCH Superseded Markus Probst 2 participants 6 messages Jul 18

Subsystems (4)

v15 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

v15 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].

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

---
Changes in v15:
- fix documentation typo
- add documentation for PrivateData::active
- adding missing #[inline] attributes
- replace serdev::Timeout with the use of impl Into<Jiffies>
- This replaces https://lore.kernel.org/rust-for-linux/[email protected]/
- Link to v14: https://patch.msgid.link/[email protected]

Changes in v14:
- fix issues reported by Sashiko:
- fix missing Sync
- fix write buffers allowed with data.len() > i32::MAX
- fix sample driver possibly stalling on full tx buffer
- Link to v13: https://patch.msgid.link/[email protected]

Changes in v13:
- Added Acked-by trailer from Rob. Consider this a RESEND.
- Link to v12: https://patch.msgid.link/[email protected]

Changes in v12:
- fix CoreInternal instead of BoundInternal
- Link to v11: https://patch.msgid.link/[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              | 605 +++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig               |  11 +
 samples/rust/Makefile              |   1 +
 samples/rust/rust_driver_serdev.rs |  90 ++++++
 10 files changed, 744 insertions(+), 1 deletion(-)

---
base-commit: 1137d8b5df06137fb49513cc923b3b24d94cb809
change-id: 20251217-rust_serdev-ee5481e9085c
prerequisite-message-id: [email protected]
prerequisite-patch-id: 310c6bee038ca3909a8e5e58ec12b74f7189b869
prerequisite-patch-id: 92812c3d42b29504838e6dc66c307ff5c035bb5e

author maintainer
#1 lore raw

PATCH v15 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           | 605 ++++++++++++++++++++++++++++++++++++++++
 7 files changed, 640 insertions(+)
MAINTAINERS +2 -0
index 806bd2d80d15..cd735d227892 100644
@@ -24568,6 +24568,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 1124785e210b..fe7c505da236 100644
@@ -85,6 +85,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 998e31052e66..6921a5ecb78a 100644
@@ -87,6 +87,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 9512af7156df..d5ca17336739 100644
@@ -119,6 +119,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 +605 -0

605 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#3 lore raw

PATCH v15 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 | 90 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 103 insertions(+)
MAINTAINERS +1 -0
index cd735d227892..7d32aa7f42a4 100644
@@ -24570,6 +24570,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 +90 -0

90 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#5 lore raw

PATCH v15 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 7d32aa7f42a4..d092042fed31 100644
@@ -24562,7 +24562,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.54.0
#4 lore raw

Re: [PATCH v15 2/3] samples: rust: add Rust serial device bus sample device driver

In reply to Markus Probst
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Incorrect device tree property used for serial baud rate configuration. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Incorrect device tree property used for serial baud rate configuration. --

--- Patch [2]: [PATCH v15 2/3] samples: rust: add Rust serial device bus sample device driver --- commit 7885024c6abc3e1d37bf3499dc357753c532b4d5
Author: Markus Probst <[email protected]>

samples: rust: add Rust serial device bus sample device driver

This commit adds a sample Rust serial device bus device driver illustrating the usage of the serial device bus abstractions. The driver probes through either a match of device or driver name, or a match within the OF ID table.

Quoted 6 lines
samples/rust/rust_driver_serdev.rs new file +0 -0
new file mode 100644
index 0000000000000..a12b1412db30c
@@ -0,0 +1,90 @@

[ ... ]

samples/rust/rust_driver_serdev.rs line 53

Quoted 12 lines
samples/rust/rust_driver_serdev.rs new file +12 -0
+    fn probe<'bound>(
+        sdev: &'bound serdev::Device<Core<'_>>,
+        _info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
+        let dev = sdev.as_ref();
+
+        dev_dbg!(dev, "Probe Rust Serial device bus device driver sample.\n");
+
+        if sdev
+            .set_baudrate(
+                dev.fwnode()
+                    .and_then(|fwnode| fwnode.property_read(c"baudrate").optional())

[Severity: Medium]
Does this use the correct device tree property for the serial baud rate?

Standard serial device nodes typically use current-speed rather than baudrate. If baudrate is queried, will the driver fail to read the configured rate from standard nodes and silently fall back to the 115200 default?

Since this is a sample driver, would it be better to query current-speed so it serves as a correct template for new developers?

Quoted 6 lines
samples/rust/rust_driver_serdev.rs new file +6 -0
+                    .unwrap_or(115200),
+            )
+            .is_err()
+        {
+            return Err(EINVAL);
+        }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#2 lore raw
In reply to Markus Probst
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] Delayed device closure and improperly synchronized teardown lead to race conditions, causing NULL…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] Delayed device closure and improperly synchronized teardown lead to race conditions, causing NULL pointer dereferences or Use-After-Free in receive_buf_callback during device unbind or probe failure.
- [High] Holding the active mutex across driver initialization and teardown causes deadlocks if a driver communicates synchronously with the hardware.
- [Low] Code fails to compile due to the use of an undefined type device::BoundInternal and an unavailable drvdata_borrow method for it.
- [Low] Small forwarding functions in the Device abstraction lack the required #[inline] annotation.
--

--- Patch [1]: [PATCH v15 1/3] rust: add basic serial device bus abstractions --- commit 08bb3dcc665ba5840df1251ed6f1adfe75a7761a
Author: Markus Probst <[email protected]>

rust: add basic serial device bus abstractions

This commit introduces the basic abstractions for writing serial device bus (serdev) drivers in Rust. It provides traits and structures representing serdev::Driver, serdev::Device, and adapter logic to bridge the C API.

Quoted 5 lines
rust/kernel/serdev.rs new file +0 -0
new file mode 100644
index 0000000000000..0fdb37cff15dd

[ ... ]

rust/kernel/serdev.rs line 135

Quoted 9 lines
rust/kernel/serdev.rs new file +9 -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() };

[Severity: High]
Does this code introduce a deadlock? It looks like the active mutex is held across the driver drop execution. If the driver communicates synchronously with the hardware and waits for a response, it might block forever because Adapter::receive_buf_callback() also waits on this active mutex.

rust/kernel/serdev.rs line 144

Quoted 9 lines
rust/kernel/serdev.rs new file +9 -0
+            *active = false;
+        }
+        drop(active);
+
+        // 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()) };

[Severity: High]
Could this result in a NULL pointer dereference or use-after-free? The device is closed here, but the driver data has already been cleared by drvdata_obtain() in the probe error path or post_unbind_rust. This leaves a window where the device is still active, and if data arrives, receive_buf_callback() might blindly dereference the NULL drvdata pointer.

Quoted 3 lines
rust/kernel/serdev.rs new file +3 -0
+        }
+    }
+}

[ ... ]

Quoted 1 line

+ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi::c_int {

[ ... ]

Quoted 7 lines
rust/kernel/serdev.rs new file +7 -0
+            let private_data = ScopeGuard::new_with_data(private_data, |_| {
+                // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
+                drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
+            });
+            let mut active = private_data.active.lock();
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.

rust/kernel/serdev.rs line 192

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+            unsafe { bindings::serdev_device_set_client_ops(sdev.as_raw(), Self::OPS) };
+
+            // SAFETY: The serial device bus only ever calls the probe callback with a valid pointer
+            // to a `serdev_device`.
+            to_result(unsafe { bindings::serdev_device_open(sdev.as_raw()) })?;
+
+            // SAFETY: We have exclusive access to `private_data.open`.
+            unsafe { *private_data.open.get() = true };
+
+            let data = T::probe(sdev, info);

[Severity: High]
Is it safe to hold the active lock across the entire driver initialization in T::probe? If a driver needs to send a command to the serial device during probe and wait for an acknowledgment, it will deadlock since receive_buf_callback() unconditionally waits on this same active mutex.

Quoted 3 lines
rust/kernel/serdev.rs new file +3 -0
+
+            // SAFETY: We have exclusive access to `private_data.driver`.
+            let driver = unsafe { &mut *private_data.driver.get() };

[ ... ]

rust/kernel/serdev.rs line 244

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::BoundInternal>>() };

[Severity: Low]
Will this compile when CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS is enabled? It appears device::BoundInternal is an undefined type, as the valid contexts in the kernel are Normal, Bound, Core, and CoreInternal.

rust/kernel/serdev.rs line 249

Quoted 5 lines
rust/kernel/serdev.rs new file +5 -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>>() };

[Severity: Low]
Does this method exist? It seems drvdata_borrow() is only implemented for Device<CoreInternal>, so even if BoundInternal existed, this method might not be available.

Quoted 1 line

+ let active = private_data.active.lock();

[Severity: High]
Could this unconditionally block and cause a deadlock? As mentioned earlier, if probe_callback() or PrivateData::drop() holds the active lock while waiting for incoming data, this callback will be blocked and the workqueue will deadlock.

Quoted 2 lines
rust/kernel/serdev.rs new file +2 -0
+
+        if !*active {

[ ... ]

rust/kernel/serdev.rs line 577

Quoted 5 lines
rust/kernel/serdev.rs new file +5 -0
+// SAFETY: Instances of `Device` are always reference-counted.
+unsafe impl AlwaysRefCounted for Device {
+    fn inc_ref(&self) {
+        self.as_ref().inc_ref();
+    }

[Severity: Low]
this isn't a bug, but shouldn't small forwarding functions like this be annotated with #[inline] according to the Rust coding guidelines?

rust/kernel/serdev.rs line 582

Quoted 5 lines
rust/kernel/serdev.rs new file +5 -0
+
+    unsafe fn dec_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
+        unsafe { bindings::serdev_device_put(obj.cast().as_ptr()) }
+    }

[Severity: Low]
this isn't a bug, but does this function also need an #[inline] annotation for being a small forwarding function?

rust/kernel/serdev.rs line 593

Quoted 11 lines
rust/kernel/serdev.rs new file +11 -0
+}
+
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
+    fn as_ref(&self) -> &device::Device<Ctx> {
+        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
+        // `struct serdev_device`.
+        let dev = unsafe { &raw mut (*self.as_raw()).dev };
+
+        // SAFETY: `dev` points to a valid `struct device`.
+        unsafe { device::Device::from_raw(dev) }
+    }

[Severity: Low]
this isn't a bug, but should this be annotated with #[inline] as well?

Quoted 1 line

+}

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1