rust: leds: add led classdev abstractions
v15 cover rust: leds: add led classdev abstractions
This patch series has previously been contained in
https://lore.kernel.org/rust-for-linux/[email protected]/T/#t
which added a rust written led driver for a microcontroller via i2c.
As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
The following changes were made:
* add basic led classdev abstractions to register and unregister leds
* add basic led classdev abstractions to register and unregister multicolor leds
Changes since v14:
* fix issues reported by Sashiko bot:
* add missing inlines
* add missing Sync trait bound
* fix vertical import layout for public export of private types
* fix potential memory leak, if a multicolor led device with over u32::MAX subleds is registered
* remove default_trigger option
* fix missing CAST doc
Changes since v13:
* rebased onto v7.1-rc1
Changes since v12:
* add led::DeviceBuilder::name() and `DeviceBuilderState'
* add led::Color::as_c_str
Changes since v11:
* use led::DeviceBuilder instead of led::InitData
* use static_assert instead of const { assert!(...) }
* restructured patches to avoid moving led::Device from rust/kernel/led.rs to rust/kernel/led/normal.rs in the 2. patch
Changes since v10:
* allow in-place initialization of LedOps
* run rustfmt for code inside try_pin_init!
Changes since v9:
* add missing periods in documentation
* duplicate led::Device and led::Adapter instead of using a complex trait
* fix imports not using prelude
* adapt to CStr change
* documented led::Color::Multi and led::Color::Rgb
Changes since v8:
* accept Option<ARef<Fwnode>> in led::InitData::fwnode()
* make functions in MultiColorSubLed const
* drop the "rust: Add trait to convert a device reference to a bus device reference" patch, as it has been picked into driver-core
Changes since v7:
* adjusted import style
* added classdev parameter to callback functions in LedOps
* implement led::Color
* extend led::InitData with
- initial_brightness
- default_trigger
- default_color
* split generic and normal led classdev abstractions up (see patch 3/4)
* add multicolor led class device abstractions (see patch 4/4)
* added MAINTAINERS entry
Changes since v6:
* fixed typos
* improved documentation
Changes since v5:
* rename IntoBusDevice trait into AsBusDevice
* fix documentation about LedOps::BLOCKING
* removed dependency on i2c bindings
* added AsBusDevice implementation for platform::Device
* removed device::Device fallback implementation
* document that AsBusDevice must not be used by drivers and is intended for bus and class device abstractions only.
Changes since v4:
* add abstraction to convert a device reference to a bus device reference
* require the bus device as parent device and provide it in class device callbacks
* remove Pin<Vec<_>> abstraction (as not relevant for the led abstractions)
* fixed formatting in led::Device::new
* fixed LedOps::BLOCKING did the inverse effect
Changes since v3:
* fixed kunit tests failing because of example in documentation
Changes since v2:
* return Devres on led::Device creation
* replace KBox<T> with T in struct definition
* increment and decrement reference-count of fwnode
* make a device parent mandatory for led classdev creation
* rename led::Handler to led::LedOps
* add optional brightness_get function to led::LedOps
* use #[vtable] instead of const BLINK: bool
* use Opaque::cast_from instead of casting a pointer
* improve documentation
* improve support for older rust versions
* use &Device<Bound> for parent
Changes since v1:
* fixed typos noticed by Onur Özkan
---
Markus Probst (3):
rust: leds: add basic led classdev abstractions
rust: leds: add Mode trait
rust: leds: add multicolor classdev abstractions
MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 351 +++++++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 396 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 229 +++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 986 insertions(+)
---
base-commit: 5e9b7d093f3f77cb0af4409559e3d139babfb443
change-id: 20251114-rust_leds-a959f7c2f7f9
PATCH v15 1/3 rust: leds: add basic led classdev abstractions
Implement the core abstractions needed for led class devices, including:
* led::LedOps - the trait for handling leds, including brightness_set, brightness_get and blink_set
* led::DeviceBuilder - the builder for the led class device
* led::Device - a safe wrapper around led_classdev
--- MAINTAINERS | 8 ++ rust/kernel/led.rs | 296 ++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 221 ++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 526 insertions(+)
MAINTAINERS +8 -0
@@ -14519,6 +14519,14 @@ F: drivers/leds/ F: include/dt-bindings/leds/ F: include/linux/leds.h +LED SUBSYSTEM [RUST] +M: Markus Probst <[email protected]> +L: [email protected] +L: [email protected] +S: Maintained +F: rust/kernel/led.rs +F: rust/kernel/led/ + LEGO MINDSTORMS EV3 R: David Lechner <[email protected]> S: Maintained
rust/kernel/led.rs new file +296 -0
296 lines not on this page · raw message
rust/kernel/led/normal.rs new file +221 -0
221 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -89,6 +89,7 @@pub mod jump_label;#[cfg( CONFIG_KUNIT )] pub mod kunit; +pub mod led;pub mod list;pub mod maple_tree;pub mod miscdevice;
Signature · 1 line
2.53.0
A message that is not in the archive (sent off-list or not yet received): [email protected]
Re: [PATCH v15 1/3] rust: leds: add basic led classdev abstractions
Quoted 61 lines · On Wed, 2026-04-29 at 20:56 +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High]DeviceBuilder::namelifetime erasure causes Use-After-Free
- [High] Unsound fwnode reference count management causes underflow and Use-After-Free
- [High] Aliasing violation and Null pointer dereference (Undefined Behavior) inblink_set_callback
- [Medium]LedOps::brightness_getprevents propagating hardware errors
--commit
a78848106d199e2b6993093a6b1e1aad9d0557e7
Author: Markus Probst <[email protected]>rust: leds: add basic led classdev abstractions
This commit introduces basic Rust abstractions for the LED subsystem, including a LedOps trait for device operations, a DeviceBuilder to register class devices, and a safe wrapper Device around
led_classdev.Quoted 5 lines
rust/kernel/led.rs new file +0
-0[ ... ]
rust/kernel/led.rs line 144
Quoted 13 lines
rust/kernel/led.rs new file +13
-0+impl <'a>DeviceBuilder <'a,Named > { +/// Sets the name of the led. +/// +/// Setting this will prevent the fwnode from being used and prevents automatic name +/// composition. +#[inline] +pub fn name (self, name: &'aCStr ) ->Self { +Self { + name:Some (name), + ..self + } + } +}Is it possible for the name string to be freed while the C subsystem still holds a pointer to it?
DeviceBuilder::nameaccepts a &'a CStr and assigns its raw pointer to the name field ofbindings::led_classdev.Because Device<T> has no lifetime parameters,
DeviceBuilder::buildreturns a Devres<Device<T>> that outlives the 'a lifetime.If a caller dynamically allocates a string, registers the device, and drops the string, the C subsystem might retain a dangling pointer in
led_cdev->namesince it does not copy the name wheninit_datais bypassed. This could lead to a use-after-free when sysfs orled_classdev_unregisteraccesses the name.[ ... ]
rust/kernel/led.rs line 217
Quoted 5 lines
rust/kernel/led.rs new file +5
-0+/// Gets the current brightness level. +fn brightness_get (&self, dev: &Self ::Bus , classdev: &Device <Self >) ->u32 { +let _ = (dev, classdev); +build_error! (VTABLE_DEFAULT_ERROR ) + }Does this signature prevent Rust LED drivers from safely propagating hardware read errors?
Quoted 8 lines
The C callback
brightness_getreturns an enumled_brightness, which the C subsystem treats as an int capable of holding negative error codes like-EIO.Functions in the C core explicitly check for negative return values to gracefully handle hardware failures. Returning a u32 forces drivers to return bogus brightness values instead of an error. Could this be changed to return a Result<u32>?
Yes.
Bindgen interprets enum led_brightness as u32, so it will require casting.
Only this issue is new. All other reports have already been dealt with the last revision.
Thanks
- Markus Probst
Quoted 71 lines
Quoted 6 lines
rust/kernel/led/normal.rs new file +0
-0[ ... ]
Quoted 12 lines
rust/kernel/led/normal.rs new file +12
-0+unsafe extern "C" fn blink_set_callback ( + led_cdev: *mut bindings::led_classdev , + delay_on: *mut usize , + delay_off: *mut usize , + ) ->i32 { +from_result (|| { +// SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a +// `led_classdev` embedded within a `led::Device`. +let classdev =unsafe {Device ::<T >::from_raw (led_cdev) }; +// SAFETY: `classdev.parent()` is guaranteed to be contained in `T::Bus`. +let parent =unsafe {T ::Bus ::from_device (classdev.parent ()) }; +rust/kernel/led/normal.rs line 197
Quoted 10 lines
rust/kernel/led/normal.rs new file +10
-0+ classdev.ops.blink_set ( + parent, + classdev, +// SAFETY: The function's contract guarantees that `delay_on` points to a `usize` +// and is exclusive for the period of this function. +unsafe { &mut *delay_on }, +// SAFETY: The function's contract guarantees that `delay_off` points to a `usize` +// and is exclusive for the period of this function. +unsafe { &mut *delay_off }, + )?;The C API permits callers to pass NULL for these arguments to request default blink delays. Would dereferencing a null pointer here to create a Rust reference cause immediate undefined behavior?
Additionally, when the C core passes pointers to the
blink_delay_onandblink_delay_offfields inside theled_classdevstruct, the callback simultaneously creates an immutable reference &Device<T> to the entire struct.Does creating a mutable reference to a field while holding an immutable reference to the parent struct violate strict aliasing rules?
[ ... ]
rust/kernel/led/normal.rs line 215
Quoted 13 lines
rust/kernel/led/normal.rs new file +13
-0+#[pinned_drop] +impl <T :LedOps >PinnedDrop for Device <T > { +fn drop (self:Pin <&mut Self >) { +let raw = self.classdev.get (); +// SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a +// valid `led_classdev`. +let dev: &device::Device =unsafe { device::Device ::from_raw ((*raw).dev) }; + +let _fwnode = dev + .fwnode () +// SAFETY: the reference count of `fwnode` has previously been +// incremented in `led::Device::new`. + .map (|fwnode|unsafe {ARef ::from_raw (NonNull ::from (fwnode)) });Can this underflow the fwnode reference count if self.fwnode was None during device building?
In
DeviceBuilder::build, the code attempts to leak the FwNode reference by callingcore::mem::forget(self.fwnode). If self.fwnode was None, nothing is leaked.If the C driver core later automatically assigns an fwnode to the device,
dev.fwnode()will return Some. This would cause PinnedDrop to construct an ARef and drop it, decrementing a reference count that it never incremented or owned.
PATCH v15 2/3 rust: leds: add Mode trait
In reply to Markus ProbstAdd the led::Mode trait to allow for other types of led class devices in led::LedOps.
--- rust/kernel/led.rs | 31 +++++++++++++++++++++++++++---- rust/kernel/led/normal.rs | 24 ++++++++++++++++-------- 2 files changed, 43 insertions(+), 12 deletions(-)
rust/kernel/led.rs +27 -4
@@ -33,7 +33,10 @@mod normal; -pub use normal::Device ; +pub use normal::{ +Device , +Normal ,// +};/// The name of the led is determined by the driver. pub enum Named {}
@@ -162,6 +165,7 @@ pub fn name(self, name: &'a CStr) -> Self {/// #[vtable] /// impl led::LedOps for MyLedOps { /// type Bus = platform::Device<device::Bound>; +/// type Mode = led::Normal; /// const BLOCKING: bool = false; /// const MAX_BRIGHTNESS: u32 = 255; ///
@@ -194,6 +198,11 @@ pub trait LedOps: Send + Sync + 'static + Sized {#[allow(private_bounds)] type Bus :AsBusDevice <Bound >; +/// The led mode to use. +/// +/// See [`Mode`]. +type Mode :Mode ; +/// If set true, [`LedOps::brightness_set`] and [`LedOps::blink_set`] must perform the /// operation immediately. If set false, they must not sleep. const BLOCKING :bool ;
@@ -206,12 +215,16 @@ pub trait LedOps: Send + Sync + 'static + Sized {fn brightness_set ( &self, dev: &Self ::Bus , - classdev: &Device <Self >, + classdev: &<Self ::Mode as Mode >::Device <Self >, brightness:u32 , ) ->Result <()>;/// Gets the current brightness level. -fn brightness_get (&self, dev: &Self ::Bus , classdev: &Device <Self >) ->u32 { +fn brightness_get ( + &self, + dev: &Self ::Bus , + classdev: &<Self ::Mode as Mode >::Device <Self >, + ) ->u32 {let _ = (dev, classdev);build_error! (VTABLE_DEFAULT_ERROR ) }
@@ -227,7 +240,7 @@ fn brightness_get(&self, dev: &Self::Bus, classdev: &Device<Self>) -> u32 {fn blink_set ( &self, dev: &Self ::Bus , - classdev: &Device <Self >, + classdev: &<Self ::Mode as Mode >::Device <Self >, delay_on: &mut usize , delay_off: &mut usize , ) ->Result <()> {
@@ -291,6 +304,16 @@ fn try_from(value: u32) -> core::result::Result<Self, Self::Error> { } } +/// The led mode. +/// +/// Each led mode has its own led class device type with different capabilities. +/// +/// See [`Normal`]. +pub trait Mode : private::Sealed { +/// The class device for the led mode. +type Device <T :LedOps <Mode =Self >>; +} +mod private {pub trait Sealed {} }
rust/kernel/led/normal.rs +16 -8
@@ -6,11 +6,19 @@use super ::*; +/// The led mode for the `struct led_classdev`. Leds with this mode can only have a fixed color. +pub enum Normal {} + +impl Mode for Normal { +type Device <T :LedOps <Mode =Self >> =Device <T >; +} +impl private::Sealed for Normal {} +/// The led class device representation. /// /// This structure represents the Rust abstraction for a led class device. #[pin_data( PinnedDrop )] -pub struct Device <T :LedOps > { +pub struct Device <T :LedOps <Mode =Normal >> {#[pin] ops:T , #[pin]
@@ -19,7 +27,7 @@ pub struct Device<T: LedOps> {impl <'a,S :DeviceBuilderState >DeviceBuilder <'a,S > {/// Registers a new [`Device`]. -pub fn build <T :LedOps >( +pub fn build <T :LedOps <Mode =Normal >>( self, parent: &'aT ::Bus , ops: impl PinInit<T, Error> + 'a,
@@ -86,7 +94,7 @@ pub fn build<T: LedOps>( } } -impl <T :LedOps >Device <T > { +impl <T :LedOps <Mode =Normal >>Device <T > {/// # Safety /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a /// `led::Device`.
@@ -105,17 +113,17 @@ fn parent(&self) -> &device::Device<Bound> { }// SAFETY: A `led::Device` can be unregistered from any thread. -unsafe impl <T :LedOps +Send >Send for Device <T > {} +unsafe impl <T :LedOps <Mode =Normal > +Send >Send for Device <T > {}// SAFETY: `led::Device` can be shared among threads because all methods of `led::Device` // are thread safe. -unsafe impl <T :LedOps +Sync >Sync for Device <T > {} +unsafe impl <T :LedOps <Mode =Normal > +Sync >Sync for Device <T > {} -struct Adapter <T :LedOps > { +struct Adapter <T :LedOps <Mode =Normal >> { _p:PhantomData <T >, } -impl <T :LedOps >Adapter <T > { +impl <T :LedOps <Mode =Normal >>Adapter <T > {/// # Safety /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a /// `led::Device`.
@@ -201,7 +209,7 @@ impl<T: LedOps> Adapter<T> { }#[pinned_drop] -impl <T :LedOps >PinnedDrop for Device <T > { +impl <T :LedOps <Mode =Normal >>PinnedDrop for Device <T > {fn drop (self:Pin <&mut Self >) {let raw = self.classdev.get ();// SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a
Signature · 1 line
2.53.0
PATCH v15 3/3 rust: leds: add multicolor classdev abstractions
In reply to Markus ProbstImplement the abstractions needed for multicolor led class devices, including:
* led::MultiColor - the led mode implementation
* MultiColorSubLed - a safe wrapper arround mc_subled
* led::MultiColorDevice - a safe wrapper around led_classdev_mc
* led::DeviceBuilder::build_multicolor - a function to register a new multicolor led class device
--- rust/bindings/bindings_helper.h | 1 + rust/kernel/led.rs | 34 +++- rust/kernel/led/multicolor.rs | 396 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 430 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +1 -0
@@ -67,6 +67,7 @@#include <linux/iosys-map.h> #include <linux/jiffies.h> #include <linux/jump_label.h> +#include <linux/led-class-multicolor.h> #include <linux/mdio.h> #include <linux/mm.h> #include <linux/miscdevice.h>
rust/kernel/led.rs +33 -1
@@ -31,8 +31,16 @@ types::Opaque, // }; +#[cfg( CONFIG_LEDS_CLASS_MULTICOLOR )] +mod multicolor;mod normal; +#[cfg( CONFIG_LEDS_CLASS_MULTICOLOR )] +pub use multicolor::{ +MultiColor , +MultiColorDevice , +MultiColorSubLed ,// +};pub use normal::{Device ,Normal ,//
@@ -267,7 +275,24 @@ pub enum Color { Violet = bindings::LED_COLOR_ID_VIOLET, Yellow = bindings::LED_COLOR_ID_YELLOW, Ir = bindings::LED_COLOR_ID_IR, +#[cfg_attr( +CONFIG_LEDS_CLASS_MULTICOLOR , +doc = "Use this color for a [`MultiColor`] led." +)] +#[cfg_attr( +not( CONFIG_LEDS_CLASS_MULTICOLOR ), +doc = "Use this color for a `MultiColor` led." +)] +/// If the led supports RGB, use [`Color::Rgb`] instead. Multi = bindings::LED_COLOR_ID_MULTI, +#[cfg_attr( +CONFIG_LEDS_CLASS_MULTICOLOR , +doc = "Use this color for a [`MultiColor`] led with rgb support." +)] +#[cfg_attr( +not( CONFIG_LEDS_CLASS_MULTICOLOR ), +doc = "Use this color for a `MultiColor` led with rgb support." +)] Rgb = bindings::LED_COLOR_ID_RGB, Purple = bindings::LED_COLOR_ID_PURPLE, Orange = bindings::LED_COLOR_ID_ORANGE,
@@ -308,7 +333,14 @@ fn try_from(value: u32) -> core::result::Result<Self, Self::Error> {/// /// Each led mode has its own led class device type with different capabilities. /// -/// See [`Normal`]. +#[cfg_attr( +CONFIG_LEDS_CLASS_MULTICOLOR , +doc = "See [`Normal`] and [`MultiColor`]." +)] +#[cfg_attr( +not( CONFIG_LEDS_CLASS_MULTICOLOR ), +doc = "See [`Normal`] and `MultiColor`." +)] pub trait Mode : private::Sealed {/// The class device for the led mode. type Device <T :LedOps <Mode =Self >>;
rust/kernel/led/multicolor.rs new file +396 -0
396 lines not on this page · raw message
Signature · 1 line
2.53.0