Skip to contentSkip to conversation

rust: add basic serial device bus abstractions

PATCH Superseded Markus Probst 5 participants 19 messages Jul 15 – Jul 17

Subsystems (4)

v14 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

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

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

Changes in v12:
- fix CoreInternal instead of BoundInternal
- Link to v11: https://patch.msgid.link/[email protected]

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

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

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

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

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

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

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

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

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

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

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

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

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

author maintainer
#1 lore raw

PATCH v14 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           | 599 ++++++++++++++++++++++++++++++++++++++++
 7 files changed, 634 insertions(+)
MAINTAINERS +2 -0
index 806bd2d80d15..cd735d227892 100644
@@ -24568,6 +24568,8 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/serial/serial.yaml
 F:	drivers/tty/serdev/
 F:	include/linux/serdev.h
+F:	rust/helpers/serdev.c
+F:	rust/kernel/serdev.rs
 
 SERIAL IR RECEIVER
 M:	Sean Young <[email protected]>
drivers/tty/serdev/Kconfig +7 -0
index 46ae732bfc68..e6dfe949ad01 100644
@@ -9,6 +9,13 @@ menuconfig SERIAL_DEV_BUS
 
 	  Note that you typically also want to enable TTY port controller support.
 
+config RUST_SERIAL_DEV_BUS_ABSTRACTIONS
+	bool "Rust Serial device bus abstractions"
+	depends on RUST
+	select SERIAL_DEV_BUS
+	help
+	  This enables the Rust abstraction for the serial device bus API.
+
 if SERIAL_DEV_BUS
 
 config SERIAL_DEV_CTRL_TTYPORT
rust/bindings/bindings_helper.h +1 -0
index 1124785e210b..fe7c505da236 100644
@@ -85,6 +85,7 @@
 #include <linux/regulator/consumer.h>
 #include <linux/sched.h>
 #include <linux/security.h>
+#include <linux/serdev.h>
 #include <linux/slab.h>
 #include <linux/sys_soc.h>
 #include <linux/task_work.h>
rust/helpers/helpers.c +1 -0
index 998e31052e66..6921a5ecb78a 100644
@@ -87,6 +87,7 @@
 #include "regulator.c"
 #include "scatterlist.c"
 #include "security.c"
+#include "serdev.c"
 #include "signal.c"
 #include "slab.c"
 #include "spinlock.c"
rust/helpers/serdev.c new file +22 -0
new file mode 100644
index 000000000000..c52b78ca3fc7
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/serdev.h>
+
+__rust_helper
+void rust_helper_serdev_device_driver_unregister(struct serdev_device_driver *sdrv)
+{
+	serdev_device_driver_unregister(sdrv);
+}
+
+__rust_helper
+void rust_helper_serdev_device_put(struct serdev_device *serdev)
+{
+	serdev_device_put(serdev);
+}
+
+__rust_helper
+void rust_helper_serdev_device_set_client_ops(struct serdev_device *serdev,
+					      const struct serdev_device_ops *ops)
+{
+	serdev_device_set_client_ops(serdev, ops);
+}
rust/kernel/lib.rs +2 -0
index 9512af7156df..d5ca17336739 100644
@@ -119,6 +119,8 @@
 pub mod scatterlist;
 pub mod security;
 pub mod seq_file;
+#[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
+pub mod serdev;
 pub mod sizes;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
rust/kernel/serdev.rs new file +599 -0

599 lines not on this page · raw message

Signature · 1 line
2.54.0
#2 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Drivers cannot synchronously wait for data during `probe` without causing a deadlock, because…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Drivers cannot synchronously wait for data during probe without causing a deadlock, because receive_buf_callback blocks on a mutex held by probe_callback.
- [High] Concurrent device callbacks during unbind or probe failure lead to Use-After-Free (UAF) or NULL pointer dereference because driver data is cleared before the device is closed.
- [High] Device::set_baudrate incorrectly treats approximate baudrates as errors, which will fail driver initialization on many hardware platforms.
--

--- Patch [1]: [PATCH v14 1/3] rust: add basic serial device bus abstractions ---
Note: The format of this review is altered to provide a free-form summary of the findings, rather than inline diff comments, due to system recitation restrictions.

commit c091dc3bf08c045ff86b0afe5e41d3fd0a94bb83
Author: Markus Probst <[email protected]>
Subject: rust: add basic serial device bus abstractions

Implement the basic serial device bus abstractions required to write a serial device bus device driver.

[Severity: High]
In Adapter<T>::probe_callback(), the code acquires the active mutex and holds it across serdev_device_open() and data.__pinned_init(). If a driver needs to send a command to the device and synchronously wait for a response during its probe routine, won't this cause a deadlock?

When the device responds, Adapter<T>::receive_buf_callback() is invoked in the RX workqueue and attempts to lock the exact same active mutex. Since probe_callback() is blocked waiting for the response, and receive_buf_callback() is blocked waiting for the mutex, the system seems like it will deadlock. Is it possible to unlock before waiting, or use a different synchronization strategy?

[Severity: High]
Looking at Adapter<T>::remove_callback(), it appears that T::unbind() is called, but PrivateData is never explicitly dropped or obtained from the device data, which might leave the device open and leak memory.

When remove_callback() returns, the C driver core sets drvdata to NULL. If data arrives immediately after, receive_buf_callback() might read a NULL pointer from drvdata_borrow() and dereference it.

Similarly, on a probe error in Adapter<T>::probe_callback(), ScopeGuard clears drvdata before PrivateData's PinnedDrop implementation closes the device. Does this create a race window where the device is still open and receiving data while drvdata is NULL or in the process of being destroyed?

[Severity: High]
In Device::set_baudrate(), the success condition is checked using strict equality (ret == speed).

Since serdev_device_set_baudrate() configures the hardware and returns the actual achieved baudrate (or 0 on failure), hardware clock divider limitations often result in a baudrate that is close but not exactly equal to the requested speed (for example, returning 115198 when 115200 is requested).

Will this strict equality check cause valid driver initializations to fail on platforms that can only approximate the requested baudrate?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
reviewer
#3 lore raw
In reply to Markus Probst
Quoted 190 lines · 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           | 599 ++++++++++++++++++++++++++++++++++++++++
 7 files changed, 634 insertions(+)
MAINTAINERS +2 -0
index 806bd2d80d15..cd735d227892 100644
@@ -24568,6 +24568,8 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/serial/serial.yaml
 F:	drivers/tty/serdev/
 F:	include/linux/serdev.h
+F:	rust/helpers/serdev.c
+F:	rust/kernel/serdev.rs
 
 SERIAL IR RECEIVER
 M:	Sean Young <[email protected]>
drivers/tty/serdev/Kconfig +7 -0
index 46ae732bfc68..e6dfe949ad01 100644
@@ -9,6 +9,13 @@ menuconfig SERIAL_DEV_BUS
 
 	  Note that you typically also want to enable TTY port controller support.
 
+config RUST_SERIAL_DEV_BUS_ABSTRACTIONS
+	bool "Rust Serial device bus abstractions"
+	depends on RUST
+	select SERIAL_DEV_BUS
+	help
+	  This enables the Rust abstraction for the serial device bus API.
+
 if SERIAL_DEV_BUS
 
 config SERIAL_DEV_CTRL_TTYPORT
rust/bindings/bindings_helper.h +1 -0
index 1124785e210b..fe7c505da236 100644
@@ -85,6 +85,7 @@
 #include <linux/regulator/consumer.h>
 #include <linux/sched.h>
 #include <linux/security.h>
+#include <linux/serdev.h>
 #include <linux/slab.h>
 #include <linux/sys_soc.h>
 #include <linux/task_work.h>
rust/helpers/helpers.c +1 -0
index 998e31052e66..6921a5ecb78a 100644
@@ -87,6 +87,7 @@
 #include "regulator.c"
 #include "scatterlist.c"
 #include "security.c"
+#include "serdev.c"
 #include "signal.c"
 #include "slab.c"
 #include "spinlock.c"
rust/helpers/serdev.c new file +22 -0
new file mode 100644
index 000000000000..c52b78ca3fc7
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/serdev.h>
+
+__rust_helper
+void rust_helper_serdev_device_driver_unregister(struct serdev_device_driver *sdrv)
+{
+	serdev_device_driver_unregister(sdrv);
+}
+
+__rust_helper
+void rust_helper_serdev_device_put(struct serdev_device *serdev)
+{
+	serdev_device_put(serdev);
+}
+
+__rust_helper
+void rust_helper_serdev_device_set_client_ops(struct serdev_device *serdev,
+					      const struct serdev_device_ops *ops)
+{
+	serdev_device_set_client_ops(serdev, ops);
+}
rust/kernel/lib.rs +2 -0
index 9512af7156df..d5ca17336739 100644
@@ -119,6 +119,8 @@
 pub mod scatterlist;
 pub mod security;
 pub mod seq_file;
+#[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
+pub mod serdev;
 pub mod sizes;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
rust/kernel/serdev.rs new file +65 -0
new file mode 100644
index 000000000000..0ffcef1849d2
@@ -0,0 +1,599 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Abstractions for the serial device bus.
+//!
+//! C header: [`include/linux/serdev.h`](srctree/include/linux/serdev.h)
+
+use crate::{
+    acpi,
+    device,
+    driver,
+    error::{
+        from_result,
+        to_result,
+        VTABLE_DEFAULT_ERROR, //
+    },
+    new_mutex,
+    of,
+    prelude::*,
+    sync::{
+        aref::AlwaysRefCounted,
+        Mutex, //
+    },
+    time::{
+        msecs_to_jiffies,
+        Jiffies,
+        Msecs, //
+    },
+    types::{
+        Opaque,
+        ScopeGuard, //
+    }, //
+};
+
+use core::{
+    cell::UnsafeCell,
+    marker::PhantomData,
+    mem::{offset_of, MaybeUninit},
+    num::NonZero,
+    ptr::NonNull, //
+};
+
+/// Parity bit to use with a serial device.
+#[repr(u32)]
+pub enum Parity {
+    /// No parity bit.
+    None = bindings::serdev_parity_SERDEV_PARITY_NONE,
+    /// Even partiy.
+    Even = bindings::serdev_parity_SERDEV_PARITY_EVEN,
+    /// Odd parity.
+    Odd = bindings::serdev_parity_SERDEV_PARITY_ODD,
+}
+
+/// Timeout in Jiffies.
+pub enum Timeout {
+    /// Wait for a specific amount of [`Jiffies`].
+    Jiffies(NonZero<Jiffies>),
+    /// Wait for a specific amount of [`Msecs`].
+    Milliseconds(NonZero<Msecs>),
+    /// Wait as long as possible.
+    ///
+    /// This is equivalent to [`kernel::task::MAX_SCHEDULE_TIMEOUT`].
+    Max,
+}
+
+impl Timeout {

rust/kernel/serdev.rs line 75

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    fn into_jiffies(self) -> isize {
+        match self {
+            Self::Jiffies(value) => value.get().try_into().unwrap_or_default(),
+            Self::Milliseconds(value) => {
+                msecs_to_jiffies(value.get()).try_into().unwrap_or_default()
+            }
+            Self::Max => 0,
+        }
+    }
+}

FWIW this shouldn't be part of serdev abstraction. See
https://lore.kernel.org/rust-for-linux/[email protected]

Quoted 107 lines
rust/kernel/serdev.rs new file +107 -0
+
+/// An adapter for the registration of serial device bus device drivers.
+pub struct Adapter<T: Driver>(T);
+
+// SAFETY:
+// - `bindings::serdev_device_driver` is a C type declared as `repr(C)`.
+// - `PrivateData<'bound, T>` is the type of the driver's device private data.
+// - `struct serdev_device_driver` embeds a `struct device_driver`.
+// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
+unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
+    type DriverType = bindings::serdev_device_driver;
+    type DriverData<'bound> = PrivateData<'bound, T>;
+    const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
+}
+
+// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
+// a preceding call to `register` has been successful.
+unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
+    unsafe fn register(
+        sdrv: &Opaque<Self::DriverType>,
+        name: &'static CStr,
+        module: &'static ThisModule,
+    ) -> Result {
+        let of_table = match T::OF_ID_TABLE {
+            Some(table) => table.as_ptr(),
+            None => core::ptr::null(),
+        };
+
+        let acpi_table = match T::ACPI_ID_TABLE {
+            Some(table) => table.as_ptr(),
+            None => core::ptr::null(),
+        };
+
+        // SAFETY: It's safe to set the fields of `struct serdev_device_driver` on initialization.
+        unsafe {
+            (*sdrv.get()).driver.name = name.as_char_ptr();
+            (*sdrv.get()).probe = Some(Self::probe_callback);
+            (*sdrv.get()).remove = Some(Self::remove_callback);
+            (*sdrv.get()).driver.of_match_table = of_table;
+            (*sdrv.get()).driver.acpi_match_table = acpi_table;
+        }
+
+        // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
+        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.0) })
+    }
+
+    unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {
+        // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
+        unsafe { bindings::serdev_device_driver_unregister(sdrv.get()) };
+    }
+}
+
+#[doc(hidden)]
+#[pin_data(PinnedDrop)]
+pub struct PrivateData<'bound, T: Driver> {
+    sdev: &'bound Device<device::Bound>,
+    #[pin]
+    driver: UnsafeCell<MaybeUninit<T::Data<'bound>>>,
+    open: UnsafeCell<bool>,
+    #[pin]
+    active: Mutex<bool>,
+}
+
+#[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;
+        }
+        drop(active);
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}
+
+impl<T: Driver> Adapter<T> {
+    const OPS: &'static bindings::serdev_device_ops = &bindings::serdev_device_ops {
+        receive_buf: if T::HAS_RECEIVE {
+            Some(Self::receive_buf_callback)
+        } else {
+            None
+        },
+        write_wakeup: Some(bindings::serdev_device_write_wakeup),
+    };
+
+    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(|| {
+            sdev.as_ref().set_drvdata(try_pin_init!(PrivateData::<T> {
+                sdev: &**sdev,
+                driver: MaybeUninit::<T::Data<'_>>::zeroed().into(),

rust/kernel/serdev.rs line 192

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+                open: false.into(),
+                active <- new_mutex!(false),
+            }))?;
+            // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
+            let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+            let private_data = ScopeGuard::new_with_data(private_data, |_| {
+                // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
+                drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
+            });
+            let mut active = private_data.active.lock();

What's this for? This gives me a strong vibe that something is off. Either the serdev subsystem is not having sufficient synchronization or there is an abstraction issue.

Either way, you really should have more comments about what this active mutex is for and why it is needed.

Quoted 243 lines
rust/kernel/serdev.rs new file +243 -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::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);
+
+            // SAFETY: We have exclusive access to `private_data.driver`.
+            let driver = unsafe { &mut *private_data.driver.get() };
+            // SAFETY:
+            // - `driver.as_mut_ptr()` is a valid pointer to uninitialized data.
+            // - `private_data.driver` is pinned.
+            let result = unsafe { data.__pinned_init(driver.as_mut_ptr()) };
+
+            *active = result.is_ok();
+
+            drop(active);
+
+            result.map(|()| {
+                private_data.dismiss();
+                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>>() };
+
+        // 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);
+    }
+
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::BoundInternal>>() };
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
+
+impl<T: Driver> driver::Adapter for Adapter<T> {
+    type IdInfo = T::IdInfo;
+
+    fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
+        T::OF_ID_TABLE
+    }
+
+    fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
+        T::ACPI_ID_TABLE
+    }
+}
+
+/// Declares a kernel module that exposes a single serial device bus device driver.
+///
+/// # Examples
+///
+/// ```ignore
+/// kernel::module_serdev_device_driver! {
+///     type: MyDriver,
+///     name: "Module name",
+///     authors: ["Author name"],
+///     description: "Description",
+///     license: "GPL v2",
+/// }
+/// ```
+#[macro_export]
+macro_rules! module_serdev_device_driver {
+    ($($f:tt)*) => {
+        $crate::module_driver!(<T>, $crate::serdev::Adapter<T>, { $($f)* });
+    };
+}
+
+/// The serial device bus device driver trait.
+///
+/// Drivers must implement this trait in order to get a serial device bus device driver registered.
+///
+/// # Examples
+///
+///```
+/// # use kernel::{
+///     acpi,
+///     bindings,
+///     device::{
+///         Bound,
+///         Core, //
+///     },
+///     of,
+///     serdev, //
+/// };
+///
+/// struct MyDriver;
+///
+/// kernel::of_device_table!(
+///     OF_TABLE,
+///     MODULE_OF_TABLE,
+///     <MyDriver as serdev::Driver>::IdInfo,
+///     [
+///         (of::DeviceId::new(c"test,device"), ())
+///     ]
+/// );
+///
+/// kernel::acpi_device_table!(
+///     ACPI_TABLE,
+///     MODULE_ACPI_TABLE,
+///     <MyDriver as serdev::Driver>::IdInfo,
+///     [
+///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
+///     ]
+/// );
+///
+/// #[vtable]
+/// impl serdev::Driver for MyDriver {
+///     type IdInfo = ();
+///     type Data<'bound> = Self;
+///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
+///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
+///
+///     fn probe<'bound>(
+///         sdev: &'bound serdev::Device<Core<'_>>,
+///         _id_info: Option<&'bound Self::IdInfo>,
+///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+///         sdev.set_baudrate(115200);
+///         sdev.write_all(b"Hello\n", serdev::Timeout::Max)?;
+///         Ok(MyDriver)
+///     }
+/// }
+///```
+#[vtable]
+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 + Sync + 'bound;
+
+    /// The table of OF device ids supported by the driver.
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
+
+    /// The table of ACPI device ids supported by the driver.
+    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
+
+    /// Serial device bus device driver probe.
+    ///
+    /// Called when a new serial device bus device is added or discovered.
+    /// Implementers should attempt to initialize the device here.
+    fn probe<'bound>(
+        sdev: &'bound Device<device::Core<'_>>,
+        id_info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
+
+    /// Serial device bus device driver unbind.
+    ///
+    /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
+    /// is optional.
+    ///
+    /// This callback serves as a place for drivers to perform teardown operations that require a
+    /// `&Device<Core>` or `&Device<Bound>` reference. For instance.
+    ///
+    /// Otherwise, release operations for driver resources should be performed in `Drop`.
+    fn unbind<'bound>(sdev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
+        let _ = (sdev, this);
+    }
+
+    /// Serial device bus device data receive callback.
+    ///
+    /// Called when data got received from device.
+    ///
+    /// Returns the number of bytes accepted.
+    fn receive<'bound>(
+        sdev: &'bound Device<device::Bound>,
+        this: Pin<&Self::Data<'bound>>,
+        data: &[u8],
+    ) -> usize {
+        let _ = (sdev, this, data);
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+}
+
+/// The serial device bus device representation.
+///
+/// This structure represents the Rust abstraction for a C `struct serdev_device`. The
+/// implementation abstracts the usage of an already existing C `struct serdev_device` within Rust
+/// code that we get passed from the C side.
+///
+/// # Invariants
+///
+/// A [`Device`] instance represents a valid `struct serdev_device` created by the C portion of
+/// the kernel.

rust/kernel/serdev.rs line 445

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+#[repr(transparent)]
+pub struct Device<Ctx: device::DeviceContext = device::Normal>(
+    Opaque<bindings::serdev_device>,
+    PhantomData<Ctx>,
+);
+
+impl<Ctx: device::DeviceContext> Device<Ctx> {
+    fn as_raw(&self) -> *mut bindings::serdev_device {
+        self.0.get()
+    }

This and many other functions should be #[inline]. I am surprised that Sashiko didn't point out.

Best,
Gary

author maintainer
#4 lore raw
Quoted 318 lines · Gary Guo
Quoted 190 lines · 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           | 599 ++++++++++++++++++++++++++++++++++++++++
 7 files changed, 634 insertions(+)
MAINTAINERS +2 -0
index 806bd2d80d15..cd735d227892 100644
@@ -24568,6 +24568,8 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/serial/serial.yaml
 F:	drivers/tty/serdev/
 F:	include/linux/serdev.h
+F:	rust/helpers/serdev.c
+F:	rust/kernel/serdev.rs
 
 SERIAL IR RECEIVER
 M:	Sean Young <[email protected]>
drivers/tty/serdev/Kconfig +7 -0
index 46ae732bfc68..e6dfe949ad01 100644
@@ -9,6 +9,13 @@ menuconfig SERIAL_DEV_BUS
 
 	  Note that you typically also want to enable TTY port controller support.
 
+config RUST_SERIAL_DEV_BUS_ABSTRACTIONS
+	bool "Rust Serial device bus abstractions"
+	depends on RUST
+	select SERIAL_DEV_BUS
+	help
+	  This enables the Rust abstraction for the serial device bus API.
+
 if SERIAL_DEV_BUS
 
 config SERIAL_DEV_CTRL_TTYPORT
rust/bindings/bindings_helper.h +1 -0
index 1124785e210b..fe7c505da236 100644
@@ -85,6 +85,7 @@
 #include <linux/regulator/consumer.h>
 #include <linux/sched.h>
 #include <linux/security.h>
+#include <linux/serdev.h>
 #include <linux/slab.h>
 #include <linux/sys_soc.h>
 #include <linux/task_work.h>
rust/helpers/helpers.c +1 -0
index 998e31052e66..6921a5ecb78a 100644
@@ -87,6 +87,7 @@
 #include "regulator.c"
 #include "scatterlist.c"
 #include "security.c"
+#include "serdev.c"
 #include "signal.c"
 #include "slab.c"
 #include "spinlock.c"
rust/helpers/serdev.c new file +22 -0
new file mode 100644
index 000000000000..c52b78ca3fc7
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/serdev.h>
+
+__rust_helper
+void rust_helper_serdev_device_driver_unregister(struct serdev_device_driver *sdrv)
+{
+	serdev_device_driver_unregister(sdrv);
+}
+
+__rust_helper
+void rust_helper_serdev_device_put(struct serdev_device *serdev)
+{
+	serdev_device_put(serdev);
+}
+
+__rust_helper
+void rust_helper_serdev_device_set_client_ops(struct serdev_device *serdev,
+					      const struct serdev_device_ops *ops)
+{
+	serdev_device_set_client_ops(serdev, ops);
+}
rust/kernel/lib.rs +2 -0
index 9512af7156df..d5ca17336739 100644
@@ -119,6 +119,8 @@
 pub mod scatterlist;
 pub mod security;
 pub mod seq_file;
+#[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
+pub mod serdev;
 pub mod sizes;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
rust/kernel/serdev.rs new file +65 -0
new file mode 100644
index 000000000000..0ffcef1849d2
@@ -0,0 +1,599 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Abstractions for the serial device bus.
+//!
+//! C header: [`include/linux/serdev.h`](srctree/include/linux/serdev.h)
+
+use crate::{
+    acpi,
+    device,
+    driver,
+    error::{
+        from_result,
+        to_result,
+        VTABLE_DEFAULT_ERROR, //
+    },
+    new_mutex,
+    of,
+    prelude::*,
+    sync::{
+        aref::AlwaysRefCounted,
+        Mutex, //
+    },
+    time::{
+        msecs_to_jiffies,
+        Jiffies,
+        Msecs, //
+    },
+    types::{
+        Opaque,
+        ScopeGuard, //
+    }, //
+};
+
+use core::{
+    cell::UnsafeCell,
+    marker::PhantomData,
+    mem::{offset_of, MaybeUninit},
+    num::NonZero,
+    ptr::NonNull, //
+};
+
+/// Parity bit to use with a serial device.
+#[repr(u32)]
+pub enum Parity {
+    /// No parity bit.
+    None = bindings::serdev_parity_SERDEV_PARITY_NONE,
+    /// Even partiy.
+    Even = bindings::serdev_parity_SERDEV_PARITY_EVEN,
+    /// Odd parity.
+    Odd = bindings::serdev_parity_SERDEV_PARITY_ODD,
+}
+
+/// Timeout in Jiffies.
+pub enum Timeout {
+    /// Wait for a specific amount of [`Jiffies`].
+    Jiffies(NonZero<Jiffies>),
+    /// Wait for a specific amount of [`Msecs`].
+    Milliseconds(NonZero<Msecs>),
+    /// Wait as long as possible.
+    ///
+    /// This is equivalent to [`kernel::task::MAX_SCHEDULE_TIMEOUT`].
+    Max,
+}
+
+impl Timeout {

rust/kernel/serdev.rs line 75

Quoted 10 lines
rust/kernel/serdev.rs new file +10 -0
+    fn into_jiffies(self) -> isize {
+        match self {
+            Self::Jiffies(value) => value.get().try_into().unwrap_or_default(),
+            Self::Milliseconds(value) => {
+                msecs_to_jiffies(value.get()).try_into().unwrap_or_default()
+            }
+            Self::Max => 0,
+        }
+    }
+}

FWIW this shouldn't be part of serdev abstraction. See
https://lore.kernel.org/rust-for-linux/[email protected]

Quoted 113 lines
rust/kernel/serdev.rs new file +113 -0
+
+/// An adapter for the registration of serial device bus device drivers.
+pub struct Adapter<T: Driver>(T);
+
+// SAFETY:
+// - `bindings::serdev_device_driver` is a C type declared as `repr(C)`.
+// - `PrivateData<'bound, T>` is the type of the driver's device private data.
+// - `struct serdev_device_driver` embeds a `struct device_driver`.
+// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
+unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
+    type DriverType = bindings::serdev_device_driver;
+    type DriverData<'bound> = PrivateData<'bound, T>;
+    const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
+}
+
+// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
+// a preceding call to `register` has been successful.
+unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
+    unsafe fn register(
+        sdrv: &Opaque<Self::DriverType>,
+        name: &'static CStr,
+        module: &'static ThisModule,
+    ) -> Result {
+        let of_table = match T::OF_ID_TABLE {
+            Some(table) => table.as_ptr(),
+            None => core::ptr::null(),
+        };
+
+        let acpi_table = match T::ACPI_ID_TABLE {
+            Some(table) => table.as_ptr(),
+            None => core::ptr::null(),
+        };
+
+        // SAFETY: It's safe to set the fields of `struct serdev_device_driver` on initialization.
+        unsafe {
+            (*sdrv.get()).driver.name = name.as_char_ptr();
+            (*sdrv.get()).probe = Some(Self::probe_callback);
+            (*sdrv.get()).remove = Some(Self::remove_callback);
+            (*sdrv.get()).driver.of_match_table = of_table;
+            (*sdrv.get()).driver.acpi_match_table = acpi_table;
+        }
+
+        // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
+        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.0) })
+    }
+
+    unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {
+        // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
+        unsafe { bindings::serdev_device_driver_unregister(sdrv.get()) };
+    }
+}
+
+#[doc(hidden)]
+#[pin_data(PinnedDrop)]
+pub struct PrivateData<'bound, T: Driver> {
+    sdev: &'bound Device<device::Bound>,
+    #[pin]
+    driver: UnsafeCell<MaybeUninit<T::Data<'bound>>>,
+    open: UnsafeCell<bool>,
+    #[pin]
+    active: Mutex<bool>,
+}
+
+#[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;
+        }
+        drop(active);
+
+        // SAFETY: We have exclusive access to `self.open`.
+        if unsafe { *self.open.get() } {
+            // SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+            // `struct serdev_device`.
+            unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+        }
+    }
+}
+
+impl<T: Driver> Adapter<T> {
+    const OPS: &'static bindings::serdev_device_ops = &bindings::serdev_device_ops {
+        receive_buf: if T::HAS_RECEIVE {
+            Some(Self::receive_buf_callback)
+        } else {
+            None
+        },
+        write_wakeup: Some(bindings::serdev_device_write_wakeup),
+    };
+
+    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(|| {
+            sdev.as_ref().set_drvdata(try_pin_init!(PrivateData::<T> {
+                sdev: &**sdev,
+                driver: MaybeUninit::<T::Data<'_>>::zeroed().into(),
+                open: false.into(),
+                active <- new_mutex!(false),
+            }))?;
+            // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
+            let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+            let private_data = ScopeGuard::new_with_data(private_data, |_| {
Quoted 8 lines

rust/kernel/serdev.rs line 192

Quoted 4 lines
rust/kernel/serdev.rs new file +4 -0
+                // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
+                drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
+            });
+            let mut active = private_data.active.lock();

What's this for? This gives me a strong vibe that something is off. Either the serdev subsystem is not having sufficient synchronization or there is an abstraction issue.

There is the following issue it trys to solve:

In the rust abstraction, the driver data is only initialized after the probe. serdev_device_open should be called inside or before probe, because otherwise the driver can't configure the serdev device. But as a sideeffect, once the serdev device is open, it is possible for receive_buf_callback to be called, which this mutex prevents while the driver data is not initialized yet.

Quoted 252 lines

Either way, you really should have more comments about what this active mutex is for and why it is needed.

Quoted 248 lines
rust/kernel/serdev.rs new file +248 -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::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);
+
+            // SAFETY: We have exclusive access to `private_data.driver`.
+            let driver = unsafe { &mut *private_data.driver.get() };
+            // SAFETY:
+            // - `driver.as_mut_ptr()` is a valid pointer to uninitialized data.
+            // - `private_data.driver` is pinned.
+            let result = unsafe { data.__pinned_init(driver.as_mut_ptr()) };
+
+            *active = result.is_ok();
+
+            drop(active);
+
+            result.map(|()| {
+                private_data.dismiss();
+                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>>() };
+
+        // 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);
+    }
+
+    extern "C" fn receive_buf_callback(
+        sdev: *mut bindings::serdev_device,
+        buf: *const u8,
+        length: usize,
+    ) -> usize {
+        // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
+        // pointer to a `struct serdev_device`.
+        //
+        // INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
+        let sdev = unsafe { &*sdev.cast::<Device<device::BoundInternal>>() };
+
+        // SAFETY: `receive_buf_callback` is only ever called after a successful call to
+        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<PrivateData<'_, T>>>`.
+        let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
+        let active = private_data.active.lock();
+
+        if !*active {
+            return length;
+        }
+
+        // SAFETY: No one has exclusive access to `private_data.driver`.
+        let data = unsafe { &*private_data.driver.get() };
+        // SAFETY:
+        // - `private_data.driver` is pinned.
+        // - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
+        //   hence it's guaranteed that `private_data.driver` was initialized.
+        let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
+        T::receive(sdev, data_pinned, buf)
+    }
+}
+
+impl<T: Driver> driver::Adapter for Adapter<T> {
+    type IdInfo = T::IdInfo;
+
+    fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
+        T::OF_ID_TABLE
+    }
+
+    fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
+        T::ACPI_ID_TABLE
+    }
+}
+
+/// Declares a kernel module that exposes a single serial device bus device driver.
+///
+/// # Examples
+///
+/// ```ignore
+/// kernel::module_serdev_device_driver! {
+///     type: MyDriver,
+///     name: "Module name",
+///     authors: ["Author name"],
+///     description: "Description",
+///     license: "GPL v2",
+/// }
+/// ```
+#[macro_export]
+macro_rules! module_serdev_device_driver {
+    ($($f:tt)*) => {
+        $crate::module_driver!(<T>, $crate::serdev::Adapter<T>, { $($f)* });
+    };
+}
+
+/// The serial device bus device driver trait.
+///
+/// Drivers must implement this trait in order to get a serial device bus device driver registered.
+///
+/// # Examples
+///
+///```
+/// # use kernel::{
+///     acpi,
+///     bindings,
+///     device::{
+///         Bound,
+///         Core, //
+///     },
+///     of,
+///     serdev, //
+/// };
+///
+/// struct MyDriver;
+///
+/// kernel::of_device_table!(
+///     OF_TABLE,
+///     MODULE_OF_TABLE,
+///     <MyDriver as serdev::Driver>::IdInfo,
+///     [
+///         (of::DeviceId::new(c"test,device"), ())
+///     ]
+/// );
+///
+/// kernel::acpi_device_table!(
+///     ACPI_TABLE,
+///     MODULE_ACPI_TABLE,
+///     <MyDriver as serdev::Driver>::IdInfo,
+///     [
+///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
+///     ]
+/// );
+///
+/// #[vtable]
+/// impl serdev::Driver for MyDriver {
+///     type IdInfo = ();
+///     type Data<'bound> = Self;
+///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
+///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
+///
+///     fn probe<'bound>(
+///         sdev: &'bound serdev::Device<Core<'_>>,
+///         _id_info: Option<&'bound Self::IdInfo>,
+///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+///         sdev.set_baudrate(115200);
+///         sdev.write_all(b"Hello\n", serdev::Timeout::Max)?;
+///         Ok(MyDriver)
+///     }
+/// }
+///```
+#[vtable]
+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 + Sync + 'bound;
+
+    /// The table of OF device ids supported by the driver.
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
+
+    /// The table of ACPI device ids supported by the driver.
+    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
+
+    /// Serial device bus device driver probe.
+    ///
+    /// Called when a new serial device bus device is added or discovered.
+    /// Implementers should attempt to initialize the device here.
+    fn probe<'bound>(
+        sdev: &'bound Device<device::Core<'_>>,
+        id_info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
+
+    /// Serial device bus device driver unbind.
+    ///
+    /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
+    /// is optional.
+    ///
+    /// This callback serves as a place for drivers to perform teardown operations that require a
+    /// `&Device<Core>` or `&Device<Bound>` reference. For instance.
+    ///
+    /// Otherwise, release operations for driver resources should be performed in `Drop`.
+    fn unbind<'bound>(sdev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
+        let _ = (sdev, this);
+    }
+
+    /// Serial device bus device data receive callback.
+    ///
+    /// Called when data got received from device.
+    ///
+    /// Returns the number of bytes accepted.
+    fn receive<'bound>(
+        sdev: &'bound Device<device::Bound>,
+        this: Pin<&Self::Data<'bound>>,
+        data: &[u8],
+    ) -> usize {
+        let _ = (sdev, this, data);
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+}
+
+/// The serial device bus device representation.
+///
+/// This structure represents the Rust abstraction for a C `struct serdev_device`. The
+/// implementation abstracts the usage of an already existing C `struct serdev_device` within Rust
+/// code that we get passed from the C side.
+///
+/// # Invariants
+///
+/// A [`Device`] instance represents a valid `struct serdev_device` created by the C portion of
+/// the kernel.
+#[repr(transparent)]
+pub struct Device<Ctx: device::DeviceContext = device::Normal>(
+    Opaque<bindings::serdev_device>,
+    PhantomData<Ctx>,
+);
Quoted 8 lines

rust/kernel/serdev.rs line 445

Quoted 5 lines
rust/kernel/serdev.rs new file +5 -0
+
+impl<Ctx: device::DeviceContext> Device<Ctx> {
+    fn as_raw(&self) -> *mut bindings::serdev_device {
+        self.0.get()
+    }

This and many other functions should be #[inline]. I am surprised that Sashiko didn't point out.

Yes, inline would make sense here. In this particular case, I used platform.rs as base, so the missing inline got inherited.

Thanks
- Markus Probst

Quoted 3 lines

Best,
Gary

author maintainer
#5 lore raw

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

In reply to Markus Probst

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

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

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

90 lines not on this page · raw message

Signature · 1 line
2.54.0
#6 lore raw

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

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] The `remove_callback` function in the Rust `serdev` abstraction fails to free the driver's private…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] The remove_callback function in the Rust serdev abstraction fails to free the driver's private data (PrivateData), leading to a memory leak when the device is unbound.
- [Medium] The receive callback returns the number of bytes written to the Tx buffer rather than the number of bytes consumed from the Rx buffer, which can permanently stall the TTY Rx path.
- [Low] The driver queries the non-standard device tree property baudrate instead of the standard current-speed to configure the serial speed.
- [Low] The driver registers an ACPI ID table but this behavior is entirely omitted from the commit message.
--

--- Patch [2]: [PATCH v14 2/3] samples: rust: add Rust serial device bus sample device driver --- commit 119f675ea28625315fe04a8ca0cdd59f9d0f26bc
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]
Does this description omit the ACPI ID table?

Looking at ACPI_TABLE in rust_driver_serdev.rs, the driver also registers an ACPI ID table for matching:

kernel::acpi_device_table!(
ACPI_TABLE,
MODULE_ACPI_TABLE,
<SampleDriver as serdev::Driver>::IdInfo,
[(acpi::DeviceId::new(c"LNUXBEEF"), ())]
);

Could the commit message be updated to mention the ACPI matching behavior as well?

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

[ ... ]

samples/rust/rust_driver_serdev.rs line 53

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

[Severity: Low]
Does this code use an incorrect, non-standard device tree property?

It looks like it queries c"baudrate" instead of the standard c"current-speed" property, which could cause it to fail to configure the speed on platforms compliant with standard bindings.

Quoted 8 lines
samples/rust/rust_driver_serdev.rs new file +8 -0
+                    .unwrap_or(115200),
+            )
+            .is_err()
+        {
+            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 {
+        sdev.write(data).unwrap_or_default() as usize

[Severity: Medium]
Could this permanently stall the TTY Rx path?

The receive callback appears to return the number of bytes written to the Tx buffer rather than the number of bytes consumed from the Rx buffer.

If the Tx buffer is full, sdev.write() returns 0, and the TTY layer will stop pushing data. Without a mechanism to wake up the Rx path when Tx space becomes available, does this permanently stall the receiver?

samples/rust/rust_driver_serdev.rs

Quoted 2 lines
samples/rust/rust_driver_serdev.rs new file +2 -0
+    }
+}

I also noticed an issue in rust/kernel/serdev.rs during driver unbind:

rust/kernel/serdev.rs:remove_callback() {
    ...
    let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };

    // SAFETY: No one has exclusive access to private_data.driver.
    let data = unsafe { &*private_data.driver.get() };
    ...
    T::unbind(sdev, data_pinned);
}

[Severity: High]
Does this code leak the driver's private data?

The remove_callback() function appears to fail to free PrivateData because it uses drvdata_borrow() instead of drvdata_obtain() on the teardown path, which would take ownership back and allow the driver data allocation to be dropped when the device is unbound.

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

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

In reply to Markus Probst

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

---
 MAINTAINERS | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
MAINTAINERS +1 -1
index 7d32aa7f42a4..d092042fed31 100644
@@ -24562,7 +24562,7 @@ F:	drivers/iio/chemical/sps30_i2c.c
 F:	drivers/iio/chemical/sps30_serial.c
 
 SERIAL DEVICE BUS
-M:	Rob Herring <[email protected]>
+M:	Markus Probst <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/devicetree/bindings/serial/serial.yaml
Signature · 1 line
2.54.0
#8 lore raw
In reply to Markus Probst
Quoted 6 lines · Markus Probst

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.

Quoted 8 lines

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

Given there are no objections, I'll go queue this up now, thanks.

greg k-h

author maintainer
#9 lore raw
Quoted 10 lines · Greg Kroah-Hartman
Quoted 9 lines · Markus Probst

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

Quoted 7 lines
Quoted 5 lines

This series depends on [1].

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

Given there are no objections, I'll go queue this up now, thanks.

Thanks for merging, but I haven't seen the dependency

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

getting picked yet (its at least not in linux-next), so it might not even compile. Not sure whats holding the patch back though.

Thanks
- Markus Probst

Quoted 2 lines

greg k-h

maintainer
#10 lore raw
Quoted 17 lines · Markus Probst
Quoted 16 lines · Greg Kroah-Hartman
Quoted 14 lines · Markus Probst

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

Quoted 7 lines
Quoted 1 line

Given there are no objections, I'll go queue this up now, thanks.

Thanks for merging, but I haven't seen the dependency

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

getting picked yet (its at least not in linux-next), so it might not even compile. Not sure whats holding the patch back though.

(Ah, saw this just after I replied to the other thread.)

Nothing is holding them back other than requiring a user (which is your work), so I did not pick them up.

Also note that tty and driver-core are different trees, so picking it up in driver-core would not have helped tty.

Thanks,
Danilo

#11 lore raw
Quoted 25 lines · Danilo Krummrich
Quoted 17 lines · Markus Probst
Quoted 16 lines · Greg Kroah-Hartman
Quoted 14 lines · Markus Probst

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

Quoted 7 lines
Quoted 1 line

Given there are no objections, I'll go queue this up now, thanks.

Thanks for merging, but I haven't seen the dependency

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

getting picked yet (its at least not in linux-next), so it might not even compile. Not sure whats holding the patch back though.

Quoted 7 lines

(Ah, saw this just after I replied to the other thread.)

Nothing is holding them back other than requiring a user (which is your work), so I did not pick them up.

Also note that tty and driver-core are different trees, so picking it up in driver-core would not have helped tty.

Should I drop this from the tty tree and take it through driver-core instead? If so, no problem for me, just let me know.

thanks,

greg k-h

reviewer
#12 lore raw
Quoted 28 lines · Greg Kroah-Hartman
Quoted 27 lines · Danilo Krummrich
Quoted 17 lines · Markus Probst
Quoted 16 lines · Greg Kroah-Hartman
Quoted 14 lines · Markus Probst

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

Quoted 7 lines
Quoted 1 line

Given there are no objections, I'll go queue this up now, thanks.

Thanks for merging, but I haven't seen the dependency

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

getting picked yet (its at least not in linux-next), so it might not even compile. Not sure whats holding the patch back though.

(Ah, saw this just after I replied to the other thread.)

Quoted 8 lines
Quoted 5 lines

Nothing is holding them back other than requiring a user (which is your work), so I did not pick them up.

Also note that tty and driver-core are different trees, so picking it up in driver-core would not have helped tty.

Should I drop this from the tty tree and take it through driver-core instead? If so, no problem for me, just let me know.

FWIW this series will also conflict quite significantly with
https://lore.kernel.org/driver-core/[email protected]/
which is routed via driver-core tree.

Best,
GAry

maintainer
#13 lore raw
Quoted 3 lines · Gary Guo

FWIW this series will also conflict quite significantly with
https://lore.kernel.org/driver-core/[email protected]/
which is routed via driver-core tree.

Yeah, but I think it should be trivial (see below)? However, routing serdev through driver-core does indeed avoid this.

Thanks,
Danilo

rust/kernel/serdev.rs +2 -3
index 0ffcef1849d2..a1161dd9f37f 100644
@@ -174,7 +174,8 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
         //
         // 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());
+        // SAFETY: `sdev` has been matched by the serial device bus via its device ID table.
+        let info = unsafe { <Self as driver::Adapter>::id_info(sdev.as_ref()) };
 
         from_result(|| {
             sdev.as_ref().set_drvdata(try_pin_init!(PrivateData::<T> {
@@ -334,7 +335,6 @@ macro_rules! module_serdev_device_driver {
 ///
 /// kernel::of_device_table!(
 ///     OF_TABLE,
-///     MODULE_OF_TABLE,
 ///     <MyDriver as serdev::Driver>::IdInfo,
 ///     [
 ///         (of::DeviceId::new(c"test,device"), ())
@@ -343,7 +343,6 @@ macro_rules! module_serdev_device_driver {
 ///
 /// kernel::acpi_device_table!(
 ///     ACPI_TABLE,
-///     MODULE_ACPI_TABLE,
 ///     <MyDriver as serdev::Driver>::IdInfo,
 ///     [
 ///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
samples/rust/rust_driver_serdev.rs +0 -2
index a12b1412db30..51b4898cd855 100644
@@ -20,14 +20,12 @@ struct SampleDriver {
 
 kernel::of_device_table!(
     OF_TABLE,
-    MODULE_OF_TABLE,
     <SampleDriver as serdev::Driver>::IdInfo,
     [(of::DeviceId::new(c"test,rust_driver_serdev"), ())]
 );
 
 kernel::acpi_device_table!(
     ACPI_TABLE,
-    MODULE_ACPI_TABLE,
     <SampleDriver as serdev::Driver>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), ())]
 );
author maintainer Reviewed-by
#14 lore raw
Quoted 43 lines · Danilo Krummrich
rust/kernel/serdev.rs +2 -3
index 0ffcef1849d2..a1161dd9f37f 100644
@@ -174,7 +174,8 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
          //
          // 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());
+        // SAFETY: `sdev` has been matched by the serial device bus via its device ID table.
+        let info = unsafe { <Self as driver::Adapter>::id_info(sdev.as_ref()) };
 
          from_result(|| {
              sdev.as_ref().set_drvdata(try_pin_init!(PrivateData::<T> {
@@ -334,7 +335,6 @@ macro_rules! module_serdev_device_driver {
  ///
  /// kernel::of_device_table!(
  ///     OF_TABLE,
-///     MODULE_OF_TABLE,
  ///     <MyDriver as serdev::Driver>::IdInfo,
  ///     [
  ///         (of::DeviceId::new(c"test,device"), ())
@@ -343,7 +343,6 @@ macro_rules! module_serdev_device_driver {
  ///
  /// kernel::acpi_device_table!(
  ///     ACPI_TABLE,
-///     MODULE_ACPI_TABLE,
  ///     <MyDriver as serdev::Driver>::IdInfo,
  ///     [
  ///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
samples/rust/rust_driver_serdev.rs +0 -0
index a12b1412db30..51b4898cd855 100644
@@ -20,14 +20,12 @@ struct SampleDriver {
 

 kernel::of_device_table!(
     OF_TABLE,
-    MODULE_OF_TABLE,
     <SampleDriver as serdev::Driver>::IdInfo, [(of::DeviceId::new(c"test,rust_driver_serdev"), ())] );

Quoted 6 lines

 kernel::acpi_device_table!(
     ACPI_TABLE,
-    MODULE_ACPI_TABLE,
     <SampleDriver as serdev::Driver>::IdInfo,
     [(acpi::DeviceId::new(c"LNUXBEEF"), ())]
 );

Not sure if necessary for a conflict resolution, but

Thanks
- Markus Probst

#16 lore raw
Quoted 9 lines · Danilo Krummrich
Quoted 2 lines · Greg Kroah-Hartman

Should I drop this from the tty tree and take it through driver-core instead? If so, no problem for me, just let me know.

Either should work, you can also take [1] through the tty tree, I don't think there will be any conflicts.

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

Hm, that gets messy. I'll just add these patches to the driver core tree, along with the above linked ones, to keep things simple.

thanks,
greg k-h

maintainer
#17 lore raw
Quoted 2 lines · Greg Kroah-Hartman

Hm, that gets messy. I'll just add these patches to the driver core tree, along with the above linked ones, to keep things simple.

Yeah, that's cleaner, thanks!

maintainer
#18 lore raw
In reply to Greg Kroah-Hartman
Quoted 10 lines · Greg Kroah-Hartman
Quoted 9 lines · Markus Probst

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

Quoted 7 lines
Quoted 5 lines

This series depends on [1].

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

Given there are no objections, I'll go queue this up now, thanks.

You'll need the patches from [1] as well.

Thanks,
Danilo