Skip to contentSkip to conversation

rust: leds: add led classdev abstractions

PATCH Superseded Markus Probst 1 participant 7 messages Apr 27 – Apr 29 3 messages not in the archive

Subsystems (3)

v14 of 29 Superseded Latest is v29 →

lore
Share & tools
lore
#0 lore raw

v14 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 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              | 356 ++++++++++++++++++++++++++++++++++++
 rust/kernel/led/multicolor.rs   | 387 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/led/normal.rs       | 231 ++++++++++++++++++++++++
 rust/kernel/lib.rs              |   1 +
 6 files changed, 984 insertions(+)

---
base-commit: 5e9b7d093f3f77cb0af4409559e3d139babfb443
change-id: 20251114-rust_leds-a959f7c2f7f9

#1 lore raw

PATCH v14 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        | 308 ++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/led/normal.rs | 223 +++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs        |   1 +
 4 files changed, 540 insertions(+)
MAINTAINERS +8 -0
index 2fb1c75afd16..58b5c9b1ff36 100644
@@ -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 +308 -0

308 lines not on this page · raw message

rust/kernel/led/normal.rs new file +223 -0

223 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index b72b2fbe046d..7a18c738c934 100644
@@ -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]

#3 lore raw

Re: [PATCH v14 1/3] rust: leds: add basic led classdev abstractions

Quoted 32 lines · On Mon, 2026-04-27 at 21:20 +0000, [email protected] wrote:

Sashiko AI review found 4 potential issue(s):
- [Critical] Unsound fwnode reference count management leads to refcount underflow and Use-After-Free.
- [Critical] Lifetime erasure in DeviceBuilder allows dangling string pointers in the C structure (Use-After-Free).
- [High] Missing Sync bound on LedOps allows data races and undefined behavior.
- [Low] Missing #[inline] annotations on small forwarding abstraction functions.
--

commit 919a1118f74d7259424462187e0643f2925bb6d6
Author: Markus Probst <[email protected]>

rust: leds: add basic led classdev abstractions

Implement the core abstractions needed for led class devices. This includes the LedOps trait for handling LEDs, the DeviceBuilder to construct the device, and a safe wrapper around led_classdev.

Quoted 5 lines
rust/kernel/led.rs new file +0 -0
new file mode 100644
index 000000000000..f371ba48ef12

[ ... ]

rust/kernel/led.rs line 206

Quoted 3 lines
rust/kernel/led.rs new file +3 -0
+#[vtable]
+pub trait LedOps: Send + 'static + Sized {
+    /// The bus device required by the implementation.

The LED subsystem frequently invokes led_classdev callbacks concurrently from multiple threads without locks. For example, led_trigger_event() calls led_set_brightness() locklessly within an RCU read-side critical section.

Quoted 3 lines

If LedOps only requires Send and lacks a Sync bound, could a driver implement this trait using types with non-thread-safe interior mutability (like core::cell::Cell), resulting in data races?

If BLOCKING is false, concurrent access to LedOps is indeed possible.

Quoted 11 lines

[ ... ]

rust/kernel/led.rs line 283

Quoted 4 lines
rust/kernel/led.rs new file +4 -0
+impl Color {
+    /// Name of the color.
+    pub fn as_c_str(self) -> &'static CStr {
+        // SAFETY:

This isn't a bug, but the Rust subsystem coding guidelines require small forwarding abstraction functions to be annotated with #[inline]. Could this attribute be added here?

I suppose yes.

Quoted 32 lines
Quoted 6 lines
rust/kernel/led/normal.rs new file +0 -0
new file mode 100644
index 000000000000..bd239f186c64

[ ... ]

Quoted 8 lines
rust/kernel/led/normal.rs new file +8 -0
+/// The led class device representation.
+///
+/// This structure represents the Rust abstraction for a led class device.
+#[pin_data(PinnedDrop)]
+pub struct Device<T: LedOps> {
+    #[pin]
+    ops: T,
+    #[pin]

rust/kernel/led/normal.rs line 26

Quoted 10 lines
rust/kernel/led/normal.rs new file +10 -0
+    classdev: Opaque<bindings::led_classdev>,
+}
+
+impl<'a, S: DeviceBuilderState> DeviceBuilder<'a, S> {
+    /// Registers a new [`Device`].
+    pub fn build<T: LedOps>(
+        self,
+        parent: &'a T::Bus,
+        ops: impl PinInit<T, Error> + 'a,
+    ) -> impl PinInit<Devres<Device<T>>, Error> + 'a {

Since the Device struct does not carry a lifetime parameter, does the return type impl PinInit<Devres<Device<T>>, Error> + 'a fail to prevent the caller from dropping the strings provided for the name and default_trigger fields?

Quoted 4 lines

The C subsystem retains these pointers indefinitely. If a caller passes a dynamically allocated string (like a CString), registers the LED, and drops the string, couldn't this lead to a use-after-free when the kernel later accesses led_cdev->name or led_cdev->default_trigger?

This is true for default_trigger, but not for name.

led_cdev->name will be copied on register and only has to be valid until the registration finishes.

I will remove default_trigger as I don't see a use for it at the current moment.

Quoted 40 lines

[ ... ]

rust/kernel/led/normal.rs line 96

Quoted 5 lines
rust/kernel/led/normal.rs new file +5 -0
+impl<T: LedOps> Device<T> {
+    /// # Safety
+    /// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a
+    /// `led::Device`.
+    unsafe fn from_raw<'a>(led_cdev: *mut bindings::led_classdev) -> &'a Self {

This isn't a bug, but the Rust subsystem coding guidelines require small forwarding abstraction functions to be annotated with #[inline]. Could this attribute be added here?

[ ... ]

rust/kernel/led/normal.rs line 104

Quoted 2 lines
rust/kernel/led/normal.rs new file +2 -0
+    fn parent(&self) -> &device::Device<Bound> {
+        // SAFETY: `self.classdev.get()` is guaranteed to be a valid pointer to `led_classdev`.

This isn't a bug, but could the #[inline] attribute be added here as well?

[ ... ]

rust/kernel/led/normal.rs line 217

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)) });

In DeviceBuilder::build(), core::mem::forget(self.fwnode) is called, which transfers ownership of the reference count if a node was explicitly provided.

Quoted 7 lines

However, the core kernel can automatically assign a fwnode to the device during registration (for example, device_platform_notify() may assign an ACPI companion node).

If self.fwnode was None but the kernel assigned a node automatically, won't this unconditional ARef::from_raw() incorrectly decrement a reference count the driver never incremented, resulting in an underflow and use-after-free?

false positive.

device_platform_notify calls 2 functions:
- acpi_device_notify:
only assigns fwnode to *bus devices*. This is a led class device.
- software_node_notify:
does not change the fwnode

#4 lore raw

PATCH v14 2/3 rust: leds: add Mode trait

In reply to Markus Probst

Add the led::Mode trait to allow for other types of led class devices in led::LedOps.

---
 rust/kernel/led.rs        | 28 ++++++++++++++++++++++++----
 rust/kernel/led/normal.rs | 24 ++++++++++++++++--------
 2 files changed, 40 insertions(+), 12 deletions(-)
rust/kernel/led.rs +24 -4
index f371ba48ef12..e8a69efd3066 100644
@@ -33,7 +33,7 @@
 
 mod normal;
 
-pub use normal::Device;
+pub use normal::{Device, Normal};
 
 /// The name of the led is determined by the driver.
 pub enum Named {}
@@ -175,6 +175,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;
 ///
@@ -207,6 +208,11 @@ pub trait LedOps: Send + '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;
@@ -219,12 +225,16 @@ pub trait LedOps: Send + '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)
     }
@@ -240,7 +250,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<()> {
@@ -303,6 +313,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
index bd239f186c64..dda247145f25 100644
@@ -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: &'a T::Bus,
         ops: impl PinInit<T, Error> + 'a,
@@ -89,7 +97,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`.
@@ -203,7 +211,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

A message that is not in the archive (sent off-list or not yet received): [email protected]

#6 lore raw

Re: [PATCH v14 2/3] rust: leds: add Mode trait

Quoted 34 lines · On Mon, 2026-04-27 at 21:30 +0000, [email protected] wrote:

Sashiko AI review found 1 potential issue(s):
- [Low] The implementation impl private::Sealed for Normal {} in rust/kernel/led/normal.rs will fail to compile because the private module is not in scope. --

commit 0a077c143ea17884a2c82d921e01b9d926d2e29a
Author: Markus Probst <[email protected]>

rust: leds: add Mode trait

Add the led::Mode trait to allow for other types of led class devices in led::LedOps.

Quoted 5 lines
rust/kernel/led/normal.rs +0 -0
index bd239f186c64..dda247145f25 100644

rust/kernel/led/normal.rs line 15

Quoted 10 lines
rust/kernel/led/normal.rs +7 -0
@@ -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 {}

Will this fail to compile?

In Rust, glob imports like use super::*; only bring public items into scope. Since mod private in rust/kernel/led.rs is a private module, it is not imported into the child module led/normal.rs.

Quoted 5 lines

Using the unqualified path private::Sealed will cause a compilation error about an undeclared crate or module private.

Will a similar compilation error happen in the subsequent commit for MultiColor in multicolor.rs?

It does compile.

#7 lore raw

PATCH v14 3/3 rust: leds: add multicolor classdev abstractions

In reply to Markus Probst

Implement 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              |  30 +++-
 rust/kernel/led/multicolor.rs   | 387 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 417 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +1 -0
index 446dbeaf0866..17b5461453e0 100644
@@ -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 +29 -1
index e8a69efd3066..8ec95c4f230c 100644
@@ -31,8 +31,12 @@
     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};
 
 /// The name of the led is determined by the driver.
@@ -277,7 +281,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,
@@ -317,7 +338,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 +387 -0

387 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]

#9 lore raw

Re: [PATCH v14 3/3] rust: leds: add multicolor classdev abstractions

Quoted 22 lines · On Mon, 2026-04-27 at 22:01 +0000, [email protected] wrote:

Sashiko AI review found 5 potential issue(s):
- [Critical] MultiColorDevice::subleds returns an immutable slice to plain data concurrently mutated by C code, causing an aliasing violation and Undefined Behavior.
- [High] Incorrect KVec capacity tracking causes Undefined Behavior, and an early return causes a memory leak.
- [High] The fwnode reference is permanently leaked (and may cause underflow on a different node) if a device name is explicitly set.
- [High] Creating exclusive mutable references to delay_on and delay_off in blink_set_callback violates mutable aliasing rules.
- [Low] Subsystem guidelines regarding #[inline] annotations and import formatting are violated.
--

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

rust: leds: add multicolor classdev abstractions

Implement the abstractions needed for multicolor led class devices, including led::MultiColor and safe wrappers around led_classdev_mc and mc_subled.

Quoted 4 lines
rust/kernel/led.rs +0 -0
index e8a69efd3066..8ec95c4f230c 100644

[ ... ]

Quoted 5 lines
Quoted 2 lines

#[cfg(CONFIG_LEDS_CLASS_MULTICOLOR)]
pub use multicolor::{MultiColor, MultiColorDevice, MultiColorSubLed};

This isn't a bug, but does this import follow the vertical import style mandated by the Rust subsystem coding guidelines?

It is a public export, so it may be special. I will add fix it anyways.

Quoted 7 lines
Quoted 6 lines
rust/kernel/led/multicolor.rs new file +0 -0
new file mode 100644
index 000000000000..726fdaf068cb

[ ... ]

Quoted 7 lines

rust/kernel/led/multicolor.rs line 78

Quoted 3 lines
rust/kernel/led/multicolor.rs new file +3 -0
+impl MultiColorSubLed {
+    /// Create a new multicolor sub led info.
+    pub const fn new(color: Color) -> Self {

This isn't a bug, but shouldn't small abstraction functions like new(), channel(), and initial_intensity() be annotated with #[inline] to comply with the subsystem guidelines?

Yes.

Quoted 13 lines

[ ... ]

rust/kernel/led/multicolor.rs line 147

Quoted 11 lines
rust/kernel/led/multicolor.rs new file +11 -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);
+
+                    // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.
+                    // `led_classdev_mc` gets fully initialized in-place by
+                    // `led_classdev_multicolor_register_ext` including `mutex` and `list_head`.
+                    unsafe {
+                        ptr.write(bindings::led_classdev_mc {
+                            led_cdev: bindings::led_classdev {
Quoted 5 lines

[ ... ]

Quoted 1 line

+ num_colors: u32::try_from(num_colors)?,

If u32::try_from(num_colors) fails, does this early return leak the memory allocated for subled_info?

Very unlikely event, but yes. In the case that it is greater than u32::MAX, there is a memory leak.

Quoted 23 lines

The inspect_err closure responsible for cleaning up the allocation is attached to the register_ext call further down, which wouldn't be reached if the try_from conversion evaluates to an error.

[ ... ]

Quoted 6 lines
rust/kernel/led/multicolor.rs new file +6 -0
+                    to_result(unsafe {
+                        bindings::led_classdev_multicolor_register_ext(
+                            parent.as_ref().as_raw(),
+                            ptr,
+                            if self.name.is_none() {
+                                &raw mut init_data

rust/kernel/led/multicolor.rs line 203

Quoted 10 lines
rust/kernel/led/multicolor.rs new file +10 -0
+                            } else {
+                                core::ptr::null_mut()
+                            },
+                        )
+                    })
+                    .inspect_err(|_err| {
+                        // 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) });
+                    })?;
Quoted 6 lines

Could reconstructing the vector this way cause undefined behavior?

The capacity returned by into_raw_parts() is discarded earlier, and the vector is rebuilt here with a hardcoded capacity of num_colors. Since extend_from_slice() can over-allocate, passing an incorrect capacity back to the allocator violates safety contracts.

On the first allocation, length always equals capacity. But I agree it isn't a perfect solution.

Quoted 5 lines

rust/kernel/led/multicolor.rs

Quoted 3 lines
rust/kernel/led/multicolor.rs new file +2 -0
+
+                    core::mem::forget(self.fwnode); // keep the reference count incremented

Does this leak the fwnode reference if self.name is explicitly set?

No, because it happens on an Option type.

Quoted 10 lines

When self.name.is_some(), core::ptr::null_mut() is passed to register_ext above, so the C device never associates with the fwnode. However, core::mem::forget(self.fwnode) is called here unconditionally.

During PinnedDrop, the code attempts to drop the reference by calling dev.fwnode(). Since the device was never given the fwnode, this might return None and leak the reference, or return an inherited fwnode, which would cause a reference count underflow on the wrong node.

Quoted 5 lines

[ ... ]

Quoted 1 line

+ pub fn subleds(&self) -> &[MultiColorSubLed] {

This isn't a bug, but shouldn't this small abstraction function also be annotated with #[inline]?

Yes.

Quoted 4 lines

Additionally, can returning an immutable slice of plain data here lead to undefined behavior?

Quoted 8 lines

The C subsystem can concurrently modify the underlying brightness and intensity fields (for example, led_mc_calc_color_components modifies brightness, and multi_intensity_store modifies intensity).

Because MultiColorSubLed defines these as plain u32 fields rather than wrapping them in UnsafeCell or Opaque, the Rust compiler assumes they will never change while the immutable reference exists. This violates strict aliasing rules and could lead to data races.

I don't think there is any quick way to avoid this.

Quoted 20 lines

[ ... ]

Quoted 6 lines
rust/kernel/led/multicolor.rs new file +6 -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(|| {

[ ... ]

rust/kernel/led/multicolor.rs line 350

Quoted 10 lines
rust/kernel/led/multicolor.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 },
+            )?;
Quoted 2 lines

Is it safe to create exclusive mutable references to delay_on and delay_off in this context?

Yes.

Quoted 3 lines

These pointers point directly to the shared led_cdev->blink_delay_on and led_cdev->blink_delay_off fields in the C struct.

Only with the timer trigger and the timer trigger only sets it directly on the pointer if it is happening on a sysfs store call.

Quoted 4 lines

If the sysfs interface reads these fields concurrently, such as through delay_on_show, it would violate Rust's strict mutable exclusivity guarantees and result in undefined behavior.

Afaik sysfs blocks any "show" function calls during this time.