Skip to contentSkip to conversation

rust: serdev: Refactor

PATCH Superseded Markus Probst 3 participants 13 messages Oct 16 – Oct 22

Subsystems (4)

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

v4 cover rust: serdev: Refactor

The following has been changed:
- introduce mutex to C serdev tty port controller
- introduce a new C serdev API to fix race conditions and simplify rust code. Should also be useful on the C side.
- fix race conditions
- simplify rust code

---
Changes in v4:
- fix issues reported by Sashiko:
- add receive_lock to prevent deadlocks
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- add mutex
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- fix missing memory barriers in serdev apis
- use tty_buffer_restart_work instead of tty_flip_buffer_push
- use tty_buffer_flush_work instead of exclusively locking the mutex
- add #[inline] to PrivateData::driver_data
- remove patches for mutable references
- Link to v1: https://patch.msgid.link/[email protected]

---
Markus Probst (4):
tty: serdev: Add mutex lock
tty: serdev: Export functions to pause receive_buf callback calls
rust: serdev: Replace active mutex with receive pause
rust: serdev: Simplify callbacks

 drivers/tty/serdev/core.c           |  54 +++++++++++-
 drivers/tty/serdev/serdev-ttyport.c |  84 ++++++++++++++++--
 include/linux/serdev.h              |   8 +-
 rust/kernel/serdev.rs               | 167 ++++++++++++------------------------
 4 files changed, 188 insertions(+), 125 deletions(-)

---
base-commit: ec8bf8280261294a9b9b4520414b42704c7f9f6b
change-id: 20260905-rust_serdev_probe_refactor-0e2b044354a7

author maintainer
#7 lore raw

PATCH v4 2/4 tty: serdev: Export functions to pause receive_buf callback calls

These functions will be used to simply the serdev rust abstraction. It also contributes to the fixing of 2 race conditions in the serdev rust abstraction.

---
 drivers/tty/serdev/core.c           | 44 ++++++++++++++++++++++++++++++++++++-
 drivers/tty/serdev/serdev-ttyport.c | 38 ++++++++++++++++++++++++++++++++
 include/linux/serdev.h              |  6 +++++
 3 files changed, 87 insertions(+), 1 deletion(-)
drivers/tty/serdev/core.c +43 -1
index 77e8e1d4d2a6..af1470e33620 100644
@@ -191,6 +191,45 @@ void serdev_device_close(struct serdev_device *serdev)
 }
 EXPORT_SYMBOL_GPL(serdev_device_close);
 
+/**
+ * serdev_device_pause_rx() - pause data receive
+ * @serdev:	serdev device
+ *
+ * Pause calls to receive_buf.
+ *
+ * Note that if a call to receive_buf is currently executed, the function will
+ * sleep until it has finished.
+ */
+void serdev_device_pause_rx(struct serdev_device *serdev)
+{
+	struct serdev_controller *ctrl = serdev->ctrl;
+
+	if (!ctrl || !ctrl->ops->pause_rx)
+		return;
+
+	ctrl->ops->pause_rx(ctrl);
+}
+EXPORT_SYMBOL_GPL(serdev_device_pause_rx);
+
+/**
+ * serdev_device_resume_rx() - resume data receive
+ * @serdev:	serdev device
+ *
+ * Resume calls to receive_buf.
+ *
+ * This can be called even if not paused to ensure data receive is active.
+ */
+void serdev_device_resume_rx(struct serdev_device *serdev)
+{
+	struct serdev_controller *ctrl = serdev->ctrl;
+
+	if (!ctrl || !ctrl->ops->resume_rx)
+		return;
+
+	ctrl->ops->resume_rx(ctrl);
+}
+EXPORT_SYMBOL_GPL(serdev_device_resume_rx);
+
 static void devm_serdev_device_close(void *serdev)
 {
 	serdev_device_close(serdev);
@@ -402,6 +441,7 @@ EXPORT_SYMBOL_GPL(serdev_device_break_ctl);
 static int serdev_drv_probe(struct device *dev)
 {
 	const struct serdev_device_driver *sdrv = to_serdev_device_driver(dev->driver);
+	struct serdev_device *sdev = to_serdev_device(dev);
 	int ret;
 
 	ret = dev_pm_domain_attach(dev, PD_FLAG_ATTACH_POWER_ON |
@@ -409,7 +449,9 @@ static int serdev_drv_probe(struct device *dev)
 	if (ret)
 		return ret;
 
-	return sdrv->probe(to_serdev_device(dev));
+	serdev_device_resume_rx(sdev);
+
+	return sdrv->probe(sdev);
 }
 
 static void serdev_drv_remove(struct device *dev)
drivers/tty/serdev/serdev-ttyport.c +38 -0
index 125a17a0bea5..e164ee7edc12 100644
@@ -7,8 +7,10 @@
 #include <linux/tty.h>
 #include <linux/tty_driver.h>
 #include <linux/poll.h>
+#include "../tty.h"
 
 #define SERPORT_ACTIVE		1
+#define SERPORT_PAUSE_RX	2
 
 struct serport {
 	struct tty_port *port;
@@ -36,6 +38,9 @@ static size_t ttyport_receive_buf(struct tty_port *port, const u8 *cp,
 	if (!test_bit(SERPORT_ACTIVE, &serport->flags))
 		return 0;
 
+	if (test_bit(SERPORT_PAUSE_RX, &serport->flags))
+		return 0;
+
 	ret = serdev_controller_receive_buf(ctrl, cp, count);
 
 	dev_WARN_ONCE(&ctrl->dev, ret > count,
@@ -185,6 +190,37 @@ static bool ttyport_close(struct serdev_controller *ctrl)
 	return true;
 }
 
+static void ttyport_pause_rx(struct serdev_controller *ctrl)
+{
+	struct serport *serport = serdev_controller_get_drvdata(ctrl);
+	struct tty_struct *tty = serport->tty;
+
+	guard(mutex)(&serport->lock);
+
+	scoped_guard(mutex, &serport->receive_lock)
+		set_bit(SERPORT_PAUSE_RX, &serport->flags);
+
+	if (test_bit(SERPORT_ACTIVE, &serport->flags))
+		tty_buffer_cancel_work(tty->port);
+}
+
+static void ttyport_resume_rx(struct serdev_controller *ctrl)
+{
+	struct serport *serport = serdev_controller_get_drvdata(ctrl);
+	struct tty_struct *tty = serport->tty;
+
+	guard(mutex)(&serport->lock);
+
+	if (!test_bit(SERPORT_PAUSE_RX, &serport->flags))
+		return;
+
+	scoped_guard(mutex, &serport->receive_lock)
+		clear_bit(SERPORT_PAUSE_RX, &serport->flags);
+
+	if (test_bit(SERPORT_ACTIVE, &serport->flags))
+		tty_buffer_restart_work(tty->port);
+}
+
 static unsigned int ttyport_set_baudrate(struct serdev_controller *ctrl, unsigned int speed)
 {
 	struct serport *serport = serdev_controller_get_drvdata(ctrl);
@@ -289,6 +325,8 @@ static const struct serdev_controller_ops ctrl_ops = {
 	.get_tiocm = ttyport_get_tiocm,
 	.set_tiocm = ttyport_set_tiocm,
 	.break_ctl = ttyport_break_ctl,
+	.pause_rx = ttyport_pause_rx,
+	.resume_rx = ttyport_resume_rx,
 };
 
 struct device *serdev_tty_port_register(struct tty_port *port,
include/linux/serdev.h +6 -0
index 0f4e81c0950d..02773554e759 100644
@@ -89,6 +89,8 @@ struct serdev_controller_ops {
 	int (*get_tiocm)(struct serdev_controller *);
 	int (*set_tiocm)(struct serdev_controller *, unsigned int, unsigned int);
 	int (*break_ctl)(struct serdev_controller *ctrl, unsigned int break_state);
+	void (*pause_rx)(struct serdev_controller *ctrl);
+	void (*resume_rx)(struct serdev_controller *ctrl);
 };
 
 /**
@@ -194,6 +196,8 @@ static inline size_t serdev_controller_receive_buf(struct serdev_controller *ctr
 int serdev_device_open(struct serdev_device *);
 void serdev_device_close(struct serdev_device *);
 int devm_serdev_device_open(struct device *, struct serdev_device *);
+void serdev_device_pause_rx(struct serdev_device *serdev);
+void serdev_device_resume_rx(struct serdev_device *serdev);
 unsigned int serdev_device_set_baudrate(struct serdev_device *, unsigned int);
 void serdev_device_set_flow_control(struct serdev_device *, bool);
 int serdev_device_write_buf(struct serdev_device *, const u8 *, size_t);
@@ -233,6 +237,8 @@ static inline int serdev_device_open(struct serdev_device *sdev)
 	return -ENODEV;
 }
 static inline void serdev_device_close(struct serdev_device *sdev) {}
+static inline void serdev_device_pause_rx(struct serdev_device *serdev) {}
+static inline void serdev_device_resume_rx(struct serdev_device *serdev) {}
 static inline unsigned int serdev_device_set_baudrate(struct serdev_device *sdev, unsigned int baudrate)
 {
 	return 0;
Signature · 1 line
2.55.0
author maintainer
#1 lore raw

PATCH v4 1/4 tty: serdev: Add mutex lock

In reply to Markus Probst

Besides more predictable behaviour, this allows for several hardened behaviour changes:

Return -EALREADY in serdev_device_open if the device is already open instead of causing undefined behaviour.

Allow calling serdev_device_close, even if the device is already closed instead of causing a null pointer dereference.

If the device is left open by the driver after remove, close it and warn instead of leaving it in a invalid state.

---
 drivers/tty/serdev/core.c           | 10 +++++---
 drivers/tty/serdev/serdev-ttyport.c | 46 +++++++++++++++++++++++++++++++------
 include/linux/serdev.h              |  2 +-
 3 files changed, 47 insertions(+), 11 deletions(-)
drivers/tty/serdev/core.c +7 -3
index 7500efcdfc21..77e8e1d4d2a6 100644
@@ -142,6 +142,11 @@ void serdev_device_remove(struct serdev_device *serdev)
 	struct serdev_controller *ctrl = serdev->ctrl;
 
 	device_unregister(&serdev->dev);
+
+	/* Warn if driver did not close the serial device. */
+	if (ctrl->ops->close && WARN_ON(ctrl->ops->close(ctrl)))
+		pm_runtime_put(&ctrl->dev);
+
 	ctrl->serdev = NULL;
 }
 EXPORT_SYMBOL_GPL(serdev_device_remove);
@@ -181,9 +186,8 @@ void serdev_device_close(struct serdev_device *serdev)
 	if (!ctrl || !ctrl->ops->close)
 		return;
 
-	pm_runtime_put(&ctrl->dev);
-
-	ctrl->ops->close(ctrl);
+	if (ctrl->ops->close(ctrl))
+		pm_runtime_put(&ctrl->dev);
 }
 EXPORT_SYMBOL_GPL(serdev_device_close);
 
drivers/tty/serdev/serdev-ttyport.c +39 -7

102 lines not on this page · raw message

include/linux/serdev.h +1 -1
index b6c3d957ec15..0f4e81c0950d 100644
@@ -81,7 +81,7 @@ struct serdev_controller_ops {
 	ssize_t (*write_buf)(struct serdev_controller *, const u8 *, size_t);
 	void (*write_flush)(struct serdev_controller *);
 	int (*open)(struct serdev_controller *);
-	void (*close)(struct serdev_controller *);
+	bool (*close)(struct serdev_controller *);
 	void (*set_flow_control)(struct serdev_controller *, bool);
 	int (*set_parity)(struct serdev_controller *, enum serdev_parity);
 	unsigned int (*set_baudrate)(struct serdev_controller *, unsigned int);
Signature · 1 line
2.55.0
author maintainer
#9 lore raw

PATCH v4 3/4 rust: serdev: Replace `active` mutex with receive pause

In reply to Markus Probst

There are currently 2 race conditions:
- in probe if Driver::probe returns Err
- in unbind
. In those cases the driver data will be set to NULL before the serdev device was closed. If data is received while the driver data is dropped, the receive_buf_callback might try to access the active mutex on a null pointer.

Removing the need for receive_buf_callback to lock the active mutex fixes these.

---
 rust/kernel/serdev.rs | 60 ++++++++++++---------------------------------------
 1 file changed, 14 insertions(+), 46 deletions(-)
rust/kernel/serdev.rs +14 -46
index 17ca504b7f8d..c16d6593a8d2 100644
@@ -13,13 +13,9 @@
         to_result,
         VTABLE_DEFAULT_ERROR, //
     },
-    new_mutex,
     of,
     prelude::*,
-    sync::{
-        aref::AlwaysRefCounted,
-        Mutex, //
-    },
+    sync::aref::AlwaysRefCounted,
     time::Jiffies,
     types::{
         Opaque,
@@ -103,40 +99,11 @@ pub struct PrivateData<'bound, T: Driver> {
     #[pin]
     driver: UnsafeCell<MaybeUninit<T::Data<'bound>>>,
     open: UnsafeCell<bool>,
-    /// Whether `receive_buf_callback` is allowed to call `Driver::receive`.
-    ///
-    /// If locked, the receive_buf_callback will be blocked on data reception.
-    /// This is the case while the driver is being probed or while [`PrivateData`] is being dropped.
-    /// This is necessary, because we need to open the serdev device before the driver has been
-    /// probed in order to allow it to be configured, which allows `receive_buf_callback` to be
-    /// called. Thus we need to block data until probe completes and the driver data becomes
-    /// initialized.
-    ///
-    /// If unlocked and true, the receive_buf_callback will forward the data to
-    /// `Driver::receive`. This is the normal state of operation.
-    ///
-    /// If unlocked and false, the receive_buf_callback will throw away the data.
-    /// This is only the case, if the serdev device is open and
-    /// - the driver returned an error in probe
-    /// or
-    /// - the driver data already has been dropped, because it was unbound.
-    #[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
@@ -170,7 +137,6 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
                 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>>() };
@@ -178,11 +144,12 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
                 // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
                 drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
             });
-            let mut active = private_data.active.lock();
-
             // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
             unsafe { bindings::serdev_device_set_client_ops(sdev.as_raw(), Self::OPS) };
 
+            // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+            unsafe { bindings::serdev_device_pause_rx(sdev.as_raw()) };
+
             // 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()) })?;
@@ -199,12 +166,12 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
             // - `private_data.driver` is pinned.
             let result = unsafe { pin_init::raw_try_init(driver.as_mut_ptr(), data) };
 
-            *active = result.is_ok();
-
-            drop(active);
-
             result.map(|()| {
                 private_data.dismiss();
+
+                // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+                unsafe { bindings::serdev_device_resume_rx(sdev.as_raw()) };
+
                 0
             })
         })
@@ -231,6 +198,12 @@ extern "C" fn remove_callback(sdev: *mut bindings::serdev_device) {
         let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
 
         T::unbind(sdev, data_pinned);
+
+        // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
+        unsafe { bindings::serdev_device_pause_rx(sdev.as_raw()) };
+
+        // SAFETY: We already established that `data` is guaranteed to be initialized.
+        unsafe { data.assume_init_drop() };
     }
 
     extern "C" fn receive_buf_callback(
@@ -248,11 +221,6 @@ extern "C" fn receive_buf_callback(
         // `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() };
Signature · 1 line
2.55.0
author maintainer
#11 lore raw

PATCH v4 4/4 rust: serdev: Simplify callbacks

In reply to Markus Probst

Initialize the driver's private data directly on PrivateData.

Introduce OpenGuard for resource cleanup.

---
 rust/kernel/serdev.rs | 131 ++++++++++++++++++++------------------------------
 1 file changed, 52 insertions(+), 79 deletions(-)
rust/kernel/serdev.rs +52 -79
index c16d6593a8d2..3f9165e16776 100644
@@ -17,16 +17,12 @@
     prelude::*,
     sync::aref::AlwaysRefCounted,
     time::Jiffies,
-    types::{
-        Opaque,
-        ScopeGuard, //
-    }, //
+    types::Opaque, //
 };
 
 use core::{
-    cell::UnsafeCell,
     marker::PhantomData,
-    mem::{offset_of, MaybeUninit},
+    mem::offset_of,
     ptr::NonNull, //
 };
 
@@ -92,24 +88,36 @@ unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {
     }
 }
 
+struct OpenGuard<'bound> {
+    sdev: &'bound Device<device::Bound>,
+}
+
+impl Drop for OpenGuard<'_> {
+    fn drop(&mut self) {
+        // SAFETY:
+        // - `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+        //   `struct serdev_device`.
+        // - The existence of self proves that the device is open.
+        unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+    }
+}
+
 #[doc(hidden)]
-#[pin_data(PinnedDrop)]
+#[pin_data]
 pub struct PrivateData<'bound, T: Driver> {
-    sdev: &'bound Device<device::Bound>,
     #[pin]
-    driver: UnsafeCell<MaybeUninit<T::Data<'bound>>>,
-    open: UnsafeCell<bool>,
+    driver: T::Data<'bound>,
+    open: OpenGuard<'bound>,
 }
 
-#[pinned_drop]
-impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
-    fn drop(self: Pin<&mut Self>) {
-        // 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<'bound, T: Driver> PrivateData<'bound, T> {
+    #[inline]
+    fn driver_data(self: Pin<&Self>) -> Pin<&T::Data<'bound>> {
+        // SAFETY: We treat the result as pinned.
+        let inner = unsafe { Pin::into_inner_unchecked(self) };
+
+        // SAFETY: `self.driver` is pinned.
+        unsafe { Pin::new_unchecked(&inner.driver) }
     }
 }
 
@@ -134,46 +142,30 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
 
         from_result(|| {
             sdev.as_ref().set_drvdata(try_pin_init!(PrivateData::<T> {
-                sdev: &**sdev,
-                driver: MaybeUninit::<T::Data<'_>>::zeroed().into(),
-                open: false.into(),
+                open: {
+                    // SAFETY:
+                    // - `sdev.as_raw()` is guaranteed to be a valid pointer to
+                    //   `serdev_device`.
+                    // - It is safe to call before open.
+                    unsafe { bindings::serdev_device_set_client_ops(sdev.as_raw(), Self::OPS) };
+
+                    // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to
+                    // `serdev_device`.
+                    unsafe { bindings::serdev_device_pause_rx(sdev.as_raw()) };
+
+                    // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to
+                    // `serdev_device`.
+                    to_result(unsafe { bindings::serdev_device_open(sdev.as_raw()) })?;
+
+                    OpenGuard { sdev }
+                },
+                driver <- T::probe(sdev, info),
             }))?;
-            // 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>>() });
-            });
-            // 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: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
-            unsafe { bindings::serdev_device_pause_rx(sdev.as_raw()) };
-
-            // 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);
+            unsafe { bindings::serdev_device_resume_rx(sdev.as_raw()) };
 
-            // 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 { pin_init::raw_try_init(driver.as_mut_ptr(), data) };
-
-            result.map(|()| {
-                private_data.dismiss();
-
-                // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
-                unsafe { bindings::serdev_device_resume_rx(sdev.as_raw()) };
-
-                0
-            })
+            Ok(0)
         })
     }
 
@@ -189,21 +181,10 @@ extern "C" fn remove_callback(sdev: *mut bindings::serdev_device) {
         // 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);
+        T::unbind(sdev, private_data.driver_data());
 
         // SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
         unsafe { bindings::serdev_device_pause_rx(sdev.as_raw()) };
-
-        // SAFETY: We already established that `data` is guaranteed to be initialized.
-        unsafe { data.assume_init_drop() };
     }
 
     extern "C" fn receive_buf_callback(
@@ -211,6 +192,9 @@ extern "C" fn receive_buf_callback(
         buf: *const u8,
         length: usize,
     ) -> usize {
+        // SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
+        let buf = unsafe { core::slice::from_raw_parts(buf, length) };
+
         // SAFETY: The serial device bus only ever calls the receive buf callback with a valid
         // pointer to a `struct serdev_device`.
         //
@@ -222,18 +206,7 @@ extern "C" fn receive_buf_callback(
         // 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.
-        // - `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)
+        T::receive(sdev, private_data.driver_data(), buf)
     }
 }
 
Signature · 1 line
2.55.0
#10 lore raw

Re: [PATCH v4 3/4] rust: serdev: Replace `active` mutex with receive pause

In reply to Markus Probst
Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

There are currently 2 race conditions:
- in probe if Driver::probe returns Err
- in unbind
. In those cases the driver data will be set to NULL before the serdev device was closed. If data is received while the driver data is dropped, the receive_buf_callback might try to access the active mutex on a null pointer.

Quoted 8 lines

Removing the need for receive_buf_callback to lock the active mutex fixes these.

Sashiko has reviewed this patch and found no issues.

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

Re: [PATCH v4 2/4] tty: serdev: Export functions to pause receive_buf callback calls

In reply to Markus Probst
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] tty: NULL pointer dereference / UAF in ttyport_pause_rx and ttyport_resume_rx due to TOCTOU --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] tty: NULL pointer dereference / UAF in ttyport_pause_rx and ttyport_resume_rx due to TOCTOU --

commit 7862c81055f41fa0e8cc37f91200a9bcccf35960
Author: Markus Probst <[email protected]>

tty: serdev: Export functions to pause receive_buf callback calls

These functions will be used to simply the serdev rust abstraction. It also contributes to the fixing of 2 race conditions in the serdev rust abstraction.

Quoted 4 lines
drivers/tty/serdev/serdev-ttyport.c +0 -0
index 125a17a0bea50..e164ee7edc121 100644

[ ... ]

drivers/tty/serdev/serdev-ttyport.c static bool ttyport_close(struct serdev_controller *ctrl) · line 198

Quoted 10 lines
drivers/tty/serdev/serdev-ttyport.c +6 -0
@@ -185,6 +190,37 @@ static bool ttyport_close(struct serdev_controller *ctrl)
 	return true;
 }
 
+static void ttyport_pause_rx(struct serdev_controller *ctrl)
+{
+	struct serport *serport = serdev_controller_get_drvdata(ctrl);
+	struct tty_struct *tty = serport->tty;
+
+	guard(mutex)(&serport->lock);

[Severity: High]
Does this code have a race condition since the local pointer tty is assigned from serport->tty before the serport->lock is acquired?

This lock protects the lifecycle of the tty structure and the SERPORT_ACTIVE flag, which are modified concurrently by ttyport_open() and ttyport_close().

If a concurrent thread calls ttyport_open() or if the port transitions states asynchronously, it will allocate a new tty_struct, set serport->tty, and set SERPORT_ACTIVE to true.

drivers/tty/serdev/serdev-ttyport.c static bool ttyport_close(struct serdev_controller *ctrl) · line 204

Quoted 6 lines
drivers/tty/serdev/serdev-ttyport.c +6 -0
+
+	scoped_guard(mutex, &serport->receive_lock)
+		set_bit(SERPORT_PAUSE_RX, &serport->flags);
+
+	if (test_bit(SERPORT_ACTIVE, &serport->flags))
+		tty_buffer_cancel_work(tty->port);

Because tty was captured outside the lock, could it remain NULL if previously closed or point to a freed structure?

If the ttyport_pause_rx() thread then acquires the lock and sees that SERPORT_ACTIVE is true, will this result in an immediate NULL pointer dereference or use-after-free when accessing tty->port?

Should the assignment of the tty pointer be moved inside the critical section?

drivers/tty/serdev/serdev-ttyport.c static bool ttyport_close(struct serdev_controller *ctrl) · line 212

Quoted 8 lines
drivers/tty/serdev/serdev-ttyport.c +8 -0
+}
+
+static void ttyport_resume_rx(struct serdev_controller *ctrl)
+{
+	struct serport *serport = serdev_controller_get_drvdata(ctrl);
+	struct tty_struct *tty = serport->tty;
+
+	guard(mutex)(&serport->lock);

[Severity: High]
Does the identical vulnerability exist in the resume path where tty is captured outside the lock?

Quoted 10 lines
drivers/tty/serdev/serdev-ttyport.c +10 -0
+
+	if (!test_bit(SERPORT_PAUSE_RX, &serport->flags))
+		return;
+
+	scoped_guard(mutex, &serport->receive_lock)
+		clear_bit(SERPORT_PAUSE_RX, &serport->flags);
+
+	if (test_bit(SERPORT_ACTIVE, &serport->flags))
+		tty_buffer_restart_work(tty->port);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#2 lore raw

Re: [PATCH v4 1/4] tty: serdev: Add mutex lock

In reply to Markus Probst
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] pm: async pm_runtime_put() in remove path cancelled by pm_runtime_disable() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] pm: async pm_runtime_put() in remove path cancelled by pm_runtime_disable() --

commit c4731a25fb19c22b675757b565d963b9ad0190e8
Author: Markus Probst <[email protected]>

tty: serdev: Add mutex lock

Besides more predictable behaviour, this allows for several hardened behaviour changes. If the device is left open by the driver after remove, close it and warn instead of leaving it in an invalid state.

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 148

Quoted 12 lines
drivers/tty/serdev/core.c +4 -0
index 7500efcdfc218..77e8e1d4d2a66 100644
@@ -142,6 +142,11 @@ void serdev_device_remove(struct serdev_device *serdev)
 	struct serdev_controller *ctrl = serdev->ctrl;
 
 	device_unregister(&serdev->dev);
+
+	/* Warn if driver did not close the serial device. */
+	if (ctrl->ops->close && WARN_ON(ctrl->ops->close(ctrl)))
+		pm_runtime_put(&ctrl->dev);

[Severity: Medium]
When this path is reached during controller teardown, will the pending asynchronous suspend work be cancelled?

In serdev_controller_remove(), device_for_each_child() synchronously invokes the removal, and then immediately calls pm_runtime_disable(&ctrl->dev):

serdev_controller_remove() {
	...
	device_for_each_child(&ctrl->dev, NULL, serdev_remove_device);
	pm_runtime_disable(&ctrl->dev);
	device_del(&ctrl->dev);
}

Since pm_runtime_disable() cancels pending asynchronous idle and suspend work, calling pm_runtime_put() here instead of pm_runtime_put_sync() can prevent the hardware from actually suspending, leaving the controller powered on indefinitely.

Could pm_runtime_put_sync() be used here instead to ensure the device is properly suspended before pm_runtime_disable() is called?

Quoted 4 lines
drivers/tty/serdev/core.c +1 -0
+
 	ctrl->serdev = NULL;
 }
 EXPORT_SYMBOL_GPL(serdev_device_remove);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#12 lore raw

Re: [PATCH v4 4/4] rust: serdev: Simplify callbacks

In reply to Markus Probst
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] rust: missing #[inline] on OpenGuard::drop --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] rust: missing #[inline] on OpenGuard::drop
--

commit 3744d6179fccd8a1197885b1019f91d6e5f289b7
Author: Markus Probst <[email protected]>

rust: serdev: Simplify callbacks

This commit initializes the driver's private data directly on PrivateData and introduces OpenGuard for resource cleanup.

Quoted 4 lines
rust/kernel/serdev.rs +0 -0
index c16d6593a8d2d..3f9165e167764 100644

[ ... ]

rust/kernel/serdev.rs unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) { · line 96

Quoted 10 lines
rust/kernel/serdev.rs +6 -0
@@ -92,24 +88,36 @@ unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {
     }
 }
 
+struct OpenGuard<'bound> {
+    sdev: &'bound Device<device::Bound>,
+}
+
+impl Drop for OpenGuard<'_> {
+    fn drop(&mut self) {

[Severity: Low]
This isn't a bug, but should the drop method on OpenGuard be annotated with #[inline]?

The Rust subsystem guidelines recommend using #[inline] on small functions in abstractions that forward directly to a C binding call, such as the call to bindings::serdev_device_close() here.

Quoted 7 lines
rust/kernel/serdev.rs +7 -0
+        // SAFETY:
+        // - `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
+        //   `struct serdev_device`.
+        // - The existence of self proves that the device is open.
+        unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
+    }
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#3 lore raw

Re: [PATCH v4 1/4] tty: serdev: Add mutex lock

In reply to Markus Probst
Quoted 24 lines · Markus Probst

Besides more predictable behaviour, this allows for several hardened behaviour changes:

Return -EALREADY in serdev_device_open if the device is already open instead of causing undefined behaviour.

Allow calling serdev_device_close, even if the device is already closed instead of causing a null pointer dereference.

If the device is left open by the driver after remove, close it and warn instead of leaving it in a invalid state.

---
 drivers/tty/serdev/core.c           | 10 +++++---
 drivers/tty/serdev/serdev-ttyport.c | 46 +++++++++++++++++++++++++++++++------
 include/linux/serdev.h              |  2 +-
 3 files changed, 47 insertions(+), 11 deletions(-)
drivers/tty/serdev/core.c +0 -0
index 7500efcdfc21..77e8e1d4d2a6 100644

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 147

Quoted 6 lines
drivers/tty/serdev/core.c +3 -0
@@ -142,6 +142,11 @@ void serdev_device_remove(struct serdev_device *serdev)
 	struct serdev_controller *ctrl = serdev->ctrl;
 
 	device_unregister(&serdev->dev);
+
+	/* Warn if driver did not close the serial device. */
+	if (ctrl->ops->close && WARN_ON(ctrl->ops->close(ctrl)))

I understand the want to give a big "splat" if this happens, but if it does somehow, you just crashed the box due to panic-on-warn, which will result in a CVE being given :)

So, if this ever can happen, we should recover like you do:

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 148

Quoted 1 line
drivers/tty/serdev/core.c +1 -0
+		pm_runtime_put(&ctrl->dev);

And you can warn about it in the kernel log, but just not with WARN_ON() please.

thanks,

greg k-h

#5 lore raw

Re: [PATCH v4 1/4] tty: serdev: Add mutex lock

In reply to Markus Probst
Quoted 24 lines · Markus Probst

Besides more predictable behaviour, this allows for several hardened behaviour changes:

Return -EALREADY in serdev_device_open if the device is already open instead of causing undefined behaviour.

Allow calling serdev_device_close, even if the device is already closed instead of causing a null pointer dereference.

If the device is left open by the driver after remove, close it and warn instead of leaving it in a invalid state.

---
 drivers/tty/serdev/core.c           | 10 +++++---
 drivers/tty/serdev/serdev-ttyport.c | 46 +++++++++++++++++++++++++++++++------
 include/linux/serdev.h              |  2 +-
 3 files changed, 47 insertions(+), 11 deletions(-)
drivers/tty/serdev/core.c +0 -0
index 7500efcdfc21..77e8e1d4d2a6 100644

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 148

Quoted 7 lines
drivers/tty/serdev/core.c +4 -0
@@ -142,6 +142,11 @@ void serdev_device_remove(struct serdev_device *serdev)
 	struct serdev_controller *ctrl = serdev->ctrl;
 
 	device_unregister(&serdev->dev);
+
+	/* Warn if driver did not close the serial device. */
+	if (ctrl->ops->close && WARN_ON(ctrl->ops->close(ctrl)))
+		pm_runtime_put(&ctrl->dev);

Wait, how can close() ever fail? That should be something that just can't happen right?

thanks,

greg k-h

author maintainer
#6 lore raw

Re: [PATCH v4 1/4] tty: serdev: Add mutex lock

Quoted 27 lines · Greg Kroah-Hartman
Quoted 26 lines · Markus Probst

Besides more predictable behaviour, this allows for several hardened behaviour changes:

Return -EALREADY in serdev_device_open if the device is already open instead of causing undefined behaviour.

Allow calling serdev_device_close, even if the device is already closed instead of causing a null pointer dereference.

If the device is left open by the driver after remove, close it and warn instead of leaving it in a invalid state.

---
 drivers/tty/serdev/core.c           | 10 +++++---
 drivers/tty/serdev/serdev-ttyport.c | 46 +++++++++++++++++++++++++++++++------
 include/linux/serdev.h              |  2 +-
 3 files changed, 47 insertions(+), 11 deletions(-)
drivers/tty/serdev/core.c +0 -0
index 7500efcdfc21..77e8e1d4d2a6 100644
@@ -142,6 +142,11 @@ void serdev_device_remove(struct serdev_device *serdev)
 	struct serdev_controller *ctrl = serdev->ctrl;
 
Quoted 8 lines

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 148

Quoted 5 lines
drivers/tty/serdev/core.c +4 -0
 	device_unregister(&serdev->dev);
+
+	/* Warn if driver did not close the serial device. */
+	if (ctrl->ops->close && WARN_ON(ctrl->ops->close(ctrl)))
+		pm_runtime_put(&ctrl->dev);

Wait, how can close() ever fail? That should be something that just can't happen right?

It can't fail and its not a fail. It returns true if the device was closed, false if already closed. Currently the driver is responsible for closing the device, so this should always be false.

The WARN_ON was intended if the driver did not close the device and close it.

Thats the "If the device is left open by the driver after remove, close it and warn instead of leaving it in a invalid state." part of the commit msg.

But I see that a panic (panic-on-warn) is definitely not appropriate here.

Thanks
- Markus Probst

Quoted 4 lines

thanks,

greg k-h

author maintainer
#4 lore raw

Re: [PATCH v4 1/4] tty: serdev: Add mutex lock

In reply to Greg Kroah-Hartman
Quoted 36 lines · Greg Kroah-Hartman
Quoted 24 lines · Markus Probst

Besides more predictable behaviour, this allows for several hardened behaviour changes:

Return -EALREADY in serdev_device_open if the device is already open instead of causing undefined behaviour.

Allow calling serdev_device_close, even if the device is already closed instead of causing a null pointer dereference.

If the device is left open by the driver after remove, close it and warn instead of leaving it in a invalid state.

---
 drivers/tty/serdev/core.c           | 10 +++++---
 drivers/tty/serdev/serdev-ttyport.c | 46 +++++++++++++++++++++++++++++++------
 include/linux/serdev.h              |  2 +-
 3 files changed, 47 insertions(+), 11 deletions(-)
drivers/tty/serdev/core.c +0 -0
index 7500efcdfc21..77e8e1d4d2a6 100644

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 147

Quoted 6 lines
drivers/tty/serdev/core.c +3 -0
@@ -142,6 +142,11 @@ void serdev_device_remove(struct serdev_device *serdev)
 	struct serdev_controller *ctrl = serdev->ctrl;
 
 	device_unregister(&serdev->dev);
+
+	/* Warn if driver did not close the serial device. */
+	if (ctrl->ops->close && WARN_ON(ctrl->ops->close(ctrl)))

I understand the want to give a big "splat" if this happens, but if it does somehow, you just crashed the box due to panic-on-warn, which will result in a CVE being given :)

Quoted 6 lines

So, if this ever can happen, we should recover like you do:

drivers/tty/serdev/core.c void serdev_device_remove(struct serdev_device *serdev) · line 148

Quoted 1 line
drivers/tty/serdev/core.c +1 -0
+		pm_runtime_put(&ctrl->dev);

And you can warn about it in the kernel log, but just not with WARN_ON() please.

To be honest, I forgot about this review and sent v5 without taking it into account.

Anyway, I looked into documentation.

"WARN*() is intended for unexpected, this-should-never-happen situations. [...] However, the existence of panic_on_warn users is not a valid reason to avoid the judicious use WARN*()." [1]

I think this is a valid case.

It is an event that should never happen, and it might cause a use- after-free vulnerability on data reception.

Thanks
- Markus Probst

[1] https://docs.kernel.org/process/coding-style.html

Quoted 4 lines

thanks,

greg k-h