Skip to contentSkip to conversation

rust: add basic serial device bus abstractions

PATCH Superseded Markus Probst 2 participants 24 messages May 30

Subsystems (7)

v8 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

v8 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 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 (5):
rust: devres: return reference in devres::register
serdev: add rust private data to serdev_device
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 +
 include/linux/serdev.h             |  15 +-
 rust/bindings/bindings_helper.h    |   1 +
 rust/helpers/helpers.c             |   1 +
 rust/helpers/serdev.c              |  22 ++
 rust/kernel/cpufreq.rs             |   3 +-
 rust/kernel/devres.rs              |  15 +-
 rust/kernel/drm/driver.rs          |   3 +-
 rust/kernel/lib.rs                 |   2 +
 rust/kernel/serdev.rs              | 548 +++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig               |  11 +
 samples/rust/Makefile              |   1 +
 samples/rust/rust_driver_serdev.rs |  91 ++++++
 14 files changed, 714 insertions(+), 11 deletions(-)

---
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

author maintainer
#1 lore raw

PATCH v8 1/5 rust: devres: return reference in `devres::register`

Return the reference to the initialized data in the devres::register function.

This is needed in a following commit (rust: add basic serial device bus abstractions).

---
 rust/kernel/cpufreq.rs    |  3 ++-
 rust/kernel/devres.rs     | 15 +++++++++++++--
 rust/kernel/drm/driver.rs |  3 ++-
 3 files changed, 17 insertions(+), 4 deletions(-)
rust/kernel/cpufreq.rs +2 -1
index d94c6cdbc45a..bbbd4f54218a 100644
@@ -1053,7 +1053,8 @@ pub fn new_foreign_owned(dev: &Device<Bound>) -> Result
     where
         T: 'static,
     {
-        devres::register(dev, Self::new()?, GFP_KERNEL)
+        devres::register(dev, Self::new()?, GFP_KERNEL)?;
+        Ok(())
     }
 }
 
rust/kernel/devres.rs +13 -2
index 82cbd8b969fb..e3e954478caa 100644
@@ -419,15 +419,26 @@ fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
 /// }
 ///
 /// fn from_bound_context(dev: &Device<Bound>) -> Result {
-///     devres::register(dev, Registration::new(), GFP_KERNEL)
+///     devres::register(dev, Registration::new(), GFP_KERNEL)?;
+///     Ok(())
 /// }
 /// ```
-pub fn register<T, E>(dev: &Device<Bound>, data: impl PinInit<T, E>, flags: Flags) -> Result
+pub fn register<'a, T, E>(
+    dev: &'a Device<Bound>,
+    data: impl PinInit<T, E>,
+    flags: Flags,
+) -> Result<&'a T>
 where
     T: Send + 'static,
     Error: From<E>,
 {
     let data = KBox::pin_init(data, flags)?;
 
+    let data_ptr = &raw const *data;
+
     register_foreign(dev, data)
+        // SAFETY: `dev` is valid for the lifetime of 'a. As long as there is a reference to
+        // `Device<Bound>`, it is guaranteed that the device is not unbound and data has not been
+        // dropped. Thus `data_ptr` is also valid for the lifetime of 'a.
+        .map(|()| unsafe { &*data_ptr })
 }
rust/kernel/drm/driver.rs +2 -1
index 5233bdebc9fc..1edfd7bacddb 100644
@@ -147,7 +147,8 @@ pub fn new_foreign_owned(
 
         let reg = Registration::<T>::new(drm, flags)?;
 
-        devres::register(dev, reg, GFP_KERNEL)
+        devres::register(dev, reg, GFP_KERNEL)?;
+        Ok(())
     }
 
     /// Returns a reference to the `Device` instance for this registration.
Signature · 1 line
2.53.0
author maintainer
#4 lore raw

PATCH v8 2/5 serdev: add rust private data to serdev_device

In reply to Markus Probst

Add rust private data to struct serdev_device, as it is required by the rust abstraction added in the following commit
(rust: add basic serial device bus abstractions).

---
 include/linux/serdev.h | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
include/linux/serdev.h +9 -6
index b6c3d957ec15..048ef5857786 100644
@@ -33,12 +33,14 @@ struct serdev_device_ops {
 
 /**
  * struct serdev_device - Basic representation of an serdev device
- * @dev:	Driver model representation of the device.
- * @nr:		Device number on serdev bus.
- * @ctrl:	serdev controller managing this device.
- * @ops:	Device operations.
- * @write_comp:	Completion used by serdev_device_write() internally
- * @write_lock:	Lock to serialize access when writing data
+ * @dev:		Driver model representation of the device.
+ * @nr:			Device number on serdev bus.
+ * @ctrl:		serdev controller managing this device.
+ * @ops:		Device operations.
+ * @write_comp:		Completion used by serdev_device_write() internally
+ * @write_lock:		Lock to serialize access when writing data
+ * @rust_private_data:	Private data for the rust abstraction. This should
+ *			not be used by the C drivers.
  */
 struct serdev_device {
 	struct device dev;
@@ -47,6 +49,7 @@ struct serdev_device {
 	const struct serdev_device_ops *ops;
 	struct completion write_comp;
 	struct mutex write_lock;
+	void *rust_private_data;
 };
 
 #define to_serdev_device(d) container_of_const(d, struct serdev_device, dev)
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

PATCH v8 3/5 rust: add basic serial device bus abstractions

In reply to Markus Probst

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           | 548 ++++++++++++++++++++++++++++++++++++++++
 7 files changed, 583 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 +548 -0

548 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#22 lore raw

PATCH v8 4/5 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
#23 lore raw

PATCH v8 5/5 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
maintainer Acked-by on v8 1/5
#2 lore raw

Re: [PATCH v8 1/5] rust: devres: return reference in `devres::register`

In reply to Markus Probst
Quoted 10 lines · On Sat May 30, 2026 at 3:13 AM CEST, Markus Probst via B4 Relay wrote:

From: Markus Probst <[email protected]>

Return the reference to the initialized data in the devres::register function.

This is needed in a following commit (rust: add basic serial device bus abstractions).

For driver-core and DRM,

This is useful in the context of the HRT work in general, should this series not make it this cycle, please let me know, then I'm going to pick this through the driver-core tree.

maintainer Reviewed-by on v8 3/5
#6 lore raw
In reply to Markus Probst
Quoted 22 lines · On Sat May 30, 2026 at 3:13 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +22 -0
+    extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi::c_int {
+        // SAFETY: The serial device bus only ever calls the probe callback with a valid pointer to
+        // a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `probe_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
+        let info = <Self as driver::Adapter>::id_info(sdev.as_ref());
+
+        from_result(|| {
+            let private_data = devres::register(
+                sdev.as_ref(),
+                try_pin_init!(PrivateData {
+                    probe_complete <- Completion::new(),
+                    error: false.into(),
+                }),
+                GFP_KERNEL,
+            )?;
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            unsafe {
+                (*sdev.as_raw()).rust_private_data =
+                    (&raw const *private_data).cast::<c_void>().cast_mut()

rust/kernel/serdev.rs line 173

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+            };
+
+            // 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::devm_serdev_device_open(sdev.as_ref().as_raw(), sdev.as_raw())
+            })?;

The bus device private data drops before devres callbacks run, thus you can't use the devm helper here. I suggest to use serdev_device_open() and call serdev_device_close() from remove_callback() instead.

You may also want to consider whether you potentially want T::unbind() to allow to have concurrent transmits in flight regardless. IOW, you may want to call serdev_device_close() before T::unbind() anyway.

Quoted 28 lines
rust/kernel/serdev.rs new file +28 -0
+
+            let data = T::probe(sdev, info);
+            let result = sdev.as_ref().set_drvdata(data);
+
+            // SAFETY: We have exclusive access to `private_data.error`.
+            unsafe { *private_data.error.get() = result.is_err() };
+
+            private_data.probe_complete.complete_all();
+
+            result.map(|()| 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<T::Data<'_>>>`.
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        T::unbind(sdev, data);
+    }
+

rust/kernel/serdev.rs line 211

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 dereferences to Core, which is technically unsound within this callback.

I think you want CoreInternal for drvdata_borrow(), so we should add a BoundInternal type state for this; I will send a patch for this.

With this and the above fixed,

from the driver-core side of things.

Quoted 26 lines
rust/kernel/serdev.rs new file +26 -0
+        // SAFETY:
+        // - The serial device bus only ever calls the receive buf callback with a valid pointer to
+        //   a `struct serdev_device`.
+        // - `receive_buf_callback` is only ever called after a successful call to
+        //   `probe_callback`, hence it's guaranteed that `sdev.private_data` is a pointer
+        //   to a valid `PrivateData`.
+        let private_data = unsafe { &*(*sdev.as_raw()).rust_private_data.cast::<PrivateData>() };
+
+        private_data.probe_complete.wait_for_completion();
+
+        // SAFETY: No one has exclusive access to `private_data.error`.
+        if unsafe { *private_data.error.get() } {
+            return length;
+        }
+
+        // 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<T::Data<'_>>>`.
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        // 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, buf)
+    }
+}
author maintainer
#7 lore raw
Quoted 38 lines · Danilo Krummrich
Quoted 22 lines · On Sat May 30, 2026 at 3:13 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +22 -0
+    extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi::c_int {
+        // SAFETY: The serial device bus only ever calls the probe callback with a valid pointer to
+        // a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `probe_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
+        let info = <Self as driver::Adapter>::id_info(sdev.as_ref());
+
+        from_result(|| {
+            let private_data = devres::register(
+                sdev.as_ref(),
+                try_pin_init!(PrivateData {
+                    probe_complete <- Completion::new(),
+                    error: false.into(),
+                }),
+                GFP_KERNEL,
+            )?;
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            unsafe {
+                (*sdev.as_raw()).rust_private_data =
+                    (&raw const *private_data).cast::<c_void>().cast_mut()

rust/kernel/serdev.rs line 173

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+            };
+
+            // 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::devm_serdev_device_open(sdev.as_ref().as_raw(), sdev.as_raw())
+            })?;

The bus device private data drops before devres callbacks run, thus you can't use the devm helper here. I suggest to use serdev_device_open() and call serdev_device_close() from remove_callback() instead.

Quoted 3 lines

You may also want to consider whether you potentially want T::unbind() to allow to have concurrent transmits in flight regardless. IOW, you may want to call serdev_device_close() before T::unbind() anyway.

serdev::Device<Core> will be passed as argument to unbind, i.e. set_baudrate, set_flow_control etc. calls are possible. If we close the serdev device before unbind, calling those would result in a null pointer dereference. Maybe a driver even wants to send a message here, so it should stay open.

If I think about it, I can't even close it inside remove_callback after T::unbind. With the driver lifetimes, the driver could store the serdev::Device<Bound> pointer in its DriverData and could still make calls to the device.

Any suggestions?

Quoted 70 lines
Quoted 29 lines
rust/kernel/serdev.rs new file +28 -0
+
+            let data = T::probe(sdev, info);
+            let result = sdev.as_ref().set_drvdata(data);
+
+            // SAFETY: We have exclusive access to `private_data.error`.
+            unsafe { *private_data.error.get() = result.is_err() };
+
+            private_data.probe_complete.complete_all();
+
+            result.map(|()| 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<T::Data<'_>>>`.
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        T::unbind(sdev, data);
+    }
+

rust/kernel/serdev.rs line 211

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 dereferences to Core, which is technically unsound within this callback.

I think you want CoreInternal for drvdata_borrow(), so we should add a BoundInternal type state for this; I will send a patch for this.

With this and the above fixed,

from the driver-core side of things.

Quoted 18 lines
rust/kernel/serdev.rs new file +18 -0
+        // SAFETY:
+        // - The serial device bus only ever calls the receive buf callback with a valid pointer to
+        //   a `struct serdev_device`.
+        // - `receive_buf_callback` is only ever called after a successful call to
+        //   `probe_callback`, hence it's guaranteed that `sdev.private_data` is a pointer
+        //   to a valid `PrivateData`.
+        let private_data = unsafe { &*(*sdev.as_raw()).rust_private_data.cast::<PrivateData>() };
+
+        private_data.probe_complete.wait_for_completion();
+
+        // SAFETY: No one has exclusive access to `private_data.error`.
+        if unsafe { *private_data.error.get() } {
+            return length;
+        }
+
+        // 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<T::Data<'_>>>`.
Quoted 8 lines

rust/kernel/serdev.rs line 238

Quoted 8 lines
rust/kernel/serdev.rs new file +8 -0
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        // 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, buf)
+    }
+}

Thanks
- Markus Probst

author maintainer
#8 lore raw
Quoted 48 lines · Markus Probst
Quoted 38 lines · Danilo Krummrich
Quoted 22 lines · On Sat May 30, 2026 at 3:13 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +22 -0
+    extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi::c_int {
+        // SAFETY: The serial device bus only ever calls the probe callback with a valid pointer to
+        // a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `probe_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
+        let info = <Self as driver::Adapter>::id_info(sdev.as_ref());
+
+        from_result(|| {
+            let private_data = devres::register(
+                sdev.as_ref(),
+                try_pin_init!(PrivateData {
+                    probe_complete <- Completion::new(),
+                    error: false.into(),
+                }),
+                GFP_KERNEL,
+            )?;
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            unsafe {
+                (*sdev.as_raw()).rust_private_data =
+                    (&raw const *private_data).cast::<c_void>().cast_mut()

rust/kernel/serdev.rs line 173

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+            };
+
+            // 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::devm_serdev_device_open(sdev.as_ref().as_raw(), sdev.as_raw())
+            })?;

The bus device private data drops before devres callbacks run, thus you can't use the devm helper here. I suggest to use serdev_device_open() and call serdev_device_close() from remove_callback() instead.

Quoted 3 lines

You may also want to consider whether you potentially want T::unbind() to allow to have concurrent transmits in flight regardless. IOW, you may want to call serdev_device_close() before T::unbind() anyway.

serdev::Device<Core> will be passed as argument to unbind, i.e. set_baudrate, set_flow_control etc. calls are possible. If we close the serdev device before unbind, calling those would result in a null pointer dereference. Maybe a driver even wants to send a message here, so it should stay open.

Quoted 6 lines

If I think about it, I can't even close it inside remove_callback after T::unbind. With the driver lifetimes, the driver could store the serdev::Device<Bound> pointer in its DriverData and could still make calls to the device.

Any suggestions?

I could keep calling devm, but close it before unbind and reopen it without the receive ops. The devm will close it then again.

This way it stays open until the last devres callback has run, but doesn't call the receive_buf_callback while the drvdata has been dropped.

I will test it and see if it works.

Thanks
- Markus Probst

Quoted 82 lines
Quoted 71 lines
Quoted 30 lines
rust/kernel/serdev.rs new file +28 -0
+
+            let data = T::probe(sdev, info);
+            let result = sdev.as_ref().set_drvdata(data);
+
+            // SAFETY: We have exclusive access to `private_data.error`.
+            unsafe { *private_data.error.get() = result.is_err() };
+
+            private_data.probe_complete.complete_all();
+
+            result.map(|()| 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<T::Data<'_>>>`.
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        T::unbind(sdev, data);
+    }
+

rust/kernel/serdev.rs line 211

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 dereferences to Core, which is technically unsound within this callback.

I think you want CoreInternal for drvdata_borrow(), so we should add a BoundInternal type state for this; I will send a patch for this.

With this and the above fixed,

from the driver-core side of things.

Quoted 18 lines
rust/kernel/serdev.rs new file +18 -0
+        // SAFETY:
+        // - The serial device bus only ever calls the receive buf callback with a valid pointer to
+        //   a `struct serdev_device`.
+        // - `receive_buf_callback` is only ever called after a successful call to
+        //   `probe_callback`, hence it's guaranteed that `sdev.private_data` is a pointer
+        //   to a valid `PrivateData`.
+        let private_data = unsafe { &*(*sdev.as_raw()).rust_private_data.cast::<PrivateData>() };
+
+        private_data.probe_complete.wait_for_completion();
+
+        // SAFETY: No one has exclusive access to `private_data.error`.
+        if unsafe { *private_data.error.get() } {
+            return length;
+        }
+
+        // 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<T::Data<'_>>>`.
Quoted 8 lines

rust/kernel/serdev.rs line 238

Quoted 8 lines
rust/kernel/serdev.rs new file +8 -0
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        // 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, buf)
+    }
+}

Thanks
- Markus Probst

author maintainer
#9 lore raw
Quoted 55 lines · Markus Probst
Quoted 48 lines · Markus Probst
Quoted 38 lines · Danilo Krummrich
Quoted 22 lines · On Sat May 30, 2026 at 3:13 AM CEST, Markus Probst via B4 Relay wrote:
rust/kernel/serdev.rs new file +22 -0
+    extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi::c_int {
+        // SAFETY: The serial device bus only ever calls the probe callback with a valid pointer to
+        // a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `probe_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
+        let info = <Self as driver::Adapter>::id_info(sdev.as_ref());
+
+        from_result(|| {
+            let private_data = devres::register(
+                sdev.as_ref(),
+                try_pin_init!(PrivateData {
+                    probe_complete <- Completion::new(),
+                    error: false.into(),
+                }),
+                GFP_KERNEL,
+            )?;
+
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            unsafe {
+                (*sdev.as_raw()).rust_private_data =
+                    (&raw const *private_data).cast::<c_void>().cast_mut()

rust/kernel/serdev.rs line 173

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+            };
+
+            // 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::devm_serdev_device_open(sdev.as_ref().as_raw(), sdev.as_raw())
+            })?;

The bus device private data drops before devres callbacks run, thus you can't use the devm helper here. I suggest to use serdev_device_open() and call serdev_device_close() from remove_callback() instead.

Quoted 3 lines

You may also want to consider whether you potentially want T::unbind() to allow to have concurrent transmits in flight regardless. IOW, you may want to call serdev_device_close() before T::unbind() anyway.

serdev::Device<Core> will be passed as argument to unbind, i.e. set_baudrate, set_flow_control etc. calls are possible. If we close the serdev device before unbind, calling those would result in a null pointer dereference. Maybe a driver even wants to send a message here, so it should stay open.

Quoted 6 lines

If I think about it, I can't even close it inside remove_callback after T::unbind. With the driver lifetimes, the driver could store the serdev::Device<Bound> pointer in its DriverData and could still make calls to the device.

Any suggestions?

Quoted 8 lines

I could keep calling devm, but close it before unbind and reopen it without the receive ops. The devm will close it then again.

This way it stays open until the last devres callback has run, but doesn't call the receive_buf_callback while the drvdata has been dropped.

I will test it and see if it works.

Ok, forget it. Only works safely in theory. serdev_device_open could fail and that would be unsound again.

Thanks
- Markus Probst

Quoted 86 lines

Thanks
- Markus Probst

Quoted 82 lines
Quoted 71 lines
Quoted 30 lines
rust/kernel/serdev.rs new file +28 -0
+
+            let data = T::probe(sdev, info);
+            let result = sdev.as_ref().set_drvdata(data);
+
+            // SAFETY: We have exclusive access to `private_data.error`.
+            unsafe { *private_data.error.get() = result.is_err() };
+
+            private_data.probe_complete.complete_all();
+
+            result.map(|()| 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<T::Data<'_>>>`.
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        T::unbind(sdev, data);
+    }
+

rust/kernel/serdev.rs line 211

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 dereferences to Core, which is technically unsound within this callback.

I think you want CoreInternal for drvdata_borrow(), so we should add a BoundInternal type state for this; I will send a patch for this.

With this and the above fixed,

from the driver-core side of things.

Quoted 18 lines
rust/kernel/serdev.rs new file +18 -0
+        // SAFETY:
+        // - The serial device bus only ever calls the receive buf callback with a valid pointer to
+        //   a `struct serdev_device`.
+        // - `receive_buf_callback` is only ever called after a successful call to
+        //   `probe_callback`, hence it's guaranteed that `sdev.private_data` is a pointer
+        //   to a valid `PrivateData`.
+        let private_data = unsafe { &*(*sdev.as_raw()).rust_private_data.cast::<PrivateData>() };
+
+        private_data.probe_complete.wait_for_completion();
+
+        // SAFETY: No one has exclusive access to `private_data.error`.
+        if unsafe { *private_data.error.get() } {
+            return length;
+        }
+
+        // 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<T::Data<'_>>>`.
Quoted 8 lines

rust/kernel/serdev.rs line 238

Quoted 8 lines
rust/kernel/serdev.rs new file +8 -0
+        let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
+
+        // 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, buf)
+    }
+}

Thanks
- Markus Probst

maintainer
#10 lore raw
Quoted 8 lines · Markus Probst
Quoted 7 lines · Markus Probst
Quoted 6 lines · Markus Probst

If I think about it, I can't even close it inside remove_callback after T::unbind. With the driver lifetimes, the driver could store the serdev::Device<Bound> pointer in its DriverData and could still make calls to the device.

Any suggestions?

Now that there is no public drvdata() accessor anymore, all bus device private data accesses go through the bus abstraction.

So, you could go back to your original approach and wrap the state in a bus specific bus device private data wrapper type, which would also get you rid of the rust_private_data pointer you add to struct serdev_device.

author maintainer
#11 lore raw
Quoted 8 lines · Danilo Krummrich
Quoted 7 lines · Markus Probst
Quoted 6 lines · Markus Probst
Quoted 5 lines · Markus Probst

If I think about it, I can't even close it inside remove_callback after T::unbind. With the driver lifetimes, the driver could store the serdev::Device<Bound> pointer in its DriverData and could still make calls to the device.

Quoted 8 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line

Any suggestions?

Now that there is no public drvdata() accessor anymore, all bus device private data accesses go through the bus abstraction.

So, you could go back to your original approach and wrap the state in a bus specific bus device private data wrapper type, which would also get you rid of the rust_private_data pointer you add to struct serdev_device.

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will automatically be dropped after the remove_callback, but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Thanks
- Markus Probst

maintainer
#12 lore raw
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

author maintainer
#13 lore raw
Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

Because the possibility exists that some classdev ops or Drop calls e.g. sdev.set_baudrate. This is a null pointer dereference after serdev_device_close has been called. I interpreted it to add a state to the abstraction private data which would prevent those calls (early return with error) after serdev_device_close has been called, but this would only work if it outlives these calls.

But it seems you were refering to something else with the state?

Thanks
- Markus Probst

maintainer
#14 lore raw
Quoted 8 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

Quoted 8 lines

Because the possibility exists that some classdev ops or Drop calls e.g. sdev.set_baudrate. This is a null pointer dereference after serdev_device_close has been called. I interpreted it to add a state to the abstraction private data which would prevent those calls (early return with error) after serdev_device_close has been called, but this would only work if it outlives these calls.

But it seems you were refering to something else with the state?

Yes, but I just notice that I'm a step ahead. With the lifetime model class device registrations shouldn't be guarded with Devres anymore, but with a lifetime.

(This also entirely eliminates the need for having different devres stages to prevent drivers from smuggling a newly created Devres object into an existing Devres<Registration<T>>'s data, which would be unsound for obvious reasons.)

With this there is no way there are still class device callbacks after the bus device private data has been dropped in the first place.

author maintainer
#15 lore raw
Quoted 22 lines · Danilo Krummrich
Quoted 8 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

Quoted 8 lines

Because the possibility exists that some classdev ops or Drop calls e.g. sdev.set_baudrate. This is a null pointer dereference after serdev_device_close has been called. I interpreted it to add a state to the abstraction private data which would prevent those calls (early return with error) after serdev_device_close has been called, but this would only work if it outlives these calls.

But it seems you were refering to something else with the state?

Yes, but I just notice that I'm a step ahead. With the lifetime model class device registrations shouldn't be guarded with Devres anymore, but with a lifetime.

Quoted 6 lines

(This also entirely eliminates the need for having different devres stages to prevent drivers from smuggling a newly created Devres object into an existing Devres<Registration<T>>'s data, which would be unsound for obvious reasons.)

With this there is no way there are still class device callbacks after the bus device private data has been dropped in the first place.

There would still be Drop, which can access the device. Drop happens after remove_callback.

Might be simpler for now: I can use a mutex to prevent calls in receive_buf after remove_callback has been called.

Thanks
- Markus Probst

maintainer
#16 lore raw
Quoted 23 lines · Markus Probst
Quoted 22 lines · Danilo Krummrich
Quoted 8 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

Quoted 8 lines

Because the possibility exists that some classdev ops or Drop calls e.g. sdev.set_baudrate. This is a null pointer dereference after serdev_device_close has been called. I interpreted it to add a state to the abstraction private data which would prevent those calls (early return with error) after serdev_device_close has been called, but this would only work if it outlives these calls.

But it seems you were refering to something else with the state?

Yes, but I just notice that I'm a step ahead. With the lifetime model class device registrations shouldn't be guarded with Devres anymore, but with a lifetime.

Quoted 8 lines
Quoted 6 lines

(This also entirely eliminates the need for having different devres stages to prevent drivers from smuggling a newly created Devres object into an existing Devres<Registration<T>>'s data, which would be unsound for obvious reasons.)

With this there is no way there are still class device callbacks after the bus device private data has been dropped in the first place.

There would still be Drop, which can access the device. Drop happens after remove_callback.

But you control drop(), so can order it such that first the driver's bus device private data drops and after this the private data of the bus wrapping it (which will also call serdev_device_close()).

Quoted 5 lines

Might be simpler for now: I can use a mutex to prevent calls in receive_buf after remove_callback has been called.

Thanks
- Markus Probst

author maintainer
#17 lore raw
Quoted 28 lines · Danilo Krummrich
Quoted 27 lines · Markus Probst
Quoted 26 lines · Danilo Krummrich
Quoted 8 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

Quoted 8 lines

Because the possibility exists that some classdev ops or Drop calls e.g. sdev.set_baudrate. This is a null pointer dereference after serdev_device_close has been called. I interpreted it to add a state to the abstraction private data which would prevent those calls (early return with error) after serdev_device_close has been called, but this would only work if it outlives these calls.

But it seems you were refering to something else with the state?

Yes, but I just notice that I'm a step ahead. With the lifetime model class device registrations shouldn't be guarded with Devres anymore, but with a lifetime.

(This also entirely eliminates the need for having different devres stages to prevent drivers from smuggling a newly created Devres object into an existing Devres<Registration<T>>'s data, which would be unsound for obvious reasons.)

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

With this there is no way there are still class device callbacks after the bus device private data has been dropped in the first place.

There would still be Drop, which can access the device. Drop happens after remove_callback.

But you control drop(), so can order it such that first the driver's bus device private data drops and after this the private data of the bus wrapping it (which will also call serdev_device_close()).

Yes.

It seems I also have to rebase led then, as it currently uses Devres.

Thanks
- Markus Probst

Quoted 6 lines
Quoted 6 lines

Might be simpler for now: I can use a mutex to prevent calls in receive_buf after remove_callback has been called.

Thanks
- Markus Probst

author maintainer
#3 lore raw

Re: [PATCH v8 1/5] rust: devres: return reference in `devres::register`

In reply to Danilo Krummrich
Quoted 12 lines · Danilo Krummrich
Quoted 10 lines · On Sat May 30, 2026 at 3:13 AM CEST, Markus Probst via B4 Relay wrote:

From: Markus Probst <[email protected]>

Return the reference to the initialized data in the devres::register function.

This is needed in a following commit (rust: add basic serial device bus abstractions).

Quoted 7 lines

For driver-core and DRM,

This is useful in the context of the HRT work in general, should this series not make it this cycle, please let me know, then I'm going to pick this through the driver-core tree.

As discussed, rust_private_data is not needed anymore thus this patch has been dropped. Feel free to pick it.

Thanks
- Markus Probst

author maintainer
#18 lore raw
In reply to Danilo Krummrich
Quoted 16 lines · Danilo Krummrich
Quoted 15 lines · Markus Probst
Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Markus Probst

This would work, but I don't see how it would get rid of rust_private_data in this way. The device private data will but the private bus abstraction data needs to outlive the devres callbacks (which is done by rust_private_data).

Why? You only ever use it in the receive callback, which won't be called after device unbind anymore.

Because the possibility exists that some classdev ops or Drop calls e.g. sdev.set_baudrate. This is a null pointer dereference after serdev_device_close has been called. I interpreted it to add a state to the abstraction private data which would prevent those calls (early return with error) after serdev_device_close has been called, but this would only work if it outlives these calls.

Quoted 5 lines
Quoted 1 line

But it seems you were refering to something else with the state?

Yes, but I just notice that I'm a step ahead. With the lifetime model class device registrations shouldn't be guarded with Devres anymore, but with a lifetime.

That might be an issue. pin-init doesn't have enum support yet, so at least in my driver devres is still required for now.

I will readd the rust_private_data field.

Thanks
- Markus Probst

Quoted 7 lines

(This also entirely eliminates the need for having different devres stages to prevent drivers from smuggling a newly created Devres object into an existing Devres<Registration<T>>'s data, which would be unsound for obvious reasons.)

With this there is no way there are still class device callbacks after the bus device private data has been dropped in the first place.

maintainer
#19 lore raw
Quoted 2 lines · Markus Probst

pin-init doesn't have enum support yet, so at least in my driver devres is still required for now.

Hm...how is this related to having a registration type that takes a lifetime rather than a registration type being wrapped in Devres?

author maintainer
#20 lore raw
Quoted 6 lines · Danilo Krummrich
Quoted 2 lines · Markus Probst

pin-init doesn't have enum support yet, so at least in my driver devres is still required for now.

Hm...how is this related to having a registration type that takes a lifetime rather than a registration type being wrapped in Devres?

In order to register "optional" devices, the driver currently uses devres::register.

I just released I could use KBox for this.

Thanks
- Markus Probst

maintainer
#21 lore raw
Quoted 11 lines · Markus Probst
Quoted 6 lines · Danilo Krummrich
Quoted 2 lines · Markus Probst

pin-init doesn't have enum support yet, so at least in my driver devres is still required for now.

Hm...how is this related to having a registration type that takes a lifetime rather than a registration type being wrapped in Devres?

In order to register "optional" devices, the driver currently uses devres::register.

I just released I could use KBox for this.

Ah, so you basically use devres::register() to avoid a pinned Option. Let's not absuse devres for this.

The class device registration should rather use a lifetime now that we got all the infrastructure for this; the pinned Option problem can be tackled otherwise.