rust: leds: add led classdev abstractions
v16 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 v15:
* fix issues reported by Sashiko bot:
* fix returning error not possible on brightness_get callback
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 | 405 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 238 +++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 1004 insertions(+)
---
base-commit: 5e9b7d093f3f77cb0af4409559e3d139babfb443
change-id: 20251114-rust_leds-a959f7c2f7f9
PATCH v16 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 | 230 +++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 535 insertions(+)
MAINTAINERS +8 -0
@@ -14520,6 +14520,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 +230 -0
230 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
PATCH v16 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 >) ->Result <u32 > { +fn brightness_get ( + &self, + dev: &Self ::Bus , + classdev: &<Self ::Mode as Mode >::Device <Self >, + ) ->Result <u32 > {let _ = (dev, classdev);build_error! (VTABLE_DEFAULT_ERROR ) }
@@ -227,7 +240,7 @@ fn brightness_get(&self, dev: &Self::Bus, classdev: &Device<Self>) -> Result<u32fn 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,
@@ -88,7 +96,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`.
@@ -107,17 +115,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`.
@@ -210,7 +218,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 v16 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 | 405 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 439 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 +405 -0
405 lines not on this page · raw message
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 v16 3/3] rust: leds: add multicolor classdev abstractions
Quoted 36 lines · On Fri, 2026-05-01 at 16:00 +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Critical] Information Leak and Array Out-of-Bounds via FFI Layout Mismatch
- [High] Data Race and Undefined Behavior via Aliasing Violation on subled fields
- [High] Memory Leak and Use-After-Free via FwNode Reference Mismanagement
- [High] Undefined Behavior and Memory Corruption viaKVecCapacity Mismatch
- [Low] Missing#[inline]attribute onMultiColorDevice::from_raw
--commit
519046430edb434e8aa4a9b617987bbaa0db6c71
Author: Markus Probst <[email protected]>
Subject: rust: leds: add multicolor classdev abstractionsThis commit implements the abstractions needed for multicolor led class devices. It provides types for the multicolor led mode, the subleds, and the device builder to register a new multicolor led class device.
Quoted 6 lines
rust/kernel/led/multicolor.rs new file +0
-0@@ -0,0 +1,405 @@[ ... ]
rust/kernel/led/multicolor.rs line 29
Quoted 6 lines
rust/kernel/led/multicolor.rs new file +6
-0+#[repr( C )] +#[derive( Copy , Clone , Debug )] +#[non_exhaustive] +pub struct MultiColorSubLed { +/// the color of the sub led +pub color:Color ,Does this structure have an identical memory layout to the C
mc_subledstruct? The Color enum doesn't have a #[repr(u32)] or #[repr(C)] attribute, so the Rust compiler will likely size it as 1 byte.
Quoted 8 lines
To align the subsequent brightness field, the compiler would insert 3 bytes of uninitialized padding.
When the C LED core accesses mc_led_cdev->subled_info[i].color_index (which is 4 bytes), could it read the 1-byte color value combined with the uninitialized padding? This might produce a large index on little-endian architectures, potentially leading to out-of-bounds reads when the C subsystem indexes arrays like
led_colors.
Thats a new one.
false positive.Color does have a #[repr(u32)].
Thanks
- Markus Probst
Quoted 123 lines
[ ... ]
Quoted 1 line
+ pub fn build_multicolor<T: LedOps<Mode = MultiColor>>(
[ ... ]
rust/kernel/led/multicolor.rs line 148
Quoted 4 lines
rust/kernel/led/multicolor.rs new file +4
-0+let mut subleds_vec =KVec ::new (); + subleds_vec.extend_from_slice (subleds,GFP_KERNEL )?; +let (subled_info, num_colors, capacity) = subleds_vec.into_raw_parts (); +debug_assert_eq! (num_colors, capacity);Could this assertion fail if the allocator sizes the allocation larger than
num_colors?extend_from_slicecan yield a capacity strictly larger than the requested size.rust/kernel/led/multicolor.rs line 154
Quoted 6 lines
rust/kernel/led/multicolor.rs new file +6
-0+ +let subled_guard =ScopeGuard ::new (|| { +// SAFETY: `subled_info` is guaranteed to be a valid array pointer to +// `mc_subled` with the length and capacity of `num_colors`. +drop (unsafe {KVec ::from_raw_parts (subled_info, num_colors, num_colors) }); + });Is it safe to reconstruct the vector with
num_colorsas the capacity?If
extend_from_sliceoriginally allocated a capacity greater thannum_colors, passing a mismatched capacity back to the allocator during cleanup could lead to memory corruption.[ ... ]
Quoted 9 lines
rust/kernel/led/multicolor.rs new file +9
-0+// SAFETY: +// - `parent.as_ref().as_raw()` is guaranteed to be a pointer to a valid +// `device`. +// - `ptr` is guaranteed to be a pointer to an initialized `led_classdev_mc`. + to_result(unsafe { + bindings::led_classdev_multicolor_register_ext( + parent.as_ref().as_raw(), + ptr, + if self.name.is_none() {rust/kernel/led/multicolor.rs line 213
Quoted 10 lines
rust/kernel/led/multicolor.rs new file +10
-0+ &raw mut init_data + }else { + core::ptr::null_mut () + }, + ) + })?; + + subled_guard.dismiss (); + + core::mem::forget (self.fwnode);// keep the reference count incremented Does this reliably transfer the reference count to the C subsystem?
If
self.name.is_some(), theinit_datapointer is explicitly passed as NULL toled_classdev_multicolor_register_ext. This means the C device is never associated with the fwnode, and the reference count leaked here might never be recovered since PinnedDrop usesdev.fwnode()to clean it up.Conversely, if self.fwnode was None initially, but the C device inherited an fwnode from its parent, would the PinnedDrop implementation reconstruct an ARef from it and erroneously decrement a reference count it never owned?
[ ... ]
rust/kernel/led/multicolor.rs line 226
Quoted 5 lines
rust/kernel/led/multicolor.rs new file +5
-0+impl <T :LedOps <Mode =MultiColor >>MultiColorDevice <T > { +/// # Safety +/// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a +/// `led::MultiColorDevice`. +unsafe fn from_raw <'a>(led_cdev: *mut bindings::led_classdev ) -> &'aSelf {This isn't a bug, but functions that are small or forwarding to a binding call should be annotated with #[inline].
[ ... ]
Quoted 7 lines
rust/kernel/led/multicolor.rs new file +7
-0+/// Returns the subleds passed to [`Device::new_multicolor`]. +#[inline] +pub fn subleds (&self) -> &[MultiColorSubLed ] { +// SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a +// valid `led_classdev_mc`. +let raw =unsafe { &*self.classdev.get () }; +// SAFETY: `raw.subled_info` is a valid pointer to `mc_subled[num_colors]`. rust/kernel/led/multicolor.rs line 260
Quoted 10 lines
rust/kernel/led/multicolor.rs new file +10
-0+// CAST: The safeguards in the const block ensure that `MultiColorSubLed` has an identical +// layout to `mc_subled`. +unsafe { + core::slice::from_raw_parts ( + raw.subled_info.cast ::<MultiColorSubLed >(), +// CAST: It is guaranteed that `num_colors` fits into an `usize`. + raw.num_colorsas usize , + ) + } + }Does returning a shared reference &[MultiColorSubLed] violate Rust's aliasing rules?
The C LED subsystem can concurrently mutate the brightness and intensity fields of these subleds (e.g., in
led_mc_calc_color_componentsor during sysfs writes).Mutating memory from C code while a Rust driver holds a shared reference could result in undefined behavior. Should these mutable fields be wrapped in an Opaque<u32> to permit interior mutability?
[ ... ]
Quoted 3 lines
rust/kernel/led/multicolor.rs new file +3
-0+#[pinned_drop] +impl <T :LedOps <Mode =MultiColor >>PinnedDrop for MultiColorDevice <T > { +fn drop (self:Pin <&mut Self >) {[ ... ]
rust/kernel/led/multicolor.rs line 405
Quoted 11 lines
rust/kernel/led/multicolor.rs new file +11
-0+// SAFETY: `subled_info` is guaranteed to be a valid array pointer to `mc_subled` with the +// length and capacity of `led_cdev.num_colors`. See `led::MulticolorDevice::new`. +drop (unsafe { +KVec ::from_raw_parts ( + led_cdev.subled_info, + led_cdev.num_colorsas usize , + led_cdev.num_colorsas usize , + ) + }); + } +}Similar to the error path above, could reconstructing this vector with led_cdev.num_colors as the capacity cause memory corruption if the original allocation capacity was larger?