rust: wmi: add ACPI WMI bus abstractions
Subsystems (2)
v2 cover rust: wmi: add ACPI WMI bus abstractions
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/[email protected]/
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/[email protected]
---
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,
Signature · 1 line
Nick Dowsett <[email protected]>
PATCH v2 1/4 rust: wmi: add basic WMI device abstraction
- 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.
--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/wmi.rs | 93 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 97 insertions(+)
MAINTAINERS +1 -0
@@ -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 <[email protected]>
rust/bindings/bindings_helper.h +1 -0
@@ -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>
rust/kernel/lib.rs +2 -0
@@ -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;
rust/kernel/wmi.rs new file +93 -0
93 lines not on this page · raw message
Signature · 1 line
2.56.1
PATCH v2 2/4 rust: wmi: add DeviceId and wmi_device_table! macro
In reply to Nick Dowsett- Add wmi::DeviceId wrapping struct wmi_device_id.
- Implements wmi::IdTable and the wmi_device_table!.
--- rust/kernel/wmi.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+)
rust/kernel/wmi.rs +60 -0
@@ -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 = &'staticdyn 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: &'staticCStr ) ->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
Signature · 1 line
2.56.1
PATCH v2 3/4 rust: wmi: add Driver trait, Adapter and implement RegistrationOps
In reply to Nick Dowsett- 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.
--- rust/kernel/wmi.rs | 127 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 125 insertions(+), 2 deletions(-)
rust/kernel/wmi.rs +125 -2
@@ -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: &'boundDevice <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: &'staticCStr , + module: &'staticThisModule , + ) ->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 = &'staticdyn 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:
Signature · 1 line
2.56.1
Re: [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps
Am 27.11.26 um 12:02 schrieb Nick Dowsett via B4 Relay:
Quoted 98 lines
From: Nick Dowsett <[email protected]>
- Implements the
wmi::Drivertrait.
- Adds adapter implementingdriver::DriverLayoutanddriver::RegistrationOps-wmi::Adapter<T: Driver>.
- Addswmi::Registration<T>type alias for convenience.Signed-off-by Nick Dowsett <[email protected]>--- rust/kernel/wmi.rs | 127 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 125 insertions(+), 2 deletions(-)rust/kernel/wmi.rs +69
-1@@ -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: &'boundDevice <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(
rust/kernel/wmi.rs line 97
Quoted 10 lines
rust/kernel/wmi.rs +10
-0+ 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
Quoted 58 lines
rust/kernel/wmi.rs +46
-1+// 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 = &'staticdyn 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:
Re: [PATCH v2 3/4] rust: wmi: add Driver trait, Adapter and implement RegistrationOps
Hi Armin,
Thanks for taking a look.
Quoted 16 lines
rust/kernel/wmi.rs line 97
Quoted 13 lines
rust/kernel/wmi.rs +13
-0+// 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: &'staticCStr , + module: &'staticThisModule , + ) ->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,
Quoted 5 lines
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
PATCH v2 4/4 rust: wmi: add Buffer and Device::invoke_method()
In reply to Nick Dowsett- 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>.
--- rust/kernel/wmi.rs | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-)
rust/kernel/wmi.rs +100 -1
@@ -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) }; + } +}
Signature · 1 line
2.56.1
Re: [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method()
Am 27.11.26 um 12:02 schrieb Nick Dowsett via B4 Relay:
Quoted 120 lines
From: Nick Dowsett <[email protected]>
- Adds safe
wmi::BufferRAII abstraction wrapping an ownedstruct wmi_buffer.
- ImplementDevice::invoke_method()- safe abstraction forwmidev_invoke_method.
- Also implementSyncforDevice<device::Bound>.Signed-off-by Nick Dowsett <[email protected]>--- rust/kernel/wmi.rs | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-)rust/kernel/wmi.rs +77
-1@@ -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
rust/kernel/wmi.rs fn as_ref(&self) -> &device::Device<Ctx> { · line 362
Quoted 10 lines
rust/kernel/wmi.rs +10
-0+/// - `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.
rust/kernel/wmi.rs fn as_ref(&self) -> &device::Device<Ctx> { · line 374
Quoted 12 lines
rust/kernel/wmi.rs +12
-0+// 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
Quoted 2 lines
rust/kernel/wmi.rs +1
-0+}
Re: [PATCH v2 4/4] rust: wmi: add Buffer and Device::invoke_method()
Hi Armin,
Quoted 8 lines
rust/kernel/wmi.rs fn as_ref(&self) -> &device::Device<Ctx> { · line 362
Quoted 7 lines
rust/kernel/wmi.rs +7
-0+impl Deref for Buffer { +type Target = [u8 ]; +#[inline] +fn deref (&self) -> &[u8 ] { +if self.0 .length ==0 { +return &[]; + }
Quoted 4 lines
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.
Quoted 12 lines
rust/kernel/wmi.rs fn as_ref(&self) -> &device::Device<Ctx> { · line 374
Quoted 7 lines
rust/kernel/wmi.rs +7
-0+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 structwmi_bufferinternal and instead return a KBox<[u8]> frominvoke_method().
Quoted 5 lines
IMHO struct
wmi_bufferonly exists because C does not define a standard slice type, so there is no reason for exposing structwmi_bufferas 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