mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH 0/4] rust: wmi: add MVP of WMI abstractions
@ 2026-11-22  4:28 Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
                   ` (3 more replies)
  0 siblings, 4 replies; 5+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-22  4:28 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Armin Wolf
  Cc: Ilpo Järvinen, linux-kernel, rust-for-linux,
	platform-driver-x86, Nick Dowsett

Hi there; new to the LKML here, long time Rustacean and Linux user.

I have implemented this series to add an MVP of Rust abstractions for the
WMI subsystem with the bare-minimum implemented to support an in-tree
user, a Clevo laptop keyboard backlight driver
(`https://github.com/nick42d/linux/pull/4`).

Patches to follow for the driver. Note it has two other dependencies:
Markus Probst's LED classdev abstractions (v28) and basic DMI matching
abstractions.

This was not directly influenced by Ilya Gladyshev's previous attempt as
I was not aware of it, upon review, the key difference is that I have
used the newer buffer-based interface (no `acpi_object`), and implemented
less functionality/callbacks.

What's covered is driver probe, registration and unregistration, device
id table, and a safe implementation of `wmidev_invoke_method` that
returns an owned RAII buffer.

Signed-off-by: Nick Dowsett <nick42d@gmail.com>
---
Nick Dowsett (4):
      rust: wmi: add basic WMI device abstraction
      rust: wmi: add DeviceId and wmi_device_table! macro
      rust: wmi: add Driver trait, Adapter and implement RegistrationOps
      rust: wmi: add Buffer and Device::invoke_method()

 MAINTAINERS                     |   1 +
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/lib.rs              |   2 +
 rust/kernel/wmi.rs              | 361 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 365 insertions(+)
---
base-commit: 4843f6873f7c4835e62f2c73ba0fd538e57a2f22
change-id: 20261119-rust-wmi-c6b0e0fe97a7

Best regards,
--  
Nick Dowsett <nick42d@gmail.com>



^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH 1/4] rust: wmi: add basic WMI device abstraction
  2026-11-22  4:28 [PATCH 0/4] rust: wmi: add MVP of WMI abstractions Nick Dowsett via B4 Relay
@ 2026-11-22  4:28 ` Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 2/4] rust: wmi: add DeviceId and wmi_device_table! macro Nick Dowsett via B4 Relay
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 5+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-22  4:28 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Armin Wolf
  Cc: Ilpo Järvinen, linux-kernel, rust-for-linux,
	platform-driver-x86, Nick Dowsett

From: Nick Dowsett <nick42d@gmail.com>

- Adds the `kernel::wmi` module
- Exposes `linux/wmi.h` to bindgen.
- Adds `rust/kernel/wmi.rs` to MAINTAINERS.
- Implements `wmi::Device<Ctx>` wrapper around `struct wmi_device`.

Signed-off-by: Nick Dowsett <nick42d@gmail.com>
---
 MAINTAINERS                     |  1 +
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/lib.rs              |  2 +
 rust/kernel/wmi.rs              | 89 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 93 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 44540a1eb2b8..f58a44003d78 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -422,6 +422,7 @@ F:	Documentation/driver-api/wmi.rst
 F:	Documentation/wmi/
 F:	drivers/platform/wmi/
 F:	include/uapi/linux/wmi.h
+F:	rust/kernel/wmi.rs
 
 ACRN HYPERVISOR SERVICE MODULE
 M:	Fei Li <fei1.li@intel.com>
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 3791af0aadc7..81652d0dfed1 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -94,6 +94,7 @@
 #include <linux/tracepoint.h>
 #include <linux/usb.h>
 #include <linux/wait.h>
+#include <linux/wmi.h>
 #include <linux/workqueue.h>
 #include <linux/xarray.h>
 #include <net/genetlink.h>
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 1ab41129d557..b9713bd16313 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -147,6 +147,8 @@
 pub mod uaccess;
 #[cfg(CONFIG_USB = "y")]
 pub mod usb;
+#[cfg(CONFIG_ACPI_WMI = "y")]
+pub mod wmi;
 pub mod workqueue;
 pub mod xarray;
 
diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
new file mode 100644
index 000000000000..5f1d8c9803d6
--- /dev/null
+++ b/rust/kernel/wmi.rs
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Abstractions for WMI.
+//!
+//! C header: [`include/linux/wmi.h`](srctree/include/linux/wmi.h)
+
+use crate::{
+    bindings,
+    device,
+    sync::aref::AlwaysRefCounted,
+    types::Opaque, //
+};
+use core::{
+    marker::PhantomData,
+    ptr::NonNull, //
+};
+
+/// A WMI bus device ([`struct wmi_device`]).
+///
+/// # Invariants
+/// - `Device` wraps an in-place `Opaque<bindings::wmi_device>` allocated and always
+///   reference-counted in a thread-safe way by the C subsystem.
+/// - Instances are never constructed or moved by value in Rust, they are only accessed behind
+///   `&Device<Ctx>` or `ARef<Device<device::Normal>>`.
+///
+/// [`struct wmi_device`]: srctree/include/linux/wmi.h
+#[repr(transparent)]
+pub struct Device<Ctx: device::DeviceContext = device::Normal> {
+    ptr: Opaque<bindings::wmi_device>,
+    _marker: PhantomData<Ctx>,
+}
+
+// SAFETY: `Device<Ctx>` is a transparent wrapper of `Opaque<bindings::wmi_device>` whose
+// representation does not depend on `Ctx`.
+crate::impl_device_context_deref!(unsafe { Device });
+crate::impl_device_context_into_aref!(Device);
+
+// SAFETY: By the invariant, `Device<Normal>` is never moved by value in Rust.
+// If sent to another thread as `ARef<Device<Normal>>`, the reference-counting
+// is performed in a thread-safe way.
+unsafe impl Send for Device<device::Normal> {}
+
+// SAFETY:
+// - All that `&Device<Normal>` can do is increment its reference count (thread-safe)
+// and perform a reference conversion to `&device::Device<Normal>`.
+// - All methods on `&device::Device<Normal>` are thread safe.
+unsafe impl Sync for Device<device::Normal> {}
+
+// SAFETY:
+// - By the type invariant, all instances of `Device` are reference-counted.
+// - Increments to the reference count keep the object alive in memory at least
+//   until matching decrements (`dec_ref` via `put_device`) are performed.
+unsafe impl AlwaysRefCounted for Device<device::Normal> {
+    fn inc_ref(&self) {
+        self.as_ref().inc_ref();
+    }
+    unsafe fn dec_ref(obj: NonNull<Self>) {
+        // CAST: `Device` is a `#[repr(transparent)]` wrapper of `Opaque<bindings::wmi_device>`.
+        let wdev: *mut bindings::wmi_device = obj.cast().as_ptr();
+        // SAFETY:
+        // - The safety requirements of `dec_ref` guarantee that `obj` is a valid pointer with a
+        //   non-zero reference count.
+        // - `put_device` safely decrements the refcount and triggers release cleanup when it
+        //   reaches 0.
+        unsafe { bindings::put_device(&raw mut (*wdev).dev) };
+    }
+}
+impl<Ctx: device::DeviceContext> Device<Ctx> {
+    /// Returns the raw pointer to the underlying `bindings::wmi_device`.
+    fn as_raw(&self) -> *mut bindings::wmi_device {
+        self.ptr.get()
+    }
+}
+
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
+    fn as_ref(&self) -> &device::Device<Ctx> {
+        // SAFETY:
+        // - By the type invariant on `Device<Ctx>`, `self.as_raw()` is a valid pointer to
+        //   a `wmi_device which embeds a `device`.
+        // - If you have a reference to a `Device<Ctx>`, then the reference count must be
+        //   non-zero.
+        // - If you have a reference to a `Device<Ctx>`, it is either:
+        //   - Borrowed from an `ARef<Device<Normal>>` that cannot be dropped and decrement
+        //     reference count to zero whilst the reference is held.
+        //   - Derived from a scope (such as a callback) that guarantees that reference count
+        //     will not be reduced to zero whilst that reference is held.
+        unsafe { device::Device::from_raw(&raw mut (*self.as_raw()).dev) }
+    }
+}

-- 
2.56.1



^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH 2/4] rust: wmi: add DeviceId and wmi_device_table! macro
  2026-11-22  4:28 [PATCH 0/4] rust: wmi: add MVP of WMI abstractions Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
@ 2026-11-22  4:28 ` Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay
  3 siblings, 0 replies; 5+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-22  4:28 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Armin Wolf
  Cc: Ilpo Järvinen, linux-kernel, rust-for-linux,
	platform-driver-x86, Nick Dowsett

From: Nick Dowsett <nick42d@gmail.com>

- Add `wmi::DeviceId` wrapping `struct wmi_device_id`.

- Implements `wmi::IdTable` and the `wmi_device_table!` macro.

Signed-off-by: Nick Dowsett <nick42d@gmail.com>
---
 rust/kernel/wmi.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)

diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
index 5f1d8c9803d6..494797fdbf68 100644
--- a/rust/kernel/wmi.rs
+++ b/rust/kernel/wmi.rs
@@ -7,6 +7,8 @@
 use crate::{
     bindings,
     device,
+    device_id::RawDeviceId,
+    prelude::*,
     sync::aref::AlwaysRefCounted,
     types::Opaque, //
 };
@@ -15,6 +17,61 @@
     ptr::NonNull, //
 };
 
+/// IdTable type for WMI drivers.
+pub type IdTable = &'static dyn crate::device_id::IdTable<DeviceId, ()>;
+
+/// A WMI device ID wrapping [`struct wmi_device_id`].
+///
+/// [`struct wmi_device_id`]: srctree/include/linux/device-id/wmi.h
+///
+/// # Invariants
+/// `self.0.guid_string` is a valid, null-terminated string of length [`bindings::UUID_STRING_LEN`].
+#[repr(transparent)]
+#[derive(Clone, Copy)]
+pub struct DeviceId(bindings::wmi_device_id);
+// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `wmi_device_id`.
+// `wmi_device_id` does not have any invariants, so it's safe to transmute to it.
+unsafe impl RawDeviceId for DeviceId {
+    type RawType = bindings::wmi_device_id;
+}
+impl DeviceId {
+    const WMI_UUID_LEN: usize = crate::num::casts::u32_as_usize(bindings::UUID_STRING_LEN);
+    /// Creates a new [`DeviceId`].
+    ///
+    /// Fails at compile time if `guid.len()` is not [`bindings::UUID_STRING_LEN`].
+    #[inline(always)]
+    pub const fn new(guid: &'static CStr) -> Self {
+        let src = guid.to_bytes_with_nul();
+        // NOTE: Function is marked `#[inline(always)]` to help compiler optimise the error path.
+        build_assert!(
+            src.len() == Self::WMI_UUID_LEN + 1,
+            "WMI DeviceId length incorrect"
+        );
+        let mut id: bindings::wmi_device_id = pin_init::zeroed();
+        // TODO: Upgrade to core::slice::copy_from_slice(src) once rustc>=1.87
+        let mut i = 0;
+        while i < src.len() {
+            id.guid_string[i] = src[i];
+            i += 1;
+        }
+        Self(id)
+    }
+}
+
+/// Create a WMI [`IdTable`] with an "alias" for modpost.
+#[macro_export]
+macro_rules! wmi_device_table {
+    ($table_name:ident, [$($id:expr),* $(,)?]) => {
+        $crate::module_device_table!(
+            "wmi",
+            $crate::wmi::DeviceId,
+            $table_name,
+            @none,
+            [$($id),*]
+        );
+    };
+}
+
 /// A WMI bus device ([`struct wmi_device`]).
 ///
 /// # Invariants

-- 
2.56.1



^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps
  2026-11-22  4:28 [PATCH 0/4] rust: wmi: add MVP of WMI abstractions Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 2/4] rust: wmi: add DeviceId and wmi_device_table! macro Nick Dowsett via B4 Relay
@ 2026-11-22  4:28 ` Nick Dowsett via B4 Relay
  2026-11-22  4:28 ` [PATCH 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay
  3 siblings, 0 replies; 5+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-22  4:28 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Armin Wolf
  Cc: Ilpo Järvinen, linux-kernel, rust-for-linux,
	platform-driver-x86, Nick Dowsett

From: Nick Dowsett <nick42d@gmail.com>

- Implements the `wmi::Driver` trait.
- Adds adapter implementing `driver::DriverLayout` and
  `driver::RegistrationOps` - `wmi::Adapter<T: Driver>`.
- Adds `wmi::Registration<T>` type alias for convenience.

Signed-off-by: Nick Dowsett <nick42d@gmail.com>
---
 rust/kernel/wmi.rs | 123 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 121 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
index 494797fdbf68..09712cbc1c93 100644
--- a/rust/kernel/wmi.rs
+++ b/rust/kernel/wmi.rs
@@ -8,15 +8,134 @@
     bindings,
     device,
     device_id::RawDeviceId,
+    driver,
+    error,
     prelude::*,
     sync::aref::AlwaysRefCounted,
-    types::Opaque, //
+    types::Opaque,
+    ThisModule, //
 };
 use core::{
     marker::PhantomData,
     ptr::NonNull, //
 };
 
+/// Type alias for [`driver::Registration<Adapter<T>>`], the registration of
+/// a WMI driver wrapping a [`struct wmi_driver`].
+///
+/// When this struct is dropped the driver will be unregistered.
+///
+/// [`struct wmi_driver`]: srctree/include/linux/wmi.h
+pub type Registration<T> = driver::Registration<Adapter<T>>;
+
+/// WMI driver trait.
+///
+/// Drivers must implement this trait in order to register a WMI driver.
+///
+/// # Examples
+///
+/// ```
+/// # use kernel::{device::Core, prelude::*, wmi};
+/// struct MyDriver;
+///
+/// kernel::wmi_device_table!(
+///     MY_DRIVER_WMI_TABLE,
+///     [wmi::DeviceId::new(c"00000000-0000-0000-0000-000000000000")]
+/// );
+///
+/// impl wmi::Driver for MyDriver {
+///     type Data<'bound> = Self;
+///     const ID_TABLE: wmi::IdTable = &MY_DRIVER_WMI_TABLE;
+///
+///     fn probe<'bound>(
+///         _dev: &'bound wmi::Device<Core<'_>>,
+///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+///         Err(ENODEV)
+///     }
+/// }
+/// ```
+pub trait Driver {
+    /// The type of the driver's bus device private data.
+    type Data<'bound>: Send + 'bound;
+    /// The table of WMI device IDs supported by the driver.
+    const ID_TABLE: IdTable;
+    /// The `probe` callback is called when the WMI driver is bound to a matching WMI device.
+    /// Allocating driver-specific data structures and initializing interfaces to other kernel
+    /// subsystems should normally be done in this function.
+    fn probe<'bound>(
+        dev: &'bound Device<device::Core<'_>>,
+    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
+}
+
+/// Adapter to allow [`Driver`] to be used with [`driver::Registration`].
+pub struct Adapter<T: Driver>(T);
+
+// SAFETY:
+// - `wmi_driver` is a C struct.
+// - Since `T` is a driver, `T::Data` is by definition the type of its
+//   device private data.
+// - `wmi_driver` embeds a `device_driver` at offset `DEVICE_DRIVER_OFFSET`
+//   as per `core::mem::offset_of!()`.
+unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
+    type DriverType = bindings::wmi_driver;
+    type DriverData<'bound> = T::Data<'bound>;
+    const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
+}
+
+// SAFETY: It's always valid to unregister a registered `wmi_driver`.
+unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
+    unsafe fn register(
+        reg: &Opaque<Self::DriverType>,
+        name: &'static CStr,
+        module: &'static ThisModule,
+    ) -> Result {
+        // SAFETY:
+        // - It's safe to set the fields of `wmi_driver` on initialization.
+        // - All set fields meet the invariants of `wmi_driver`.
+        unsafe {
+            (*reg.get()).driver.name = name.as_char_ptr();
+            // SAFETY: This callback will only be called with a pointer to a `wmi_device`
+            // valid for the lifetime of the callback.
+            (*reg.get()).probe = Some(Self::probe_callback);
+            (*reg.get()).id_table = T::ID_TABLE.as_ptr();
+            (*reg.get()).no_singleton = true;
+        }
+
+        // SAFETY: `reg` is a valid `wmi_driver`.
+        error::to_result(unsafe { bindings::__wmi_driver_register(reg.get(), module.as_ptr()) })
+    }
+    unsafe fn unregister(wdrv: &Opaque<Self::DriverType>) {
+        // SAFETY: `wdrv` is a valid `wmi_driver` previously registered with `register()`.
+        unsafe { bindings::wmi_driver_unregister(wdrv.get()) };
+    }
+}
+
+impl<T: Driver> Adapter<T> {
+    /// C wrapper for [`Driver::probe`] function to use it as a C function pointer.
+    ///
+    /// # Safety
+    /// - The caller must ensure that `wdev` is a pointer to a `wmi_device` valid for
+    ///   the lifetime of the callback.
+    unsafe extern "C" fn probe_callback(
+        wdev: *mut bindings::wmi_device,
+        _context: *const c_void,
+    ) -> c_int {
+        // SAFETY:
+        // - As per the safety requirement for the function, `wdev` is a pointer to a
+        //   `struct wmi_device` valid for the lifetime of the callback.
+        //   This is the definition of the Core and CoreInternal marker lifetime.
+        // - `Device` is `#[repr(transparent)]` over `struct wmi_device`.
+        let wdev = unsafe { &*wdev.cast::<Device<device::CoreInternal<'_>>>() };
+        let data = T::probe(wdev);
+        // As per the C driver subsystem documentation, the return type of a driver
+        // probe callback is 0 on success or a kernel error code on failure.
+        error::from_result(|| {
+            wdev.as_ref().set_drvdata(data)?;
+            Ok(0)
+        })
+    }
+}
+
 /// IdTable type for WMI drivers.
 pub type IdTable = &'static dyn crate::device_id::IdTable<DeviceId, ()>;
 
@@ -133,7 +252,7 @@ impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
     fn as_ref(&self) -> &device::Device<Ctx> {
         // SAFETY:
         // - By the type invariant on `Device<Ctx>`, `self.as_raw()` is a valid pointer to
-        //   a `wmi_device which embeds a `device`.
+        //   a `wmi_device` which embeds a `device`.
         // - If you have a reference to a `Device<Ctx>`, then the reference count must be
         //   non-zero.
         // - If you have a reference to a `Device<Ctx>`, it is either:

-- 
2.56.1



^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH 4/4] rust: wmi: add Buffer and Device::invoke_method()
  2026-11-22  4:28 [PATCH 0/4] rust: wmi: add MVP of WMI abstractions Nick Dowsett via B4 Relay
                   ` (2 preceding siblings ...)
  2026-11-22  4:28 ` [PATCH 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
@ 2026-11-22  4:28 ` Nick Dowsett via B4 Relay
  3 siblings, 0 replies; 5+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-22  4:28 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Armin Wolf
  Cc: Ilpo Järvinen, linux-kernel, rust-for-linux,
	platform-driver-x86, Nick Dowsett

From: Nick Dowsett <nick42d@gmail.com>

- Adds safe \`wmi::Buffer\` RAII abstraction wrapping an owned

  \`struct wmi_buffer\`.

- Implement \`Device::invoke_method()\` - safe abstraction for

  \`wmidev_invoke_method\`.

- Also implement \`Sync\` for \`Device<device::Bound>\`.

Signed-off-by: Nick Dowsett <nick42d@gmail.com>
---
 rust/kernel/wmi.rs | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 97 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
index 09712cbc1c93..d97c8cb7cbf7 100644
--- a/rust/kernel/wmi.rs
+++ b/rust/kernel/wmi.rs
@@ -17,7 +17,9 @@
 };
 use core::{
     marker::PhantomData,
-    ptr::NonNull, //
+    ops::Deref,
+    ptr::NonNull,
+    slice, //
 };
 
 /// Type alias for [`driver::Registration<Adapter<T>>`], the registration of
@@ -222,6 +224,11 @@ unsafe impl Send for Device<device::Normal> {}
 // - All methods on `&device::Device<Normal>` are thread safe.
 unsafe impl Sync for Device<device::Normal> {}
 
+// SAFETY:
+// - As per `&Device<Normal>`, but `&Device<Bound>` also has the method `invoke_method()`,
+//   which wraps the internally synchronised `bindings::wmidev_invoke_method()`.
+unsafe impl Sync for Device<device::Bound> {}
+
 // SAFETY:
 // - By the type invariant, all instances of `Device` are reference-counted.
 // - Increments to the reference count keep the object alive in memory at least
@@ -248,6 +255,70 @@ fn as_raw(&self) -> *mut bindings::wmi_device {
     }
 }
 
+impl Device<device::Bound> {
+    /// Calls `wmidev_invoke_method`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{device::Bound, prelude::*, wmi};
+    /// const METHOD_ID: u32 = 0xB105;
+    /// const METHOD_ARGS: [u8; 1] = [0];
+    /// fn method_returning_u32(wdev: &wmi::Device<Bound>) -> Result<u32> {
+    ///     let output: wmi::Buffer = wdev
+    ///         .invoke_method(0, METHOD_ID, &METHOD_ARGS, size_of::<u32>())?;
+    ///     let output_as_bytes: [u8; 4] = output
+    ///         .get(..size_of::<u32>())
+    ///         .and_then(|buf| buf.try_into().ok())
+    ///         .ok_or(ENODATA)?;
+    ///     let output_u32 = u32::from_le_bytes(output_as_bytes);
+    ///     dev_dbg!(wdev.as_ref(), "WMI output: {}\n", output_u32);
+    ///     Ok(output_u32)
+    /// }
+    /// ```
+    pub fn invoke_method(
+        &self,
+        instance: u8,
+        method_id: u32,
+        input: &[u8],
+        min_output_size: usize,
+    ) -> Result<Buffer> {
+        let mut out_buf = bindings::wmi_buffer::default();
+        let in_buf = bindings::wmi_buffer {
+            length: input.len(),
+            // NOTE1: Even if the input slice is empty, this will create a dangling pointer
+            // rather than a null pointer as Rust references are always non-null.
+            // NOTE2: The input parameter to wmidev_invoke_method is expected to be read-only,
+            // however, we cast to a mutable pointer here purely to meet the type definition of
+            // `wmi_buffer`.
+            data: input.as_ptr().cast_mut().cast::<c_void>(),
+        };
+        // SAFETY:
+        // - By type invariants, `self.as_raw()` points to a valid, live `wmi_device`.
+        // - `out_buf` and `in_buf` are pointers to valid, live `wmi_buffer`s.
+        // - `in_buf` contains a pointer to an allocation behind a Rust reference (which therefore
+        //   lives as long as this method call) with length less than or equal to the allocation
+        //   size, or contains a dangling pointer with length 0.
+        // - The allocation in `in_buf` will not be mutated - the C implementation declares the in
+        //   parameter as const.
+        let status = unsafe {
+            bindings::wmidev_invoke_method(
+                self.as_raw(),
+                instance,
+                method_id,
+                &raw const in_buf,
+                &raw mut out_buf,
+                min_output_size,
+            )
+        };
+        error::to_result(status)?;
+
+        // On success, `wmidev_invoke_method` returns a `wmi_buffer`
+        // satisfying `Buffer`'s invariants, which we hand to the caller as the
+        // new owner.
+        Ok(Buffer(out_buf))
+    }
+}
 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
     fn as_ref(&self) -> &device::Device<Ctx> {
         // SAFETY:
@@ -263,3 +334,28 @@ fn as_ref(&self) -> &device::Device<Ctx> {
         unsafe { device::Device::from_raw(&raw mut (*self.as_raw()).dev) }
     }
 }
+
+/// An owned, 8-byte aligned output buffer.
+///
+/// # Invariants
+/// - `self.0.data` is a pointer to an 8-byte aligned owned buffer of length
+///   at least `self.0.length` and freeable with `kfree()`.
+pub struct Buffer(bindings::wmi_buffer);
+impl Deref for Buffer {
+    type Target = [u8];
+    fn deref(&self) -> &[u8] {
+        if self.0.length == 0 {
+            return &[];
+        }
+        // SAFETY: By the type invariant, `self.0.length != 0` guarantees `self.0.data`
+        // points to an owned buffer of length at least `self.0.length`.
+        unsafe { slice::from_raw_parts(self.0.data.cast::<u8>(), self.0.length) }
+    }
+}
+impl Drop for Buffer {
+    fn drop(&mut self) {
+        // SAFETY: By the type invariant, `self.0.data` is exclusively owned and
+        // freeable with `kfree()`.
+        unsafe { bindings::kfree(self.0.data) };
+    }
+}

-- 
2.56.1



^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2026-11-22  4:28 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-22  4:28 [PATCH 0/4] rust: wmi: add MVP of WMI abstractions Nick Dowsett via B4 Relay
2026-11-22  4:28 ` [PATCH 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
2026-11-22  4:28 ` [PATCH 2/4] rust: wmi: add DeviceId and wmi_device_table! macro Nick Dowsett via B4 Relay
2026-11-22  4:28 ` [PATCH 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
2026-11-22  4:28 ` [PATCH 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®