Skip to contentSkip to conversation

rust: add basic serial device bus abstractions

PATCH Superseded Markus Probst 2 participants 8 messages Jul 12 – Jul 15

Subsystems (4)

v13 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

v13 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 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              | 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: 4c45e14df2f4e77982ad70d6d8e3fe750edd4c37
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 v13 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 4a8b0fd665ce..00d977ce7028 100644
@@ -24567,6 +24567,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 +590 -0

590 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#4 lore raw

PATCH v13 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 00d977ce7028..ed4f8f2f17d5 100644
@@ -24569,6 +24569,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.54.0
author maintainer
#7 lore raw

PATCH v13 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 ed4f8f2f17d5..c2e3430ac213 100644
@@ -24561,7 +24561,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
#2 lore raw
In reply to Markus Probst
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] `serdev::Driver::Data` is missing a `Sync` trait bound, allowing safe code to trigger Undefined…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] serdev::Driver::Data is missing a Sync trait bound, allowing safe code to trigger Undefined Behavior via data races.
- [High] The framework defers serdev_device_close() to PrivateData::drop and fails to close the device synchronously in remove_callback, creating a race window that leads to NULL pointer dereferences, Use-After-Free, and deadlocks.
- [High] Holding the active mutex across T::probe introduces a cyclic AB-BA deadlock if a driver synchronously awaits receive data during initialization.
- [Medium] write_all improperly casts the ssize_t return value of serdev_device_write to i32, which causes successful writes larger than 2GB to be incorrectly treated as negative error codes. --

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

rust: add basic serial device bus abstractions

This commit introduces the Rust abstractions for the serial device bus API. It adds the serdev::Driver trait, the serdev::Device abstraction representing a struct serdev_device, and adapter mechanisms to register drivers with the generic driver core.

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

[ ... ]

Quoted 10 lines
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()) };
+        }
+    }
+}

[Severity: High]
Does deferring serdev_device_close() to drop() introduce an AB-BA deadlock?

If receive_buf_callback() executes on the receive workqueue while PrivateData is being dropped, the receive thread will block waiting for the 'active' mutex. Meanwhile, this drop() method holds the 'active' mutex and calls serdev_device_close(), which synchronously flushes the workqueue. This seems like it would cause the two threads to deadlock.

[ ... ]

Quoted 1 line

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

[ ... ]

rust/kernel/serdev.rs line 203

Quoted 13 lines
rust/kernel/serdev.rs new file +13 -0
+            let mut active = private_data.active.lock();
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            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]
Can holding the 'active' mutex across T::probe() cause a cyclic deadlock during device initialization?

If a driver sends a hardware identification command in its probe() routine and synchronously waits for the response, the incoming data will trigger receive_buf_callback() on a separate thread. Because receive_buf_callback() unconditionally attempts to acquire the 'active' mutex, it will block forever while probe_callback() holds the mutex and waits for the receive data.

[ ... ]

Quoted 12 lines
rust/kernel/serdev.rs new file +12 -0
+    extern "C" fn remove_callback(sdev: *mut bindings::serdev_device) {
+        // SAFETY: The serial device bus only ever calls the remove callback with a valid pointer
+        // to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `remove_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
+
+        // SAFETY: `remove_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>>() };
+

rust/kernel/serdev.rs line 244

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `remove_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()) };
+
+        T::unbind(sdev, data_pinned);
+    }

[Severity: High]
Should serdev_device_close() be called synchronously in remove_callback() rather than waiting for PrivateData::drop?

By not closing the device synchronously here, the device remains active and the receive layer can asynchronously trigger receive_buf_callback() on a workqueue. In the unbind path, the device core subsequently invokes post_unbind_rust(), which clears the device's drvdata pointer.

If receive_buf_callback() executes right after drvdata is cleared, it blindly dereferences a null pointer via drvdata_borrow().

[ ... ]

rust/kernel/serdev.rs line 380

Quoted 11 lines
rust/kernel/serdev.rs new file +11 -0
+pub trait Driver {
+    /// The type holding driver private data about each device id supported by the driver.
+    // TODO: Use associated_type_defaults once stabilized:
+    //
+    // ```
+    // type IdInfo: 'static = ();
+    // ```
+    type IdInfo: 'static;
+
+    /// The type of the driver's bus device private data.
+    type Data<'bound>: Send + 'bound;

[Severity: High]
Is serdev::Driver::Data missing a Sync trait bound?

The serdev framework invokes receive_buf_callback() from the receive workqueue and remove_callback() from the driver core unbind context. Both callbacks synthesize a shared reference Pin<&T::Data> from the raw driver pointer without any mutual exclusion.

Because T::Data does not require Sync, safe Rust code could use non-thread-safe types (e.g., core::cell::Cell) in the driver state, leading to data races and undefined behavior.

[ ... ]

Quoted 7 lines
rust/kernel/serdev.rs new file +7 -0
+    pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
+        // SAFETY:
+        // - `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
+        // - `data.as_ptr()` is guaranteed to be a valid array pointer with the size of
+        //   `data.len()`.
+        let ret = unsafe {
+            bindings::serdev_device_write(

rust/kernel/serdev.rs line 505

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+                self.as_raw(),
+                data.as_ptr(),
+                data.len(),
+                timeout.into_jiffies(),
+            )
+        };
+        // CAST: negative return values are guaranteed to be between `-MAX_ERRNO` and `-1`,
+        // which always fit into a `i32`.
+        to_result(ret as i32).map(|()| ret.unsigned_abs())
+    }

[Severity: Medium]
Does casting the ssize_t return value of serdev_device_write() to i32 incorrectly treat large successful writes as errors?

If a caller passes a slice larger than 2GB (e.g., on a 64-bit architecture) and the write succeeds, the positive isize return value will overflow during the 'as i32' cast, resulting in a negative number. to_result() will then erroneously interpret this successful return as a kernel error code.

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

Re: [PATCH v13 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 5 potential issue(s) to consider: - [High] The `receive` callback issues an unbounded blocking write (`serdev::Timeout::Max`), which can…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] The receive callback issues an unbounded blocking write (serdev::Timeout::Max), which can stall the TTY receive worker indefinitely and cause kernel hangs during module unload.
- [High] The serdev abstraction's remove_callback fails to drop the driver's private data, leaking memory and leaving the device open, which leads to a null-pointer dereference in the receive workqueue.
- [Medium] The driver attempts to read a non-standard "baudrate" property instead of the standard "current-speed" property.
- [Medium] The driver's probe function will fail on many valid hardware platforms because it rejects inexact baud rates.
- [Low] The commit message falsely claims the driver supports device/driver name matching and omits mention of ACPI support.
--

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

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

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

Quoted 2 lines

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

[Severity: Low]
This isn't a bug, but the commit message inaccurately describes the bus matching behavior.

serdev_device_match() exclusively checks ACPI and OF ID tables and does not fall back to device/driver name matching. The implemented ACPI matching is also omitted from the description.

Could the commit message be updated to accurately reflect the supported matching mechanisms?

Quoted 5 lines
samples/rust/rust_driver_serdev.rs new file +0 -0
new file mode 100644
index 0000000000000..824affbf65936

[ ... ]

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]
Will this fail to read the configured speed from standard device trees?

The driver attempts to read a non-standard "baudrate" property instead of the standard "current-speed" property. This causes a silent fallback to the 115200 default.

Should this use the standard "current-speed" property instead?

samples/rust/rust_driver_serdev.rs line 56

Quoted 3 lines
samples/rust/rust_driver_serdev.rs new file +3 -0
+                    .unwrap_or(115200),
+            )
+            .is_err()

[Severity: Medium]
Does strictly rejecting any Err with EINVAL cause the driver to fail probe when an inexact baud rate is achieved?

The bindings::serdev_device_set_baudrate() function returns the actual configured speed. The Rust set_baudrate() abstraction returns Err(actual_speed) if the hardware cannot exactly match the requested speed due to clock dividers.

Quoted 5 lines
samples/rust/rust_driver_serdev.rs new file +5 -0
+        {
+            return Err(EINVAL);
+        }
+        sdev.set_flow_control(false);
+        sdev.set_parity(serdev::Parity::None)?;

samples/rust/rust_driver_serdev.rs line 71

Quoted 10 lines
samples/rust/rust_driver_serdev.rs new file +10 -0
+
+        Ok(Self { sdev: sdev.into() })
+    }
+
+    fn receive<'bound>(
+        sdev: &'bound serdev::Device<Bound>,
+        _this: Pin<&Self>,
+        data: &[u8],
+    ) -> usize {
+        let _ = sdev.write_all(data, serdev::Timeout::Max);

[Severity: High]
Can this unbounded blocking write stall the TTY receive worker indefinitely?

The receive() callback executes in the TTY RX workqueue. serdev::Timeout::Max maps to a 0 timeout in serdev_device_write(), which waits indefinitely. If the hardware TX buffer fills up due to a slow remote device or flow control, the worker thread will block forever.

This deadlock of the TTY RX worker leads to an unkillable task and system hang when cancel_work_sync() is called during module unload.

samples/rust/rust_driver_serdev.rs line 74

Quoted 3 lines
samples/rust/rust_driver_serdev.rs new file +3 -0
+        data.len()
+    }
+}

Additionally, I noticed an issue in the underlying serdev abstraction code in rust/kernel/serdev.rs:

[Severity: High]
Does Adapter::remove_callback() in rust/kernel/serdev.rs fail to drop the driver's private data during unbind?

During device unbind, remove_callback() uses drvdata_borrow() instead of drvdata_obtain(). This fails to take ownership of the KBox<PrivateData>, leaking the memory.

Because PrivateData::drop never runs, bindings::serdev_device_close() is never called. The C driver core then resets dev->driver_data to NULL. Because the device is still open, incoming serial data triggers receive_buf_callback(), which calls drvdata_borrow() on the now-NULL drvdata pointer, causing a panic when locking the mutex.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#3 lore raw
In reply to [email protected]
Quoted 48 lines · On Sun, 2026-07-12 at 17:15 +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] serdev::Driver::Data is missing a Sync trait bound, allowing safe code to trigger Undefined Behavior via data races.
- [High] The framework defers serdev_device_close() to PrivateData::drop and fails to close the device synchronously in remove_callback, creating a race window that leads to NULL pointer dereferences, Use-After-Free, and deadlocks.
- [High] Holding the active mutex across T::probe introduces a cyclic AB-BA deadlock if a driver synchronously awaits receive data during initialization.
- [Medium] write_all improperly casts the ssize_t return value of serdev_device_write to i32, which causes successful writes larger than 2GB to be incorrectly treated as negative error codes. --

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

rust: add basic serial device bus abstractions

This commit introduces the Rust abstractions for the serial device bus API. It adds the serdev::Driver trait, the serdev::Device abstraction representing a struct serdev_device, and adapter mechanisms to register drivers with the generic driver core.

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

[ ... ]

Quoted 10 lines
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()) };
+        }
+    }
+}

[Severity: High]
Does deferring serdev_device_close() to drop() introduce an AB-BA deadlock?

Quoted 5 lines

If receive_buf_callback() executes on the receive workqueue while PrivateData is being dropped, the receive thread will block waiting for the 'active' mutex. Meanwhile, this drop() method holds the 'active' mutex and calls serdev_device_close(), which synchronously flushes the workqueue. This seems like it would cause the two threads to deadlock.

That is an issue.

Quoted 22 lines

[ ... ]

Quoted 1 line

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

[ ... ]

rust/kernel/serdev.rs line 203

Quoted 13 lines
rust/kernel/serdev.rs new file +13 -0
+            let mut active = private_data.active.lock();
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            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]
Can holding the 'active' mutex across T::probe() cause a cyclic deadlock during device initialization?

Quoted 6 lines

If a driver sends a hardware identification command in its probe() routine and synchronously waits for the response, the incoming data will trigger receive_buf_callback() on a separate thread. Because receive_buf_callback() unconditionally attempts to acquire the 'active' mutex, it will block forever while probe_callback() holds the mutex and waits for the receive data.

False positive, kinda.

It is not possbile yet, to retrieve initial device data.

Quoted 29 lines

[ ... ]

Quoted 12 lines
rust/kernel/serdev.rs new file +12 -0
+    extern "C" fn remove_callback(sdev: *mut bindings::serdev_device) {
+        // SAFETY: The serial device bus only ever calls the remove callback with a valid pointer
+        // to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `remove_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
+
+        // SAFETY: `remove_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>>() };
+

rust/kernel/serdev.rs line 244

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `remove_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()) };
+
+        T::unbind(sdev, data_pinned);
+    }

[Severity: High]
Should serdev_device_close() be called synchronously in remove_callback() rather than waiting for PrivateData::drop?

Quoted 7 lines

By not closing the device synchronously here, the device remains active and the receive layer can asynchronously trigger receive_buf_callback() on a workqueue. In the unbind path, the device core subsequently invokes post_unbind_rust(), which clears the device's drvdata pointer.

If receive_buf_callback() executes right after drvdata is cleared, it blindly dereferences a null pointer via drvdata_borrow().

False positive.

impl Drop for PrivateData locks the active mutex and sets its value to false.
receive_buf_callback trys to acquire this mutex and if the value is false, it never accesses the driver data. serdev_device_close gets called before private data gets deallocated.

Quoted 17 lines

[ ... ]

rust/kernel/serdev.rs line 380

Quoted 11 lines
rust/kernel/serdev.rs new file +11 -0
+pub trait Driver {
+    /// The type holding driver private data about each device id supported by the driver.
+    // TODO: Use associated_type_defaults once stabilized:
+    //
+    // ```
+    // type IdInfo: 'static = ();
+    // ```
+    type IdInfo: 'static;
+
+    /// The type of the driver's bus device private data.
+    type Data<'bound>: Send + 'bound;

[Severity: High]
Is serdev::Driver::Data missing a Sync trait bound?

Quoted 8 lines

The serdev framework invokes receive_buf_callback() from the receive workqueue and remove_callback() from the driver core unbind context. Both callbacks synthesize a shared reference Pin<&T::Data> from the raw driver pointer without any mutual exclusion.

Because T::Data does not require Sync, safe Rust code could use non-thread-safe types (e.g., core::cell::Cell) in the driver state, leading to data races and undefined behavior.

I suppose thats an issue too.

Quoted 20 lines

[ ... ]

Quoted 7 lines
rust/kernel/serdev.rs new file +7 -0
+    pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
+        // SAFETY:
+        // - `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
+        // - `data.as_ptr()` is guaranteed to be a valid array pointer with the size of
+        //   `data.len()`.
+        let ret = unsafe {
+            bindings::serdev_device_write(

rust/kernel/serdev.rs line 505

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+                self.as_raw(),
+                data.as_ptr(),
+                data.len(),
+                timeout.into_jiffies(),
+            )
+        };
+        // CAST: negative return values are guaranteed to be between `-MAX_ERRNO` and `-1`,
+        // which always fit into a `i32`.
+        to_result(ret as i32).map(|()| ret.unsigned_abs())
+    }
Quoted 3 lines

[Severity: Medium]
Does casting the ssize_t return value of serdev_device_write() to i32 incorrectly treat large successful writes as errors?

Yes, but thats more an issue with the input not being checked than the return type.

Quoted 6 lines

If a caller passes a slice larger than 2GB (e.g., on a 64-bit architecture) and the write succeeds, the positive isize return value will overflow during the 'as i32' cast, resulting in a negative number. to_result() will then erroneously interpret this successful return as a kernel error code.

author maintainer
#6 lore raw

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

In reply to [email protected]
Quoted 24 lines · On Sun, 2026-07-12 at 17:19 +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] The receive callback issues an unbounded blocking write (serdev::Timeout::Max), which can stall the TTY receive worker indefinitely and cause kernel hangs during module unload.
- [High] The serdev abstraction's remove_callback fails to drop the driver's private data, leaking memory and leaving the device open, which leads to a null-pointer dereference in the receive workqueue.
- [Medium] The driver attempts to read a non-standard "baudrate" property instead of the standard "current-speed" property.
- [Medium] The driver's probe function will fail on many valid hardware platforms because it rejects inexact baud rates.
- [Low] The commit message falsely claims the driver supports device/driver name matching and omits mention of ACPI support.
--

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

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

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

Quoted 2 lines

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

[Severity: Low]
This isn't a bug, but the commit message inaccurately describes the bus matching behavior.

Quoted 6 lines

serdev_device_match() exclusively checks ACPI and OF ID tables and does not fall back to device/driver name matching. The implemented ACPI matching is also omitted from the description.

Could the commit message be updated to accurately reflect the supported matching mechanisms?

There is a todo comment in serdev_device_match, so I will leave it for now.

Quoted 23 lines
Quoted 6 lines
samples/rust/rust_driver_serdev.rs new file +0 -0
new file mode 100644
index 0000000000000..824affbf65936

[ ... ]

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]
Will this fail to read the configured speed from standard device trees?

Quoted 5 lines

The driver attempts to read a non-standard "baudrate" property instead of the standard "current-speed" property. This causes a silent fallback to the 115200 default.

Should this use the standard "current-speed" property instead?

Just an example.

Quoted 5 lines

samples/rust/rust_driver_serdev.rs line 56

Quoted 4 lines
samples/rust/rust_driver_serdev.rs new file +3 -0
+                    .unwrap_or(115200),
+            )
+            .is_err()
Quoted 7 lines

[Severity: Medium]
Does strictly rejecting any Err with EINVAL cause the driver to fail probe when an inexact baud rate is achieved?

The bindings::serdev_device_set_baudrate() function returns the actual configured speed. The Rust set_baudrate() abstraction returns Err(actual_speed) if the hardware cannot exactly match the requested speed due to clock dividers.

Just an example.

Quoted 20 lines
Quoted 6 lines
samples/rust/rust_driver_serdev.rs new file +5 -0
+        {
+            return Err(EINVAL);
+        }
+        sdev.set_flow_control(false);
+        sdev.set_parity(serdev::Parity::None)?;

samples/rust/rust_driver_serdev.rs line 71

Quoted 10 lines
samples/rust/rust_driver_serdev.rs new file +10 -0
+
+        Ok(Self { sdev: sdev.into() })
+    }
+
+    fn receive<'bound>(
+        sdev: &'bound serdev::Device<Bound>,
+        _this: Pin<&Self>,
+        data: &[u8],
+    ) -> usize {
+        let _ = sdev.write_all(data, serdev::Timeout::Max);

[Severity: High]
Can this unbounded blocking write stall the TTY receive worker indefinitely?

Quoted 7 lines

The receive() callback executes in the TTY RX workqueue. serdev::Timeout::Max maps to a 0 timeout in serdev_device_write(), which waits indefinitely. If the hardware TX buffer fills up due to a slow remote device or flow control, the worker thread will block forever.

This deadlock of the TTY RX worker leads to an unkillable task and system hang when cancel_work_sync() is called during module unload.

Might or might not be an issue, I have to look into this. But its still an example.

Quoted 8 lines

samples/rust/rust_driver_serdev.rs line 74

Quoted 4 lines
samples/rust/rust_driver_serdev.rs new file +3 -0
+        data.len()
+    }
+}

Additionally, I noticed an issue in the underlying serdev abstraction code in rust/kernel/serdev.rs:

Quoted 7 lines

[Severity: High]
Does Adapter::remove_callback() in rust/kernel/serdev.rs fail to drop the driver's private data during unbind?

During device unbind, remove_callback() uses drvdata_borrow() instead of drvdata_obtain(). This fails to take ownership of the KBox<PrivateData>, leaking the memory.

driver.rs should take care of dropping PrivateData, which will also drop the underlying driver data.

Quoted 6 lines

Because PrivateData::drop never runs, bindings::serdev_device_close() is never called. The C driver core then resets dev->driver_data to NULL. Because the device is still open, incoming serial data triggers receive_buf_callback(), which calls drvdata_borrow() on the now-NULL drvdata pointer, causing a panic when locking the mutex.

See above.