rust: serdev: trivial fixes
Subsystems (3)
Markus Probst
maintainercover 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.
---
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 | 80 +++++++++++++++++++++++++++------------------------ 1 file changed, 43 insertions(+), 37 deletions(-)
---
base-commit: 25acf039a5dbb40b6865d9392e05be8e713a39f3
change-id: 20260717-rust_serdev_fixes-9baf5f310278
Markus Probst
maintainerPATCH 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
@@ -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
Markus Probst
maintainerPATCH 2/4 rust: serdev: mark small functions as `#[inline]`
In reply to Markus ProbstThese methods should be inlined for optimization reasons.
--- rust/kernel/serdev.rs | 8 ++++++++ 1 file changed, 8 insertions(+)
rust/kernel/serdev.rs +8 -0
@@ -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 (), parityas 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
Markus Probst
maintainerPATCH 3/4 rust: serdev: document `PrivateData::active`
In reply to Markus ProbstGary 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
@@ -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_buf`. +/// +/// If locked, the receive_buf_callback will be blocked on data receival. +/// 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 [`Adapter::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_buf`. 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
A message that is not in the archive (sent off-list or not yet received): [email protected]
Markus Probst
maintainerRe: [PATCH 3/4] rust: serdev: document `PrivateData::active`
Quoted 21 lines · On Sat, 2026-07-18 at 11:46 +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
New issues:
- [Low] Documentation incorrectly references a non-existent trait methodDriver::receive_buf.
- [Low] Intra-doc link from a public struct to a private associated item.
- [Low] Documentation uses the non-standard term 'receival'.Pre-existing issues:
- [High] Use-After-Free and NULL pointer dereference inreceive_buf_callbackduring device probe failure. ----- Patch [3]: [PATCH 3/4] rust: serdev: document
PrivateData::active--- commitd30c5d18f4ae9af1ec1875509c50169875963fd4
Author: Markus Probst <[email protected]>
rust: serdev: documentPrivateData::activeThis commit adds documentation comments for the active mutex in PrivateData, explaining its purpose in blocking data reception during probe and drop.
Quoted 13 lines
rust/kernel/serdev.rs pub struct PrivateData<'bound, T: Driver> { · line 135
Quoted 9 lines
rust/kernel/serdev.rs +1
-0@@ -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_buf`. [Severity: Low]
Is the reference toDriver::receive_bufcorrect here? The Driver trait seems to implement a method named receive rather thanreceive_buf.
True.
Quoted 6 lines
rust/kernel/serdev.rs pub struct PrivateData<'bound, T: Driver> { · line 137
Quoted 3 lines
rust/kernel/serdev.rs +2
-0+/// +/// If locked, the receive_buf_callback will be blocked on data receival. [Severity: Low]
This isn't a bug, but should "receival" be replaced with "reception"?
Shouldn't matter that much, but might be a better fit.
Quoted 8 lines
rust/kernel/serdev.rs pub struct PrivateData<'bound, T: Driver> { · line 140
Quoted 4 lines
rust/kernel/serdev.rs +3
-0+/// 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 [`Adapter::receive_buf_callback`] [Severity: Low]
Can this intra-doc link cause build warnings under -Dwarnings?Adapter::receive_buf_callbackappears to be an implicitly private function.
There is no clippy warning at least.
Quoted 40 lines
rust/kernel/serdev.rs pub struct PrivateData<'bound, T: Driver> { · line 149
Quoted 10 lines
rust/kernel/serdev.rs +9
-0+/// 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_buf`. 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 [Severity: High]
This is a pre-existing issue, but could this sequence lead to a use-after-free or a null pointer dereference ifT::probefails?If
T::probefails, theprobe_callbackexecutes the ScopeGuard cleanup, which callsdrvdata_obtainand frees the PrivateData allocation:rust/kernel/serdev.rs:probe_callback() { ... let private_data = ScopeGuard::new_with_data(private_data, |_| { drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() }); }); // ... to_result(unsafe { bindings::serdev_device_open(sdev.as_raw()) })?; // ... let data = T::probe(sdev, info); // ... }However,
serdev_device_closeis only called inside the Drop implementation of PrivateData:rust/kernel/serdev.rs:PrivateData::drop() { ... if unsafe { *self.open.get() } { unsafe { bindings::serdev_device_close(self.sdev.as_raw()) }; } }
Quoted 7 lines
Because this close happens after the drvdata pointer is cleared, the C serdev subsystem could asynchronously invoke
receive_buf_callbackwhile the memory is being destroyed.Would
receive_buf_callbackthen fetch a null pointer fromdrvdata_borrow, or access the Mutex memory after PrivateData is freed if it was already waiting on the active Mutex?
No, because active is set to false. Then serdev_device_close is called which should synchronize the receive_buf_callback.
Quoted 13 lines
rust/kernel/serdev.rs:receive_buf_callback() { ... let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() }; let active = private_data.active.lock(); ... }Quoted 5 lines
rust/kernel/serdev.rs +2
-0+/// or +/// - the driver data already has been dropped, because it was unbound. #[pin] active: Mutex<bool>, }
Markus Probst
maintainerPATCH 4/4 rust: serdev: remove `serdev::Timeout`
In reply to Markus ProbstInstead of relying on its own timeout types, the abstraction should make use of impl Into<Jiffies>.
--- rust/kernel/serdev.rs | 53 +++++++++++++++++---------------------------------- 1 file changed, 17 insertions(+), 36 deletions(-)
rust/kernel/serdev.rs +17 -36
@@ -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 );
@@ -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