Linux PCI subsystem development
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Markus Probst" <markus.probst@posteo.de>
Cc: linux-leds@vger.kernel.org, linux-pci@vger.kernel.org,
	lee@kernel.org, ojeda@kernel.org, gary@garyguo.net
Subject: Re: [PATCH v29 1/4] rust: leds: Add basic led classdev abstractions
Date: Thu, 03 Dec 2026 22:02:35 +0000	[thread overview]
Message-ID: <sashiko-outbox-248723@kernel.org> (raw)
In-Reply-To: <20261203-rust_leds-v29-1-dc8a8ccb96d7@posteo.de>

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [High] rust: leds: missing kCFI cfi_encoding for enum led_brightness
  in callbacks
- [High] rust: leds: double-put of software_node fwnode in
  PinnedDrop::drop()
- [Medium] rust: leds: safe DeviceBuilder::build() allows UAF via
  core::mem::forget()
- [Medium] rust: leds: aliased mutable references in
  Adapter::blink_set_callback()
- [Low] rust: leds: T::MAX_BRIGHTNESS checks mismatch runtime
  max_brightness overrides
- [Low] rust: leds: DeviceBuilder typestate allows invalid states and
  drops errors
- [Low] rust: leds: missing inline on Color::try_from() and
  Device::deref()
--

commit 3198ee5b6a5df02b501695f833e966524250cb17
Author: Markus Probst <markus.probst@posteo.de>

rust: leds: Add basic led classdev abstractions

This commit adds basic Rust abstractions for LED class devices, including
the LedOps trait, DeviceBuilder, and the Device wrapper around struct
led_classdev.

> diff --git a/rust/kernel/led.rs b/rust/kernel/led.rs
> new file mode 100644
> index 0000000000000..e21b81e863cbe
> --- /dev/null
> +++ b/rust/kernel/led.rs

[ ... ]

> +impl<S: DeviceBuilderState> DeviceBuilder<'static, S> {
> +    /// Creates a new [`DeviceBuilder`].
> +    #[inline]
> +    #[expect(
> +        clippy::new_without_default,
> +        reason = "no need and derive is prevented by S"
> +    )]
> +    pub fn new() -> Self {
> +        Self {
> +            fwnode: None,
> +            name: None,
> +            devicename: None,
> +            devname_mandatory: false,
> +            initial_brightness: 0,
> +            color: Color::default(),
> +            _p: PhantomData,
> +        }
> +    }
> +}
> +
> +impl<'init> DeviceBuilder<'init, Unnamed> {
> +    /// Sets the firmware node.
> +    #[inline]
> +    pub fn fwnode(self, fwnode: Option<ARef<FwNode>>) -> Self {
> +        Self { fwnode, ..self }
> +    }

[Severity: Low]
Can DeviceBuilder::<Named>::new() without calling name() or
DeviceBuilder::<Unnamed>::new() with fwnode set to None ever succeed?
Because DeviceBuilder::build() always sets default_label to NULL,
led_compose_name() returns -EINVAL when both fwnode and default_label are
NULL; taking the required name or ARef<FwNode> in the constructors would
enforce this at compile time.

Also, hardcoding 'static on DeviceBuilder::new() instead of 'init prevents
passing a non-'static &'init CStr to name() or devicename() on a local
builder variable.  In addition, Adapter::brightness_set_callback() silently
discards errors returned by LedOps::brightness_set() when BLOCKING is false,
which is not documented on LedOps.

[ ... ]

> +impl TryFrom<u32> for Color {
> +    type Error = zerocopy::ValidityError<u32, Color>;
> +
> +    fn try_from(value: u32) -> core::result::Result<Self, Self::Error> {
> +        try_transmute!(value)
> +    }
> +}

[Severity: Low]
This isn't a bug, but Color::try_from() here and Device::deref() in
rust/kernel/led/normal.rs are single-expression kernel crate methods missing
#[inline].  In addition, struct Device in rust/kernel/led/normal.rs lacks an
# Invariants doc section (and matching // INVARIANT: comments in
DeviceBuilder::build()) for the registration and validity invariants relied
on by PinnedDrop::drop().

> diff --git a/rust/kernel/led/normal.rs b/rust/kernel/led/normal.rs
> new file mode 100644
> index 0000000000000..a22c29cfd2628
> --- /dev/null
> +++ b/rust/kernel/led/normal.rs

[ ... ]

> +impl<'init, S: DeviceBuilderState> DeviceBuilder<'init, S> {
> +    /// Registers a new [`Device`].
> +    pub fn build<'bound: 'init, T: LedOps + 'bound>(
> +        self,
> +        parent: &'bound device::Device<Bound>,
> +        ops: impl PinInit<T, Error> + 'init,
> +    ) -> impl PinInit<Device<'bound, T>, Error> + 'init {

[Severity: Medium]
Can a safe caller trigger a use-after-free or NULL pointer dereference by
leaking the returned Device<'bound, T> with core::mem::forget()?

DeviceBuilder::build() is a safe function that registers led_classdev
directly with led_classdev_register_ext() without devres cleanup, relying on
PinnedDrop::drop() to call led_classdev_unregister().  Leaking a heap-pinned
Device<'bound, T> via core::mem::forget() is safe in Rust and leaves the
classdev registered after 'bound ends or parent unbinds, so subsequent C
callbacks dereference dangling 'bound references in ops and led_module_get()
dereferences a NULL parent->driver->owner.  Marking build() unsafe with a
no-forget contract (like MiscDeviceRegistration::register()) or tying
unregistration to devres would close this hole.

> +        const_assert!(T::MAX_BRIGHTNESS <= i32::MAX.unsigned_abs() || !T::HAS_BRIGHTNESS_GET);

[Severity: Low]
Does this compile-time check match the runtime led_cdev->max_brightness
after led_classdev_register_ext() runs?

led_classdev_register_ext() overwrites led_cdev->max_brightness from the
fwnode "max-brightness" property without clamping to T::MAX_BRIGHTNESS or
i32::MAX, and replaces 0 with LED_FULL (255).  As a result, brightness_set()
can receive values above T::MAX_BRIGHTNESS, a firmware value above i32::MAX
causes brightness_get_callback() to fail with -EINVAL, and
debug_assert!(*val <= T::MAX_BRIGHTNESS) in brightness_get_callback() can
panic under CONFIG_RUST_DEBUG_ASSERTIONS=y when returning a value valid for
(*led_cdev).max_brightness.

[ ... ]

> +    unsafe extern "C" fn brightness_set_callback(
> +        led_cdev: *mut bindings::led_classdev,
> +        brightness: u32,
> +    ) {

[ ... ]

> +    unsafe extern "C" fn brightness_set_blocking_callback(
> +        led_cdev: *mut bindings::led_classdev,
> +        brightness: u32,
> +    ) -> i32 {

[ ... ]

> +    unsafe extern "C" fn brightness_get_callback(led_cdev: *mut bindings::led_classdev) -> u32 {

[Severity: High]
Will these callbacks trigger a kCFI panic on CONFIG_CFI_CLANG=y kernels?

In include/linux/leds.h, struct led_classdev declares brightness_set,
brightness_set_blocking, and brightness_get with enum led_brightness, which
Clang encodes by enum tag name rather than as u32.  Because led_brightness
is not declared in rust/bindgen_parameters with --newtype-enum and
#[cfi_encoding="14led_brightness"] and these callbacks use raw u32, every
indirect call from the C LED core (including led_update_brightness() during
registration or sysfs reads) will fail the kCFI check and trap.

[ ... ]

> +    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) };
> +
> +            classdev.blink_set(
> +                // 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 },
> +            )?;
> +            Ok(0)
> +        })
> +    }

[Severity: Medium]
Are delay_on and delay_off actually exclusive when blink_set_callback() is
called?

In drivers/leds/trigger/ledtrig-timer.c, led_delay_on_store() calls
led_blink_set(led_cdev, &state, &led_cdev->blink_delay_off) without holding
any per-LED lock, and led_blink_setup() invokes led_cdev->blink_set()
directly.  Because kernfs_fop_write_iter() only serializes per open file
description, two concurrent writes to delay_on on separate file descriptors
reach blink_set_callback() together and construct aliasing &mut usize
references to led_cdev->blink_delay_off, causing Rust aliasing and data-race
undefined behavior.

[ ... ]

> +#[pinned_drop]
> +impl<'bound, T: '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::DeviceBuilder::build`.
> +            .map(|fwnode| unsafe { ARef::from_raw(NonNull::from(fwnode)) });
> +
> +        // 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) };
> +    }
> +}

[Severity: High]
Does this double-put a software_node fwnode and cause a use-after-free on
unregister?

In drivers/leds/led-class.c, led_classdev_register_ext() calls
device_create_with_groups() before device_set_node(led_cdev->dev,
init_data->fwnode), so software_node_notify() runs while dev->fwnode is
still NULL and does not call swnode_get().  DeviceBuilder::build() therefore
leaves only the single forgotten ARef<FwNode> reference on swnode.

When Device is dropped, led_classdev_unregister() calls
device_unregister() -> device_del() -> software_node_notify_remove(), which
sees the populated dev->fwnode and calls swnode_put().  Dropping _fwnode at
the end of PinnedDrop::drop() then calls fwnode_handle_put() -> swnode_put()
a second time, underflowing the refcount and freeing the still-registered
software node via software_node_release().

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203-rust_leds-v29-0-dc8a8ccb96d7@posteo.de?part=1

  reply	other threads:[~2026-12-03 22:02 UTC|newest]

Thread overview: 8+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 21:38 [PATCH v29 0/4] rust: leds: Add led classdev abstractions Markus Probst
2026-12-03 21:38 ` [PATCH v29 1/4] rust: leds: Add basic " Markus Probst
2026-12-03 22:02   ` sashiko-bot [this message]
2026-12-03 21:38 ` [PATCH v29 2/4] rust: leds: Add Mode trait Markus Probst
2026-12-03 21:38 ` [PATCH v29 3/4] rust: leds: Add multicolor classdev abstractions Markus Probst
2026-12-03 22:00   ` sashiko-bot
2026-12-03 21:38 ` [PATCH v29 4/4] MAINTAINERS: rust: leds: Add rust abstraction entry Markus Probst
2026-12-03 22:02 ` [PATCH v29 0/4] rust: leds: Add led classdev abstractions sashiko-bot

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-248723@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=gary@garyguo.net \
    --cc=lee@kernel.org \
    --cc=linux-leds@vger.kernel.org \
    --cc=linux-pci@vger.kernel.org \
    --cc=markus.probst@posteo.de \
    --cc=ojeda@kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox