rust: leds: add led classdev abstractions
v19 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.
This series depends on [2].
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] 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 v18:
* add inlines
* fix invalid documentation
* improve led color duplicate checking
Changes since v17:
* use lifetimes instead of Devres
Changes since v16:
* use for loops for duplicate checking
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 | 339 +++++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 405 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 238 +++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 992 insertions(+)
---
base-commit: 3bc831df9ee16fceee851872315161377ca1417d
change-id: 20251114-rust_leds-a959f7c2f7f9
prerequisite-message-id: [email protected]
prerequisite-patch-id: d2aebf69b153c039bbed1d0ed26906708fd22534
prerequisite-patch-id: 84b28da2f5de20fc1785095c647b2ffc35d969a5
prerequisite-patch-id: 67318671a5eed5fb4ad23a450f1cf0e442bf8ca2
prerequisite-message-id: [email protected]
prerequisite-patch-id: b84db329d4372a175cb8d49e4e88c3eecf7eb228
prerequisite-patch-id: 2c30303f409cc8288cc87e241920219f5ddd8390
prerequisite-patch-id: 4e4f0ad370d763ad00b0f75b91fa216f2cc95953
prerequisite-patch-id: 5bcd6b37f3498feebda275dfef78136eba34004e
prerequisite-patch-id: 872b0982f3e5e7d1698d9df3b325e4cd27b27789
prerequisite-patch-id: 3a3c7749e017d9335f58497404d1350e96caf471
prerequisite-patch-id: 3526c9154f581497a11465b936d83ef61a875454
prerequisite-patch-id: 65d8c757b52475c2acc7d22ddc92cd3f0152b55d
prerequisite-patch-id: 4bd31f1414d5248dc080884caadf5f21684a8427
prerequisite-patch-id: 7beadbb0da3e589ed86d12f512d1c83427dd82b4
prerequisite-patch-id: 12cd0f67ffd27347f90c065db491945908206b7f
prerequisite-patch-id: 4642e31f66331f6c3b579377111ea733dbb3a11c
prerequisite-patch-id: 52d67b40b4396c741e2222d6a5bc7927abcb77aa
prerequisite-patch-id: 74ca82ff26cf9c7a993757c87db8be62006e820f
prerequisite-patch-id: 466fb9fa7febbffd8ef51b311c7d9893c11fc0f0
prerequisite-patch-id: e515cd98b06e26721cbbe6a4fbacd251d0073b63
prerequisite-patch-id: 8dc8e75d9f6499a554ef7e474bbacdbf3660a9f2
prerequisite-patch-id: 5fdb9f71dca2f44dd293760a60db125b770f1f55
prerequisite-patch-id: c766a24c2d5064f5ec09daada0b8e8fba862d3aa
prerequisite-patch-id: b768f6456d35fa7a80c015e34bbdba6082dbd593
prerequisite-patch-id: 6a8b17234f12f7084e6e2ce843a7031b0a891ce4
prerequisite-patch-id: 98b2deb9e60c1f28f90c5ee34fd608aaa9fd9420
prerequisite-patch-id: 774b29be66e641ee50cedb4704cf49d8b9fabf50
prerequisite-patch-id: cf95dc936cfc4b3a7a363435a51a48d9009645b3
PATCH v19 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 | 288 ++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 230 ++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 527 insertions(+)
MAINTAINERS +8 -0
@@ -14533,6 +14533,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 +288 -0
288 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
[email protected]
AI reviewRe: [PATCH v19 1/3] rust: leds: add basic led classdev abstractions
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] The `PinnedDrop` implementation for `Device` unconditionally retrieves the `FwNode` from the C…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] The PinnedDrop implementation for Device unconditionally retrieves the FwNode from the C device and constructs an ARef<FwNode> to decrement its refcount, which can lead to refcount underflow and use-after-free.
- [High] DeviceBuilder::name accepts a temporary string reference that is embedded into the C led_classdev struct, but the resulting Device does not capture this lifetime, allowing the string to be freed while the kernel retains a dangling pointer.
- [High] The blink_set_callback concurrently creates exclusive mutable references (&mut usize) from shared memory pointers without locks, triggering Undefined Behavior.
--
commit 98d2c51d584ea9d4d3617e05e091d1f8a6a9b7c2
Author: Markus Probst <[email protected]>
rust: leds: add basic led classdev abstractions
This commit introduces the core abstractions needed for LED class devices in Rust. It implements traits for handling LEDs, a builder for the LED class device, and a safe wrapper around led_classdev.
Quoted 4 lines
rust/kernel/led.rs new file +0
-0
[ ... ]
rust/kernel/led.rs line 137
Quoted 7 lines
rust/kernel/led.rs new file +7
-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 {
[Severity: High]
Does this builder API allow the C string to be freed while the kernel retains a dangling pointer?
The name method accepts a string reference bounded by a lifetime, but the resulting Device struct does not capture this lifetime. The raw string pointer is written into the long-lived led_classdev C struct in DeviceBuilder::build.
If the caller dynamically allocates a CString and drops it immediately after pin-initialization, the C LED subsystem could later access a dangling pointer when sysfs triggers or error messages run.
Quoted 6 lines
rust/kernel/led.rs new file +6
-0+Self { + name:Some (name), + ..self + } + } +}
[ ... ]
Quoted 4 lines
rust/kernel/led/normal.rs new file +0
-0
[ ... ]
Quoted 11 lines
rust/kernel/led/normal.rs new file +11
-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 205
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 },
[Severity: High]
Can this lead to concurrent aliasing mutable references and undefined behavior?
The C LED subsystem can invoke the blink callback without locks. For example, when users write to the sysfs delay_on file, led_delay_on_store() calls led_blink_set() and passes pointers to shared struct fields like &led_cdev->blink_delay_off.
If multiple CPUs write to the sysfs file concurrently, they could invoke this callback simultaneously with the exact same pointer. Creating exclusive mutable references from these shared pointers concurrently violates Rust's mutable aliasing rules.
Quoted 5 lines
rust/kernel/led/normal.rs new file +5
-0+ )?; +Ok (0 ) + }) + } +}
[ ... ]
rust/kernel/led/normal.rs line 224
Quoted 13 lines
rust/kernel/led/normal.rs new file +13
-0+#[pinned_drop] +impl <'bound,T :LedOps + 'bound>PinnedDrop for Device <'bound,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)) });
[Severity: High]
Can this lead to a refcount underflow and use-after-free of the firmware node?
DeviceBuilder::build transfers ownership and leaks the self.fwnode refcount only if it was provided. However, this drop implementation unconditionally retrieves the FwNode from the C device and constructs an ARef to decrement its refcount.
The C driver core can independently populate dev->fwnode, such as via ACPI bindings during device_add. If the C code populates the node while self.fwnode was not set, this code will blindly construct an ARef and drop it, underflowing the refcount of an active firmware node.
Quoted 6 lines
rust/kernel/led/normal.rs new file +6
-0+ +// SAFETY: The existence of `self` guarantees that `self.classdev` has previously been +// successfully registered with `led_classdev_register_ext`. +unsafe { bindings::led_classdev_unregister (raw) }; + } +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v19 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 | 27 +++++++++++++++++++++++---- rust/kernel/led/normal.rs | 22 +++++++++++++++------- 2 files changed, 38 insertions(+), 11 deletions(-)
rust/kernel/led.rs +23 -4
@@ -32,7 +32,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 {}
@@ -161,6 +164,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; ///
@@ -182,6 +186,11 @@ pub trait LedOps: Send + Sync + 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 ;
@@ -194,7 +203,7 @@ pub trait LedOps: Send + Sync + Sized {fn brightness_set <'bound>( &self, dev: &'boundSelf ::Bus , - classdev: &Device <'bound,Self >, + classdev: &<Self ::Mode as Mode >::Device <'bound,Self >, brightness:u32 , ) ->Result <()>;
@@ -202,7 +211,7 @@ fn brightness_set<'bound>(fn brightness_get <'bound>( &self, dev: &'boundSelf ::Bus , - classdev: &Device <'bound,Self >, + classdev: &<Self ::Mode as Mode >::Device <'bound,Self >, ) ->Result <u32 > {let _ = (dev, classdev);build_error! (VTABLE_DEFAULT_ERROR )
@@ -219,7 +228,7 @@ fn brightness_get<'bound>(fn blink_set <'bound>( &self, dev: &'boundSelf ::Bus , - classdev: &Device <'bound,Self >, + classdev: &<Self ::Mode as Mode >::Device <'bound,Self >, delay_on: &mut usize , delay_off: &mut usize , ) ->Result <()> {
@@ -283,6 +292,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 <'bound,T :LedOps <Mode =Self > + 'bound>; +} +mod private {pub trait Sealed {} }
rust/kernel/led/normal.rs +15 -7
@@ -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 <'bound,T :LedOps <Mode =Self > + 'bound> =Device <'bound,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 <'bound,T :LedOps + 'bound> { +pub struct Device <'bound,T :LedOps <Mode =Normal > + 'bound> {#[pin] ops:T , #[pin]
@@ -20,7 +28,7 @@ pub struct Device<'bound, T: LedOps + 'bound> {impl <'a,S :DeviceBuilderState >DeviceBuilder <'a,S > {/// Registers a new [`Device`]. -pub fn build <'bound: 'a,T :LedOps + 'bound>( +pub fn build <'bound: 'a,T :LedOps <Mode =Normal > + 'bound>( self, parent: &'boundT ::Bus , ops: impl PinInit<T, Error> + 'a,
@@ -87,7 +95,7 @@ pub fn build<'bound: 'a, T: LedOps + 'bound>( } } -impl <'bound,T :LedOps + 'bound>Device <'bound,T > { +impl <'bound,T :LedOps <Mode =Normal > + 'bound>Device <'bound,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) -> &'bound device::Device<Bound> { }// SAFETY: A `led::Device` can be unregistered from any thread. -unsafe impl <'bound,T :LedOps + 'bound +Send >Send for Device <'bound,T > {} +unsafe impl <'bound,T :LedOps <Mode =Normal > + 'bound +Send >Send for Device <'bound,T > {}// SAFETY: `led::Device` can be shared among threads because all methods of `led::Device` // are thread safe. -unsafe impl <'bound,T :LedOps + 'bound +Sync >Sync for Device <'bound,T > {} +unsafe impl <'bound,T :LedOps <Mode =Normal > + 'bound +Sync >Sync for Device <'bound,T > {}struct Adapter <T :LedOps > { _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 <'bound,T :LedOps + 'bound>PinnedDrop for Device <'bound,T > { +impl <'bound,T :LedOps <Mode =Normal > + 'bound>PinnedDrop for Device <'bound,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
[email protected]
AI reviewRe: [PATCH v19 2/3] rust: leds: add Mode trait
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Compilation error due to undeclared module 'private'. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Compilation error due to undeclared module 'private'.
--
commit e81e640b175bb4d8e30e9e60973a904d55f53f03
Author: Markus Probst <[email protected]>
rust: leds: add Mode trait
This commit adds 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
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 <'bound,T :LedOps <Mode =Self > + 'bound> =Device <'bound,T >; +} +impl private::Sealed for Normal {}
[Severity: Low]
Will this compile? The glob import use super::*; only brings public items from the parent module into scope. Since mod private is private to led.rs, it seems private::Sealed is not in scope here. Should this explicitly reference the parent module using impl super::private::Sealed for Normal {}?
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v19 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
@@ -30,8 +30,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 ,//
@@ -255,7 +263,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,
@@ -296,7 +321,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 <'bound,T :LedOps <Mode =Self > + 'bound>;
rust/kernel/led/multicolor.rs new file +405 -0
405 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v19 3/3] rust: leds: add multicolor classdev abstractions
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Reconstructing `KVec` with `num_colors` as capacity leads to Undefined Behavior due to a capacity…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Reconstructing KVec with num_colors as capacity leads to Undefined Behavior due to a capacity and type mismatch.
- [High] Exposing brightness and intensity as plain u32 fields in a shared reference &[MultiColorSubLed] violates Rust's aliasing rules and introduces data races.
- [High] The MultiColorDevice API has a soundness hole that fails to capture the 'a lifetime of the name string, leading to a Use-After-Free of led_cdev->name. --
commit a904c5bd0f7e2718f470d76c33437063136b14c4
Author: Markus Probst <[email protected]>
rust: leds: add multicolor classdev abstractions
Implement the abstractions needed for multicolor led class devices, including MultiColor, MultiColorSubLed, MultiColorDevice, and build_multicolor.
Quoted 5 lines
rust/kernel/led/multicolor.rs new file +0
-0
[ ... ]
rust/kernel/led/multicolor.rs line 35
Quoted 12 lines
rust/kernel/led/multicolor.rs new file +12
-0+#[repr( C )] +#[derive( Copy , Clone , Debug )] +#[non_exhaustive] +pub struct MultiColorSubLed { +/// the color of the sub led +pub color:Color , +/// the brightness of the sub led. +/// +/// The value will be automatically calculated. +pub brightness:u32 , +/// the intensity of the sub led. +pub intensity:u32 ,
[Severity: High]
Will exposing brightness and intensity as plain u32 fields violate Rust's aliasing rules?
When a driver calls subleds() to get a &[MultiColorSubLed], it receives an immutable reference which guarantees the underlying memory won't be modified concurrently. However, the C LED subsystem can mutate these fields concurrently (for instance, via multi_intensity_store() or led_mc_calc_color_components()). Should these fields be wrapped in Opaque<u32> or UnsafeCell<u32> to allow safe concurrent modifications?
Quoted 3 lines
rust/kernel/led/multicolor.rs new file +3
-0+/// arbitrary data for the driver to store. + pub channel: u32, +}
[ ... ]
rust/kernel/led/multicolor.rs line 124
Quoted 8 lines
rust/kernel/led/multicolor.rs new file +8
-0+impl <'a,S :DeviceBuilderState >DeviceBuilder <'a,S > { +/// Registers a new [`MulticolorDevice`]. +pub fn build_multicolor <'bound: 'a,T :LedOps <Mode =MultiColor > + 'bound>( + self, + parent: &'boundT ::Bus , + ops:impl PinInit <T ,Error > + 'a, + subleds: &'a [MultiColorSubLed ], + ) ->impl PinInit <MultiColorDevice <'bound,T >,Error > + 'a {
[Severity: High]
Could the returned initialization type fail to capture the 'a lifetime of the name string in DeviceBuilder?
Because MultiColorDevice<'bound, T> does not capture 'a, safe code might pass a short-lived stack-allocated CString to the builder and drop it after registration, while the registered MultiColorDevice remains alive.
Quoted 5 lines
rust/kernel/led/multicolor.rs new file +5
-0+const_assert! (T ::MAX_BRIGHTNESS <=i32 ::MAX .unsigned_abs () || !T ::HAS_BRIGHTNESS_GET ); + +try_pin_init! (MultiColorDevice { + ops <- ops, + classdev <-Opaque ::try_ffi_init(|ptr: *mut bindings::led_classdev_mc | {
[ ... ]
rust/kernel/led/multicolor.rs line 141
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);
[Severity: High]
Can discarding the true capacity from into_raw_parts() lead to undefined behavior during deallocation?
When extend_from_slice() allocates the underlying buffer, the allocator may reserve a larger capacity than exactly num_colors. If the true capacity is discarded, later reconstructing the vector with capacity set to num_colors violates the from_raw_parts() safety contract and could pass the wrong layout to the deallocator.
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) }); + });
[ ... ]
Quoted 5 lines
rust/kernel/led/multicolor.rs new file +5
-0+unsafe { + ptr.write (bindings::led_classdev_mc { + led_cdev: bindings::led_classdev { + brightness_set: (!T ::BLOCKING ) + .then_some (Adapter ::<T >::brightness_set_callback),
rust/kernel/led/multicolor.rs line 166
Quoted 10 lines
rust/kernel/led/multicolor.rs new file +10
-0+ brightness_set_blocking: T::BLOCKING + .then_some(Adapter::<T>::brightness_set_blocking_callback), + brightness_get: T::HAS_BRIGHTNESS_GET + .then_some(Adapter::<T>::brightness_get_callback), + blink_set: T::HAS_BLINK_SET + .then_some(Adapter::<T>::blink_set_callback), + max_brightness: T::MAX_BRIGHTNESS, + brightness: self.initial_brightness, + color: self.color as u32, + name: self.name.map_or(core::ptr::null(), CStrExt::as_char_ptr),
[Severity: High]
Might assigning self.name directly to the C struct without copying result in a use-after-free?
If the DeviceBuilder was provided a short-lived string, this pointer will become dangling once the string is dropped, as mentioned above. Should the API require &'static CStr or duplicate the string to avoid a use-after-free?
Quoted 2 lines
rust/kernel/led/multicolor.rs new file +2
-0+ ..bindings::led_classdev::default () + },
[ ... ]
rust/kernel/led/multicolor.rs line 240
Quoted 3 lines
rust/kernel/led/multicolor.rs new file +3
-0+/// Returns the subleds passed to [`Device::new_multicolor`]. +#[inline] +pub fn subleds (&self) -> &[MultiColorSubLed ] {
[Severity: High]
Is it safe to return a shared reference &[MultiColorSubLed] when C code may concurrently mutate fields?
Because MultiColorDevice is Sync, drivers might retain this slice and concurrently read the brightness and intensity fields. Since they are plain u32 fields, this could introduce data races.
Quoted 3 lines
rust/kernel/led/multicolor.rs new file +3
-0+// 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 () };
[ ... ]
Quoted 4 lines
rust/kernel/led/multicolor.rs new file +4
-0+#[pinned_drop] +impl <'bound,T :LedOps <Mode =MultiColor > + 'bound>PinnedDrop for MultiColorDevice <'bound,T > { +fn drop (self:Pin <&mut Self >) { +let raw = self.classdev.get ();
[ ... ]
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 , + ) + }); + } +}
[Severity: High]
Does this KVec reconstruction cause undefined behavior upon deallocation?
Similar to the ScopeGuard above, passing num_colors as the capacity instead of the original capacity violates the from_raw_parts() contract. Additionally, reconstructing using KVec::from_raw_parts with bindings::mc_subled instead of the original MultiColorSubLed type might violate allocator provenance rules.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3