Rust for Linux List
 help / color / mirror / Atom feed
* [PATCH v2 0/4] rust: wmi: add ACPI WMI bus abstractions
@ 2026-11-27 11:02 Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
                   ` (3 more replies)
  0 siblings, 4 replies; 9+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-27 11:02 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: 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 (`include/linux/wmi.h`) with the bare-minimum
implemented to support an in-tree user, a Clevo laptop keyboard
backlight driver [1].

Note the driver has two other dependencies: Markus Probst's LED
classdev abstractions and basic DMI matching abstractions.

[1] https://lore.kernel.org/all/20261122-clevo-laptop-v1-0-881debf4d4b0@gmail.com/

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

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.

---
Changes in v2:
- Add inline annotations (Sashiko)
- Add / standardise `// INVARIANT:` documentation (Sashiko).
- Additional comments documenting device construction state, expand
  abbreviation in module documentation, and fix typos.
- Rebased onto v7.4-rc4.
- Link to v1: https://patch.msgid.link/20261122-rust-wmi-v1-0-63111d9e824c@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              | 375 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 379 insertions(+)
---
base-commit: b6a9fa34ce4187cb69d3c588a4bbffc31ce5db8f
change-id: 20261119-rust-wmi-c6b0e0fe97a7

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



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

* [PATCH v2 1/4] rust: wmi: add basic WMI device abstraction
  2026-11-27 11:02 [PATCH v2 0/4] rust: wmi: add ACPI WMI bus abstractions Nick Dowsett via B4 Relay
@ 2026-11-27 11:02 ` Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 2/4] rust: wmi: add DeviceId and wmi_device_table! macro Nick Dowsett via B4 Relay
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 9+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-27 11:02 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: 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              | 93 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 97 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..f821bf35220e
--- /dev/null
+++ b/rust/kernel/wmi.rs
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Abstractions for WMI (Windows Management Instrumentation).
+//!
+//! 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> {
+    #[inline]
+    fn inc_ref(&self) {
+        self.as_ref().inc_ref();
+    }
+    #[inline]
+    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`.
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::wmi_device {
+        self.ptr.get()
+    }
+}
+
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
+    #[inline]
+    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 related	[flat|nested] 9+ messages in thread

* [PATCH v2 2/4] rust: wmi: add DeviceId and wmi_device_table! macro
  2026-11-27 11:02 [PATCH v2 0/4] rust: wmi: add ACPI WMI bus abstractions Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
@ 2026-11-27 11:02 ` Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay
  3 siblings, 0 replies; 9+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-27 11:02 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: 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!`.

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

diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
index f821bf35220e..f7fbde29177b 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,64 @@
     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;
+        }
+        // INVARIANT:
+        // - All bytes were copied from a Rust `&'static CStr`.
+        // - The build assert above guarantees `id` to meet the length invariant.
+        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 related	[flat|nested] 9+ messages in thread

* [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps
  2026-11-27 11:02 [PATCH v2 0/4] rust: wmi: add ACPI WMI bus abstractions Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
  2026-11-27 11:02 ` [PATCH v2 2/4] rust: wmi: add DeviceId and wmi_device_table! macro Nick Dowsett via B4 Relay
@ 2026-11-27 11:02 ` Nick Dowsett via B4 Relay
  2026-11-28 15:57   ` Armin Wolf
  2026-11-27 11:02 ` [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay
  3 siblings, 1 reply; 9+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-27 11:02 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: 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 | 127 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 125 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
index f7fbde29177b..235c4a2cef6a 100644
--- a/rust/kernel/wmi.rs
+++ b/rust/kernel/wmi.rs
@@ -8,15 +8,138 @@
     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 {
+            // SAFETY: `name` is valid for the static lifetime.
+            (*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);
+            // SAFETY: `T::ID_TABLE` is valid for the static lifetime.
+            (*reg.get()).id_table = T::ID_TABLE.as_ptr();
+            // Per the documentation, new WMI drivers should be allowed to be instantiated
+            // multiple times (see `Documentation/wmi/driver-development-guide.rst`).
+            (*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, ()>;
 
@@ -140,7 +263,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 related	[flat|nested] 9+ messages in thread

* [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method()
  2026-11-27 11:02 [PATCH v2 0/4] rust: wmi: add ACPI WMI bus abstractions Nick Dowsett via B4 Relay
                   ` (2 preceding siblings ...)
  2026-11-27 11:02 ` [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
@ 2026-11-27 11:02 ` Nick Dowsett via B4 Relay
  2026-11-28 16:05   ` Armin Wolf
  3 siblings, 1 reply; 9+ messages in thread
From: Nick Dowsett via B4 Relay @ 2026-11-27 11:02 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: 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 | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 100 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
index 235c4a2cef6a..3cd5bed6066f 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
@@ -229,6 +231,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
@@ -258,6 +265,71 @@ 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)
+    /// }
+    /// ```
+    #[inline]
+    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)?;
+
+        // INVARIANT: `wmidev_invoke_method` was confirmed to succeed. On success
+        // it 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> {
     #[inline]
     fn as_ref(&self) -> &device::Device<Ctx> {
@@ -274,3 +346,30 @@ 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];
+    #[inline]
+    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 {
+    #[inline]
+    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 related	[flat|nested] 9+ messages in thread

* Re: [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps
  2026-11-27 11:02 ` [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
@ 2026-11-28 15:57   ` Armin Wolf
  2026-11-29  1:32     ` Nick Dowsett
  0 siblings, 1 reply; 9+ messages in thread
From: Armin Wolf @ 2026-11-28 15:57 UTC (permalink / raw)
  To: nick42d, 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
  Cc: linux-kernel, rust-for-linux, platform-driver-x86

Am 27.11.26 um 12:02 schrieb Nick Dowsett via B4 Relay:

> 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 | 127 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
>   1 file changed, 125 insertions(+), 2 deletions(-)
>
> diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
> index f7fbde29177b..235c4a2cef6a 100644
> --- a/rust/kernel/wmi.rs
> +++ b/rust/kernel/wmi.rs
> @@ -8,15 +8,138 @@
>       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 {
> +            // SAFETY: `name` is valid for the static lifetime.
> +            (*reg.get()).driver.name = name.as_char_ptr();

Hi,

can drivers set driver.probe_type = PROBE_PREFER_ASYNCHRONOUS? If no then please
set it here is possible.

Thanks,
Armin Wolf

> +            // 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);
> +            // SAFETY: `T::ID_TABLE` is valid for the static lifetime.
> +            (*reg.get()).id_table = T::ID_TABLE.as_ptr();
> +            // Per the documentation, new WMI drivers should be allowed to be instantiated
> +            // multiple times (see `Documentation/wmi/driver-development-guide.rst`).
> +            (*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, ()>;
>   
> @@ -140,7 +263,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:
>

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

* Re: [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method()
  2026-11-27 11:02 ` [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay
@ 2026-11-28 16:05   ` Armin Wolf
  2026-11-29  3:08     ` Nick Dowsett
  0 siblings, 1 reply; 9+ messages in thread
From: Armin Wolf @ 2026-11-28 16:05 UTC (permalink / raw)
  To: nick42d, 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
  Cc: linux-kernel, rust-for-linux, platform-driver-x86

Am 27.11.26 um 12:02 schrieb Nick Dowsett via B4 Relay:

> 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 | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
>   1 file changed, 100 insertions(+), 1 deletion(-)
>
> diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs
> index 235c4a2cef6a..3cd5bed6066f 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
> @@ -229,6 +231,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
> @@ -258,6 +265,71 @@ 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)
> +    /// }
> +    /// ```
> +    #[inline]
> +    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)?;
> +
> +        // INVARIANT: `wmidev_invoke_method` was confirmed to succeed. On success
> +        // it 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> {
>       #[inline]
>       fn as_ref(&self) -> &device::Device<Ctx> {
> @@ -274,3 +346,30 @@ 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];
> +    #[inline]
> +    fn deref(&self) -> &[u8] {
> +        if self.0.length == 0 {
> +            return &[];
> +        }

Hi,

this might not be necessary, because an empty WMI buffer from the subsystem will
never contain NULL for .data, instead said field will be set to ZERO_SIZE_PTR.

> +        // 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 {
> +    #[inline]
> +    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) };
> +    }

This is wrong for WMI buffers used as input for wmidev_invoke_method(), because the data
might be statically allocated. I suggest that you keep struct wmi_buffer internal and
instead return a KBox<[u8]> from invoke_method().

IMHO struct wmi_buffer only exists because C does not define a standard slice type,
so there is no reason for exposing struct wmi_buffer as a separate public rust type.

Thanks,
Armin Wolf

> +}
>

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

* Re: [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps
  2026-11-28 15:57   ` Armin Wolf
@ 2026-11-29  1:32     ` Nick Dowsett
  0 siblings, 0 replies; 9+ messages in thread
From: Nick Dowsett @ 2026-11-29  1:32 UTC (permalink / raw)
  To: Armin Wolf, 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
  Cc: linux-kernel, rust-for-linux, platform-driver-x86

Hi Armin,

Thanks for taking a look. 

>> +// 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 {
>> +            // SAFETY: `name` is valid for the static lifetime.
>> +            (*reg.get()).driver.name = name.as_char_ptr();
>
> Hi,
>
> can drivers set driver.probe_type = PROBE_PREFER_ASYNCHRONOUS? If no then please
> set it here is possible.
>
> Thanks,
> Armin Wolf

At the moment I didn't wrap `probe_type` from `driver.h` so drivers are
not able to set this themselves. If I can confirm it's OK to use
`PROBE_PREFER_ASYNCHRONOUS` for the reference Clevo driver are you OK if
this is hardcoded here for now? If a future consumer of the binding has
this requirement they could add a new associated const to `wmi::Driver`
defaulting to 'prefer asynchronous' in line with the recommendation from
the wmi subsystem docs. 

Cheers Nick

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

* Re: [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method()
  2026-11-28 16:05   ` Armin Wolf
@ 2026-11-29  3:08     ` Nick Dowsett
  0 siblings, 0 replies; 9+ messages in thread
From: Nick Dowsett @ 2026-11-29  3:08 UTC (permalink / raw)
  To: Armin Wolf, 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
  Cc: linux-kernel, rust-for-linux, platform-driver-x86

Hi Armin,

>> +impl Deref for Buffer {
>> +    type Target = [u8];
>> +    #[inline]
>> +    fn deref(&self) -> &[u8] {
>> +        if self.0.length == 0 {
>> +            return &[];
>> +        }
>
> Hi,
>
> this might not be necessary, because an empty WMI buffer from the subsystem will
> never contain NULL for .data, instead said field will be set to ZERO_SIZE_PTR.

Good to know - thanks! Would you be open to me adding a doc comment in C
as part of this series to reflect this - or is it kind of implied already?
I'm not super experienced in C.

>> +impl Drop for Buffer {
>> +    #[inline]
>> +    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) };
>> +    }
>
> This is wrong for WMI buffers used as input for wmidev_invoke_method(), because the data
> might be statically allocated. I suggest that you keep struct wmi_buffer internal and
> instead return a KBox<[u8]> from invoke_method().
>
> IMHO struct wmi_buffer only exists because C does not define a standard slice type,
> so there is no reason for exposing struct wmi_buffer as a separate public rust type.
>
> Thanks,
> Armin Wolf

Note that the Rust implementation of `invoke_method()` actually takes a Rust
byte slice as input and converts it to a `struct wmi_buffer` internally,
so the `wmi::Buffer` type here was just to be used for the allocated return
type case.

It was my initial thinking to use KBox here, but some warnings from an LLM
steered me away from this. From my own research, for regular Rust Box types
it can be a bit of a safety minefield to convert from C types (see
https://doc.rust-lang.org/std/boxed/index.html#memory-layout) and I am
unsure if KBox is in the same boat. I also couldn't see anywhere else in the
kernel where we construct a KBox from a C type either. So my preference
for now is to keep this unless someone from R4L is able to advise otherwise.
If the naming is confusing because wmi_buffer is also used as input on C
side - would you prefer this to be named BufferOwned?

I agree that looked to be your intent so it would be very nice to return
KBox in future if possible! I was a bit surpised there isn't a generic C
slice type in the kernel btw and wmi has needed to define it itself.

Cheers Nick

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

end of thread, other threads:[~2026-11-29  3:08 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-27 11:02 [PATCH v2 0/4] rust: wmi: add ACPI WMI bus abstractions Nick Dowsett via B4 Relay
2026-11-27 11:02 ` [PATCH v2 1/4] rust: wmi: add basic WMI device abstraction Nick Dowsett via B4 Relay
2026-11-27 11:02 ` [PATCH v2 2/4] rust: wmi: add DeviceId and wmi_device_table! macro Nick Dowsett via B4 Relay
2026-11-27 11:02 ` [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps Nick Dowsett via B4 Relay
2026-11-28 15:57   ` Armin Wolf
2026-11-29  1:32     ` Nick Dowsett
2026-11-27 11:02 ` [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method() Nick Dowsett via B4 Relay
2026-11-28 16:05   ` Armin Wolf
2026-11-29  3:08     ` Nick Dowsett

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