Skip to contentSkip to conversation

rust: serdev: trivial fixes

PATCH In review Markus Probst 3 participants 12 messages Jul 18 – Jul 19 2 messages not in the archive

Subsystems (3)
lore
Share & tools
lore

Markus Probst

author maintainer
#0 lore raw

v2 cover rust: serdev: trivial fixes

Those are small fixes discovered by the kernel test robot and Gary Guo after the serdev rust abstraction have already been merged.

This includes
- a fix for a documentation typo
- adding missing #[inline] attributes
- a small structual change for timeout

There is no urgency to merge this.

---
Changes in v2:
- resolve Sashiko issues:
- reword small parts of the PrivateData::active documentation
- fix documentation references left to serdev::Timeout.
- Link to v1: https://patch.msgid.link/[email protected]

---
Markus Probst (4):
rust: serdev: fix typo in rustdoc
rust: serdev: mark small functions as #[inline]
rust: serdev: document PrivateData::active
rust: serdev: remove serdev::Timeout

 rust/kernel/serdev.rs | 82 +++++++++++++++++++++++++++------------------------
 1 file changed, 44 insertions(+), 38 deletions(-)

---
base-commit: 25acf039a5dbb40b6865d9392e05be8e713a39f3
change-id: 20260717-rust_serdev_fixes-9baf5f310278

author maintainer
#1 lore raw

PATCH v2 1/4 rust: serdev: fix typo in rustdoc

Fix trivial typo

---
 rust/kernel/serdev.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/serdev.rs +1 -1
index 0ffcef1849d2..47ca57966abf 100644
@@ -515,7 +515,7 @@ pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
     /// [`Device::write_all`].
     ///
     /// Note that any accepted data has only been buffered by the controller. Use
-    /// [ Device::wait_until_sent`] to make sure the controller write buffer has actually been
+    /// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
     /// emptied.
     ///
     /// Returns the number of bytes written (less than `data.len()` if not enough room in the
Signature · 1 line
2.54.0
author maintainer
#2 lore raw

PATCH v2 2/4 rust: serdev: mark small functions as `#[inline]`

In reply to Markus Probst

These methods should be inlined for optimization reasons.

---
 rust/kernel/serdev.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/serdev.rs +8 -0
index 47ca57966abf..79d61c6ceeec 100644
@@ -440,6 +440,7 @@ pub struct Device<Ctx: device::DeviceContext = device::Normal>(
 );
 
 impl<Ctx: device::DeviceContext> Device<Ctx> {
+    #[inline]
     fn as_raw(&self) -> *mut bindings::serdev_device {
         self.0.get()
     }
@@ -451,6 +452,7 @@ impl Device<device::Bound> {
     /// Common baudrates are 115200, 9600, 19200, 57600, 4800.
     ///
     /// Use [`Device::write_flush`] before calling this if you have written data prior to this call.
+    #[inline]
     pub fn set_baudrate(&self, speed: u32) -> Result<(), u32> {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
         let ret = unsafe { bindings::serdev_device_set_baudrate(self.as_raw(), speed) };
@@ -464,6 +466,7 @@ pub fn set_baudrate(&self, speed: u32) -> Result<(), u32> {
     /// Set if flow control should be enabled.
     ///
     /// Use [`Device::write_flush`] before calling this if you have written data prior to this call.
+    #[inline]
     pub fn set_flow_control(&self, enable: bool) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
         unsafe { bindings::serdev_device_set_flow_control(self.as_raw(), enable) };
@@ -472,6 +475,7 @@ pub fn set_flow_control(&self, enable: bool) {
     /// Set parity to use.
     ///
     /// Use [`Device::write_flush`] before calling this if you have written data prior to this call.
+    #[inline]
     pub fn set_parity(&self, parity: Parity) -> Result {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
         to_result(unsafe { bindings::serdev_device_set_parity(self.as_raw(), parity as u32) })
@@ -487,6 +491,7 @@ pub fn set_parity(&self, parity: Parity) -> Result {
     /// Returns the number of bytes written (less than `data.len()` if interrupted).
     /// [`kernel::error::code::ETIMEDOUT`] or [`kernel::error::code::ERESTARTSYS`] if interrupted
     /// before any bytes were written.
+    #[inline]
     pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
         if data.len() > i32::MAX as usize {
             return Err(EINVAL);
@@ -520,6 +525,7 @@ pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
     ///
     /// Returns the number of bytes written (less than `data.len()` if not enough room in the
     /// write buffer).
+    #[inline]
     pub fn write(&self, data: &[u8]) -> Result<u32> {
         if data.len() > i32::MAX as usize {
             return Err(EINVAL);
@@ -539,6 +545,7 @@ pub fn write(&self, data: &[u8]) -> Result<u32> {
     ///
     /// Note that this doesn't guarantee that the data has been transmitted.
     /// Use [`Device::wait_until_sent`] for this purpose.
+    #[inline]
     pub fn write_flush(&self) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
         unsafe { bindings::serdev_device_write_flush(self.as_raw()) };
@@ -547,6 +554,7 @@ pub fn write_flush(&self) {
     /// Wait for the data to be sent.
     ///
     /// After this function, the write buffer of the controller should be empty.
+    #[inline]
     pub fn wait_until_sent(&self, timeout: Timeout) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
         unsafe { bindings::serdev_device_wait_until_sent(self.as_raw(), timeout.into_jiffies()) };
Signature · 1 line
2.54.0
author maintainer
#5 lore raw

PATCH v2 3/4 rust: serdev: document `PrivateData::active`

In reply to Markus Probst

Gary pointed out that it isn't clear for what the mutex is used for, thus adding documentation comments for it.

---
 rust/kernel/serdev.rs | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
rust/kernel/serdev.rs +17 -0
index 79d61c6ceeec..a78dfa6e2c27 100644
@@ -132,6 +132,23 @@ 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>,
 }
Signature · 1 line
2.54.0
author maintainer
#6 lore raw

PATCH v2 4/4 rust: serdev: remove `serdev::Timeout`

In reply to Markus Probst

Instead of relying on its own timeout types, the abstraction should make use of impl Into<Jiffies>.

---
 rust/kernel/serdev.rs | 55 +++++++++++++++++----------------------------------
 1 file changed, 18 insertions(+), 37 deletions(-)
rust/kernel/serdev.rs +18 -37
index a78dfa6e2c27..0fdb37cff15d 100644
@@ -20,11 +20,7 @@
         aref::AlwaysRefCounted,
         Mutex, //
     },
-    time::{
-        msecs_to_jiffies,
-        Jiffies,
-        Msecs, //
-    },
+    time::Jiffies,
     types::{
         Opaque,
         ScopeGuard, //
@@ -35,7 +31,6 @@
     cell::UnsafeCell,
     marker::PhantomData,
     mem::{offset_of, MaybeUninit},
-    num::NonZero,
     ptr::NonNull, //
 };
 
@@ -50,30 +45,6 @@ pub enum 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 {
-    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,
-        }
-    }
-}
-
 /// An adapter for the registration of serial device bus device drivers.
 pub struct Adapter<T: Driver>(T);
 
@@ -379,7 +350,7 @@ macro_rules! module_serdev_device_driver {
 ///         _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)?;
+///         sdev.write_all(b"Hello\n", 0usize)?;
 ///         Ok(MyDriver)
 ///     }
 /// }
@@ -505,11 +476,13 @@ pub fn set_parity(&self, parity: Parity) -> Result {
     /// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
     /// emptied.
     ///
+    /// Use a timeout of 0 to wait indefinitely.
+    ///
     /// Returns the number of bytes written (less than `data.len()` if interrupted).
     /// [`kernel::error::code::ETIMEDOUT`] or [`kernel::error::code::ERESTARTSYS`] if interrupted
-    /// before any bytes were written.
+    /// before any bytes were written. [`kernel::error::code::EINVAL`] if `data.len() > i32::MAX`.
     #[inline]
-    pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
+    pub fn write_all(&self, data: &[u8], timeout: impl Into<Jiffies>) -> Result<usize> {
         if data.len() > i32::MAX as usize {
             return Err(EINVAL);
         }
@@ -523,7 +496,7 @@ pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
                 self.as_raw(),
                 data.as_ptr(),
                 data.len(),
-                timeout.into_jiffies(),
+                isize::try_from(timeout.into()).unwrap_or_default(),
             )
         };
         // CAST: negative return values are guaranteed to be between `-MAX_ERRNO` and `-1`,
@@ -570,11 +543,19 @@ pub fn write_flush(&self) {
 
     /// Wait for the data to be sent.
     ///
-    /// After this function, the write buffer of the controller should be empty.
+    /// After this function, the write buffer of the controller should be empty or the timeout
+    /// elapsed.
+    ///
+    /// Use a timeout of 0 to wait indefinitely.
     #[inline]
-    pub fn wait_until_sent(&self, timeout: Timeout) {
+    pub fn wait_until_sent(&self, timeout: impl Into<Jiffies>) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
-        unsafe { bindings::serdev_device_wait_until_sent(self.as_raw(), timeout.into_jiffies()) };
+        unsafe {
+            bindings::serdev_device_wait_until_sent(
+                self.as_raw(),
+                isize::try_from(timeout.into()).unwrap_or_default(),
+            )
+        };
     }
 }
 
Signature · 1 line
2.54.0
author maintainer
#4 lore raw

Re: [PATCH v2 2/4] rust: serdev: mark small functions as `#[inline]`

In reply to a message not in the archive
Quoted 44 lines · On Sat, 2026-07-18 at 12:54 +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [Low] This problem wasn't introduced by this patch, but the patch incompletely applies the #[inline] attribute, missing several small and forwarding functions in the same module, violating the Rust subsystem guide. --

--- Patch [2]: [PATCH v2 2/4] rust: serdev: mark small functions as #[inline] --- commit 51b61be6e88e2f99505c9aba8afbad7558d43605
Author: Markus Probst <[email protected]>

rust: serdev: mark small functions as #[inline]

This commit adds #[inline] annotations to several methods in the Device struct to allow cross-crate inlining for optimization.

Quoted 4 lines
rust/kernel/serdev.rs +0 -0
index 47ca57966abfe..79d61c6ceeecd 100644

[ ... ]

rust/kernel/serdev.rs pub fn write_flush(&self) { · line 560

Quoted 8 lines
rust/kernel/serdev.rs +1 -0
@@ -547,6 +554,7 @@ pub fn write_flush(&self) {
     /// Wait for the data to be sent.
     ///
     /// After this function, the write buffer of the controller should be empty.
+    #[inline]
     pub fn wait_until_sent(&self, timeout: Timeout) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
         unsafe { bindings::serdev_device_wait_until_sent(self.as_raw(), timeout.into_jiffies()) };

[Severity: Low]
This is a pre-existing issue, but since this commit aims to mark small functions as inline, could we also add the attribute to the other forwarding methods in this module?

The Rust subsystem guidelines mandate that small or forwarding functions in abstractions should be annotated with #[inline].

For example, Timeout::into_jiffies() is quite small:

rust/kernel/serdev.rs:Timeout::into_jiffies()

Quoted 9 lines
    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,
        }
    }

This will be removed in the same patch series.

Quoted 23 lines

And the forwarding trait methods at the end of the file are also missing it:

rust/kernel/serdev.rs:AlwaysRefCounted

    fn inc_ref(&self) {
        self.as_ref().inc_ref();
    }

    unsafe fn dec_ref(obj: NonNull<Self>) {
        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
        unsafe { bindings::serdev_device_put(obj.cast().as_ptr()) }
    }

rust/kernel/serdev.rs:AsRef

    fn as_ref(&self) -> &device::Device<Ctx> {
        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
        // `struct serdev_device`.
        let dev = unsafe { &raw mut (*self.as_raw()).dev };

        // SAFETY: `dev` points to a valid `struct device`.
        unsafe { device::Device::from_raw(dev) }
    }
Quoted 2 lines

Would it make sense to update these functions in a subsequent patch, or include them here to ensure the module fully complies with the guidelines?

Those are trait implements. I haven't seen inline to be used on those.

author maintainer
#8 lore raw

Re: [PATCH v2 4/4] rust: serdev: remove `serdev::Timeout`

In reply to a message not in the archive
Quoted 37 lines · On Sat, 2026-07-18 at 12:57 +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The signature impl Into<Jiffies> fails to enforce time unit safety, as Jiffies and Msecs are type aliases for primitive integers, silently bypassing unit conversion. --

--- Patch [4]: [PATCH v2 4/4] rust: serdev: remove serdev::Timeout --- commit 0f6c93da8f797f31f699e23c7c0c2ff923d0ea30
Author: Markus Probst <[email protected]>

rust: serdev: remove serdev::Timeout

This commit removes the serdev::Timeout enum in favor of accepting timeout values through an impl Into<Jiffies> trait bound. This applies to both the write_all() and wait_until_sent() functions.

Quoted 6 lines
rust/kernel/serdev.rs +0 -0
@@ -505,11 +476,13 @@ pub fn set_parity(&self, parity: Parity) -> Result {
     /// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
     /// emptied.

rust/kernel/serdev.rs pub fn set_parity(&self, parity: Parity) -> Result { · line 485

Quoted 10 lines
rust/kernel/serdev.rs +4 -2
     ///
+    /// Use a timeout of 0 to wait indefinitely.
+    ///
     /// Returns the number of bytes written (less than `data.len()` if interrupted).
     /// [`kernel::error::code::ETIMEDOUT`] or [`kernel::error::code::ERESTARTSYS`] if interrupted
-    /// before any bytes were written.
+    /// before any bytes were written. [`kernel::error::code::EINVAL`] if `data.len() > i32::MAX`.
     #[inline]
-    pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
+    pub fn write_all(&self, data: &[u8], timeout: impl Into<Jiffies>) -> Result<usize> {

[Severity: High]
Since Jiffies is a type alias for usize and Msecs is an alias for u32, does this impl Into<Jiffies> bound silently bypass time unit conversion?

Quoted 4 lines

If a caller passes a value typed as Msecs (u32), it inherently implements Into<usize> and will compile, but the value will be silently zero-extended rather than being correctly converted via msecs_to_jiffies(), resulting in timeouts that are grossly incorrect depending on CONFIG_HZ.

It is intended to be used for Jiffies or Delta only.

Quoted 19 lines

[ ... ]

rust/kernel/serdev.rs pub fn write_flush(&self) { · line 551

Quoted 12 lines
rust/kernel/serdev.rs +5 -2
@@ -570,11 +543,19 @@ pub fn write_flush(&self) {
 
     /// Wait for the data to be sent.
     ///
-    /// After this function, the write buffer of the controller should be empty.
+    /// After this function, the write buffer of the controller should be empty or the timeout
+    /// elapsed.
+    ///
+    /// Use a timeout of 0 to wait indefinitely.
     #[inline]
-    pub fn wait_until_sent(&self, timeout: Timeout) {
+    pub fn wait_until_sent(&self, timeout: impl Into<Jiffies>) {

[Severity: High]
Does this also suffer from the same unit safety bypass issue, since it relies on impl Into<Jiffies>?

#12 lore raw
In reply to Markus Probst
Quoted 7 lines · Markus Probst

Those are small fixes discovered by the kernel test robot and Gary Guo after the serdev rust abstraction have already been merged.

This includes
- a fix for a documentation typo
- adding missing #[inline] attributes
- a small structual change for timeout

Thanks for the quick follow-up, the patches were only in the -testing branch, so I dropped them from the queue.

Can you please integrate those changes into the original patches and resend?

Thanks,
Danilo

reviewer
#9 lore raw

Re: [PATCH v2 4/4] rust: serdev: remove `serdev::Timeout`

In reply to Markus Probst
Quoted 67 lines · Markus Probst

Instead of relying on its own timeout types, the abstraction should make use of impl Into<Jiffies>.

---
 rust/kernel/serdev.rs | 55 +++++++++++++++++----------------------------------
 1 file changed, 18 insertions(+), 37 deletions(-)
rust/kernel/serdev.rs +1 -30
index a78dfa6e2c27..0fdb37cff15d 100644
@@ -20,11 +20,7 @@
         aref::AlwaysRefCounted,
         Mutex, //
     },
-    time::{
-        msecs_to_jiffies,
-        Jiffies,
-        Msecs, //
-    },
+    time::Jiffies,
     types::{
         Opaque,
         ScopeGuard, //
@@ -35,7 +31,6 @@
     cell::UnsafeCell,
     marker::PhantomData,
     mem::{offset_of, MaybeUninit},
-    num::NonZero,
     ptr::NonNull, //
 };
 
@@ -50,30 +45,6 @@ pub enum 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 {
-    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,
-        }
-    }
-}
-
 /// An adapter for the registration of serial device bus device drivers.
 pub struct Adapter<T: Driver>(T);
 

rust/kernel/serdev.rs macro_rules! module_serdev_device_driver { · line 353

Quoted 5 lines
rust/kernel/serdev.rs +1 -1
@@ -379,7 +350,7 @@ macro_rules! module_serdev_device_driver {
 ///         _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)?;
+///         sdev.write_all(b"Hello\n", 0usize)?;

Note that the jiffies type is being converted to a new type (in fact, Into<Jiffies> only make sense with it being a new type.

Best,
Gary

Quoted 51 lines
rust/kernel/serdev.rs +16 -6
 ///         Ok(MyDriver)
 ///     }
 /// }
@@ -505,11 +476,13 @@ pub fn set_parity(&self, parity: Parity) -> Result {
     /// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
     /// emptied.
     ///
+    /// Use a timeout of 0 to wait indefinitely.
+    ///
     /// Returns the number of bytes written (less than `data.len()` if interrupted).
     /// [`kernel::error::code::ETIMEDOUT`] or [`kernel::error::code::ERESTARTSYS`] if interrupted
-    /// before any bytes were written.
+    /// before any bytes were written. [`kernel::error::code::EINVAL`] if `data.len() > i32::MAX`.
     #[inline]
-    pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
+    pub fn write_all(&self, data: &[u8], timeout: impl Into<Jiffies>) -> Result<usize> {
         if data.len() > i32::MAX as usize {
             return Err(EINVAL);
         }
@@ -523,7 +496,7 @@ pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
                 self.as_raw(),
                 data.as_ptr(),
                 data.len(),
-                timeout.into_jiffies(),
+                isize::try_from(timeout.into()).unwrap_or_default(),
             )
         };
         // CAST: negative return values are guaranteed to be between `-MAX_ERRNO` and `-1`,
@@ -570,11 +543,19 @@ pub fn write_flush(&self) {
 
     /// Wait for the data to be sent.
     ///
-    /// After this function, the write buffer of the controller should be empty.
+    /// After this function, the write buffer of the controller should be empty or the timeout
+    /// elapsed.
+    ///
+    /// Use a timeout of 0 to wait indefinitely.
     #[inline]
-    pub fn wait_until_sent(&self, timeout: Timeout) {
+    pub fn wait_until_sent(&self, timeout: impl Into<Jiffies>) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
-        unsafe { bindings::serdev_device_wait_until_sent(self.as_raw(), timeout.into_jiffies()) };
+        unsafe {
+            bindings::serdev_device_wait_until_sent(
+                self.as_raw(),
+                isize::try_from(timeout.into()).unwrap_or_default(),
+            )
+        };
     }
 }
 
author maintainer
#10 lore raw

Re: [PATCH v2 4/4] rust: serdev: remove `serdev::Timeout`

Quoted 67 lines · Gary Guo
Quoted 66 lines · Markus Probst

Instead of relying on its own timeout types, the abstraction should make use of impl Into<Jiffies>.

---
 rust/kernel/serdev.rs | 55 +++++++++++++++++----------------------------------
 1 file changed, 18 insertions(+), 37 deletions(-)
rust/kernel/serdev.rs +1 -30
index a78dfa6e2c27..0fdb37cff15d 100644
@@ -20,11 +20,7 @@
         aref::AlwaysRefCounted,
         Mutex, //
     },
-    time::{
-        msecs_to_jiffies,
-        Jiffies,
-        Msecs, //
-    },
+    time::Jiffies,
     types::{
         Opaque,
         ScopeGuard, //
@@ -35,7 +31,6 @@
     cell::UnsafeCell,
     marker::PhantomData,
     mem::{offset_of, MaybeUninit},
-    num::NonZero,
     ptr::NonNull, //
 };
 
@@ -50,30 +45,6 @@ pub enum 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 {
-    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,
-        }
-    }
-}
-
 /// An adapter for the registration of serial device bus device drivers.
 pub struct Adapter<T: Driver>(T);
 
Quoted 9 lines

rust/kernel/serdev.rs macro_rules! module_serdev_device_driver { · line 353

Quoted 6 lines
rust/kernel/serdev.rs +1 -1
@@ -379,7 +350,7 @@ macro_rules! module_serdev_device_driver {
 ///         _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)?;
+///         sdev.write_all(b"Hello\n", 0usize)?;

Note that the jiffies type is being converted to a new type (in fact, Into<Jiffies> only make sense with it being a new type.

I assume it won't take long for the patch series for the new type to be merged. Currently there is no user for any other timeout than 0 (which corrosponds to MAX_SCHEDULE_TIMEOUT in serdev).

Or should I revert to serdev::Timeout until then?

Thanks
- Markus Probst

Quoted 56 lines

Best,
Gary

Quoted 51 lines
rust/kernel/serdev.rs +16 -6
 ///         Ok(MyDriver)
 ///     }
 /// }
@@ -505,11 +476,13 @@ pub fn set_parity(&self, parity: Parity) -> Result {
     /// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
     /// emptied.
     ///
+    /// Use a timeout of 0 to wait indefinitely.
+    ///
     /// Returns the number of bytes written (less than `data.len()` if interrupted).
     /// [`kernel::error::code::ETIMEDOUT`] or [`kernel::error::code::ERESTARTSYS`] if interrupted
-    /// before any bytes were written.
+    /// before any bytes were written. [`kernel::error::code::EINVAL`] if `data.len() > i32::MAX`.
     #[inline]
-    pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
+    pub fn write_all(&self, data: &[u8], timeout: impl Into<Jiffies>) -> Result<usize> {
         if data.len() > i32::MAX as usize {
             return Err(EINVAL);
         }
@@ -523,7 +496,7 @@ pub fn write_all(&self, data: &[u8], timeout: Timeout) -> Result<usize> {
                 self.as_raw(),
                 data.as_ptr(),
                 data.len(),
-                timeout.into_jiffies(),
+                isize::try_from(timeout.into()).unwrap_or_default(),
             )
         };
         // CAST: negative return values are guaranteed to be between `-MAX_ERRNO` and `-1`,
@@ -570,11 +543,19 @@ pub fn write_flush(&self) {
 
     /// Wait for the data to be sent.
     ///
-    /// After this function, the write buffer of the controller should be empty.
+    /// After this function, the write buffer of the controller should be empty or the timeout
+    /// elapsed.
+    ///
+    /// Use a timeout of 0 to wait indefinitely.
     #[inline]
-    pub fn wait_until_sent(&self, timeout: Timeout) {
+    pub fn wait_until_sent(&self, timeout: impl Into<Jiffies>) {
         // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
-        unsafe { bindings::serdev_device_wait_until_sent(self.as_raw(), timeout.into_jiffies()) };
+        unsafe {
+            bindings::serdev_device_wait_until_sent(
+                self.as_raw(),
+                isize::try_from(timeout.into()).unwrap_or_default(),
+            )
+        };
     }
 }
 
reviewer
#11 lore raw

Re: [PATCH v2 4/4] rust: serdev: remove `serdev::Timeout`

Quoted 77 lines · Markus Probst
Quoted 67 lines · Gary Guo
Quoted 66 lines · Markus Probst

Instead of relying on its own timeout types, the abstraction should make use of impl Into<Jiffies>.

---
 rust/kernel/serdev.rs | 55 +++++++++++++++++----------------------------------
 1 file changed, 18 insertions(+), 37 deletions(-)
rust/kernel/serdev.rs +1 -30
index a78dfa6e2c27..0fdb37cff15d 100644
@@ -20,11 +20,7 @@
         aref::AlwaysRefCounted,
         Mutex, //
     },
-    time::{
-        msecs_to_jiffies,
-        Jiffies,
-        Msecs, //
-    },
+    time::Jiffies,
     types::{
         Opaque,
         ScopeGuard, //
@@ -35,7 +31,6 @@
     cell::UnsafeCell,
     marker::PhantomData,
     mem::{offset_of, MaybeUninit},
-    num::NonZero,
     ptr::NonNull, //
 };
 
@@ -50,30 +45,6 @@ pub enum 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 {
-    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,
-        }
-    }
-}
-
 /// An adapter for the registration of serial device bus device drivers.
 pub struct Adapter<T: Driver>(T);
 
Quoted 9 lines

rust/kernel/serdev.rs macro_rules! module_serdev_device_driver { · line 353

Quoted 6 lines
rust/kernel/serdev.rs +1 -1
@@ -379,7 +350,7 @@ macro_rules! module_serdev_device_driver {
 ///         _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)?;
+///         sdev.write_all(b"Hello\n", 0usize)?;

Note that the jiffies type is being converted to a new type (in fact, Into<Jiffies> only make sense with it being a new type.

Quoted 5 lines

I assume it won't take long for the patch series for the new type to be merged. Currently there is no user for any other timeout than 0 (which corrosponds to MAX_SCHEDULE_TIMEOUT in serdev).

Or should I revert to serdev::Timeout until then?

Timeout uses Jiffies and Msec directly which would be changed too. I think we just need to treat this as conflict and figure out how to handle the conflict.

I think realistic there're some designs to still iron out for the jiffy series, so yours one may land first. The easiest thing is probably just have API that take Jiffies type directly without Into (as having it doesn't bring much value at the moment), and that can be converted by the jiffy series.

Best,
Gary

author maintainer
#13 lore raw
In reply to Danilo Krummrich
Quoted 9 lines · Danilo Krummrich
Quoted 7 lines · Markus Probst

Those are small fixes discovered by the kernel test robot and Gary Guo after the serdev rust abstraction have already been merged.

This includes
- a fix for a documentation typo
- adding missing #[inline] attributes
- a small structual change for timeout

Quoted 7 lines

Thanks for the quick follow-up, the patches were only in the -testing branch, so I dropped them from the queue.

Can you please integrate those changes into the original patches and resend?

Thanks,
Danilo

Hi,

The patches have been integrated into
https://lore.kernel.org/rust-for-linux/[email protected]
.

As they haven't been picked up again yet, I assume you want to wait to allow for comments to be written.

Thanks
- Markus Probst