rust: leds: add led classdev abstractions
v17 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 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 | 351 +++++++++++++++++++++++++++++++++++ rust/kernel/led/multicolor.rs | 400 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/led/normal.rs | 238 ++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 6 files changed, 999 insertions(+)
---
base-commit: 9e171fc1d7d7ab847a750c03571c87ac3c17bd84
change-id: 20251114-rust_leds-a959f7c2f7f9
PATCH v17 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
@@ -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 +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
[email protected]
AI reviewRe: [PATCH v17 1/3] rust: leds: add basic led classdev abstractions
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Lifetime erasure in `DeviceBuilder::build` allows `led_classdev.name` to hold a dangling pointer…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Lifetime erasure in DeviceBuilder::build allows led_classdev.name to hold a dangling pointer, leading to a use-after-free.
- [High] Device::drop unconditionally constructs an ARef<FwNode> from the underlying C device's fwnode, which can drop unowned references and cause a refcount underflow/use-after-free. --
commit 3bf2be04b997951443702ccedf215841f12a00f7
Author: Markus Probst <[email protected]>
rust: leds: add basic led classdev abstractions
This commit implements the core abstractions needed for led class devices, including LedOps, DeviceBuilder, and Device wrappers around led_classdev.
Quoted 4 lines
rust/kernel/led/normal.rs new file +0
-0
[ ... ]
Quoted 7 lines
rust/kernel/led/normal.rs new file +7
-0+impl <'a,S :DeviceBuilderState >DeviceBuilder <'a,S > { +/// Registers a new [`Device`]. +pub fn build <T :LedOps >( + self, + parent: &'aT ::Bus , + ops:impl PinInit <T ,Error > + 'a, + ) ->impl PinInit <Devres <Device <T >>,Error > + 'a {
[ ... ]
Quoted 2 lines
rust/kernel/led/normal.rs new file +2
-0+unsafe { + ptr.write (bindings::led_classdev {
[ ... ]
rust/kernel/led/normal.rs line 52
Quoted 4 lines
rust/kernel/led/normal.rs new file +4
-0+ name: self.name.map_or(core::ptr::null(), CStrExt::as_char_ptr), + ..bindings::led_classdev::default () + }) + };
[Severity: High]
Does this erase the lifetime bounds of the name string and risk a use-after-free?
In the DeviceBuilder definition, the name field has a bounded lifetime 'a:
name: Option<&'a CStr>
However, the returned impl PinInit builds a Device<T> which does not capture the 'a lifetime parameter, meaning the resulting device can outlive the provided string. If a caller uses a short-lived string (like a dynamically allocated CString) for the name, the string will be dropped after device initialization.
Since this raw pointer is written directly into led_classdev.name without requiring a 'static lifetime or taking internal ownership, could the kernel access freed memory when reading the name later, such as via sysfs or debug logs?
[ ... ]
rust/kernel/led/normal.rs line 224
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)) });
[Severity: High]
Can this unconditionally drop unowned fwnode references and cause a refcount underflow?
In DeviceBuilder::build(), the fwnode reference count is only leaked via core::mem::forget(self.fwnode) if self.fwnode was explicitly provided.
However, here in Device::drop(), the fwnode is read back from the underlying C device structure using dev.fwnode(), and unconditionally wrapped in an ARef to decrement its reference count.
If the device was initialized without an explicitly provided fwnode, but the kernel's driver core later automatically assigns one to the child device from its parent (e.g., during device_add), dev.fwnode() will return a valid pointer.
Would this cause Device::drop() to decrement the reference count of an fwnode it never actually owned, leading to a use-after-free?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v17 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 v17 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 | 400 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 434 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 +400 -0
400 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v17 3/3] rust: leds: add multicolor classdev abstractions
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] Data race and Undefined Behavior in `MultiColorDevice::subleds()` due to exposing concurrently…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] Data race and Undefined Behavior in MultiColorDevice::subleds() due to exposing concurrently mutable fields without interior mutability.
- [High] Undefined Behavior due to mismatched capacity when reconstructing KVec during teardown and error handling.
- [High] Incorrect fwnode reference management when name is provided leads to permanent memory leaks and refcount underflow (Use-After-Free).
- [Low] Missing #[inline] annotation on small forwarding abstraction function.
--
commit 9445e701d1ca0b8b1d07c7890ba8fe351626ede1
Author: Markus Probst <[email protected]>
rust: leds: add multicolor classdev abstractions
This commit implements the abstractions needed for multicolor led class devices. It introduces the led mode implementation, a wrapper around mc_subled, and a function to register a new multicolor led class device.
Quoted 5 lines
rust/kernel/led/multicolor.rs new file +0
-0
[ ... ]
Quoted 13 lines
rust/kernel/led/multicolor.rs new file +13
-0+pub struct MultiColorSubLed { +/// the color of the sub led +pub color:Color , +/// the brightness of the sub led. +/// +/// The value will be automatically calculated. +/// See `MultiColor::pre_brightness_set`. +pub brightness:u32 , +/// the intensity of the sub led. +pub intensity:u32 , +/// arbitrary data for the driver to store. +pub channel:u32 , +}
[ ... ]
rust/kernel/led/multicolor.rs line 149
Quoted 10 lines
rust/kernel/led/multicolor.rs new file +10
-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); + +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) }); + });
[Severity: High]
Could reconstructing the vector using num_colors instead of the original capacity cause undefined behavior during deallocation?
The extend_from_slice() call might allocate memory with a capacity strictly greater than num_colors. By discarding the true capacity and passing num_colors to KVec::from_raw_parts(), the safety contract is violated.
Rust requires the capacity passed to from_raw_parts() to exactly match the original allocation capacity, otherwise it can produce an incorrect layout during deallocation.
[ ... ]
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 208
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
[Severity: High]
Does this sequence leak the fwnode reference when a name is provided?
If self.name is provided, core::ptr::null_mut() is passed instead of init_data, meaning the C subsystem never takes ownership of the provided fwnode. However, core::mem::forget(self.fwnode) is called unconditionally, which would permanently leak the reference in this case.
[ ... ]
rust/kernel/led/multicolor.rs line 221
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 {
[Severity: Low]
Should this small forwarding function have an #[inline] annotation?
The Rust subsystem guidelines require that functions which are small or forwarding to a binding call should be annotated with #[inline].
[ ... ]
rust/kernel/led/multicolor.rs line 241
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]
Does returning a shared slice of MultiColorSubLed here lead to undefined behavior if the C subsystem mutates the fields?
When the C LED subsystem mutates the brightness fields of mc_subled concurrently (such as in led_mc_calc_color_components()), it modifies the underlying memory.
Since MultiColorSubLed defines these fields as plain u32 types and we return a safe &[MultiColorSubLed] slice, Rust's strict aliasing rules are violated because shared references guarantee memory immutability without an interior mutability primitive.
[ ... ]
rust/kernel/led/multicolor.rs line 381
Quoted 13 lines
rust/kernel/led/multicolor.rs new file +13
-0+#[pinned_drop] +impl <T :LedOps <Mode =MultiColor >>PinnedDrop for MultiColorDevice <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_mc`. +let dev: &device::Device =unsafe { device::Device ::from_raw ((*raw).led_cdev.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]
Could this underflow the parent device's fwnode reference count?
If init_data was ignored during registration (because self.name was set), the C core typically assigns the parent device's fwnode to the new LED device without incrementing its refcount.
During drop, the teardown logic blindly steals a reference via ARef::from_raw() and drops it, which would underflow the parent device's fwnode refcount and potentially cause a use-after-free.
[ ... ]
rust/kernel/led/multicolor.rs line 400
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]
Similar to the error path above, could reconstructing the vector using num_colors instead of the original capacity cause undefined behavior during deallocation here?
The extend_from_slice() call during initialization might allocate memory with a capacity strictly greater than num_colors. Discarding the true capacity and passing num_colors to KVec::from_raw_parts() violates the safety contract and can produce an incorrect layout during deallocation.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3