From nobody Mon Feb 9 04:30:17 2026 Received: from m.foxido.dev (m.foxido.dev [81.177.217.87]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5528B34F486; Sun, 11 Jan 2026 18:31:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=81.177.217.87 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1768156322; cv=none; b=igZMy/j224SLYZuZYAdQLVfXyMgkmpz1StKsuGtZbrPGEN1ea1NwVJRbiHNBVhHqk9B9FWQW836u/yZdvuUc4Kxi2TotElVOrJdAJF8QY92oJCIKwC55tdG96C/Utq0GmUmXyyT8rn22VfeLutIjtfihU2XAxQ1dTdYTKWgpfPg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1768156322; c=relaxed/simple; bh=bV4EWz/BTK+Xq0GJsnKA8hk4RPz8zyxpx91FWog7v0c=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=WBqwkLjdN3Ghta+P57F47cJ4GMVF8kFkRU8elU4er3qA13KNLVfdnet7dfF7+ED++bw9EaVS3BRuACPLa+DxGz1tOIUH0aZc5ZU5sN6JkDAlOxJ7rR+uDKb65qEflT2qyKEbyWSEuKH1vsNwIc6qtKZ03R+nAOAfDsPWmRmNkl8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=foxido.dev; spf=pass smtp.mailfrom=foxido.dev; dkim=pass (2048-bit key) header.d=foxido.dev header.i=@foxido.dev header.b=TLqQOnHP; dkim=permerror (0-bit key) header.d=foxido.dev header.i=@foxido.dev header.b=Ws2sGOfg; arc=none smtp.client-ip=81.177.217.87 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=foxido.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=foxido.dev Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=foxido.dev header.i=@foxido.dev header.b="TLqQOnHP"; dkim=permerror (0-bit key) header.d=foxido.dev header.i=@foxido.dev header.b="Ws2sGOfg" DKIM-Signature: v=1; a=rsa-sha256; s=202508r; d=foxido.dev; c=relaxed/relaxed; h=Message-ID:Date:Subject:To:From; t=1768156306; bh=Xf4l59yTGNgTpiVOoO0eqv6 lrW07UkUBCfzLt473RJc=; b=TLqQOnHPpgfksRyq6fV8azxq+Oy9ChJMM6u8nbBjgkZagorXmb uCvmBdWLNPfOaRPgsAu9ZwjuI8e7XMFFH+AkFwU5sFGWw/06q/ArXGvfKtAHfJpspaozYzuYL1G 2a+sQnhZYKzw7fceP9dtykVi5gtXW7DfpSMr3Hbaux3QA7xh+RGgZ0u3skzUq+KF5CpjT0hgx09 HR/xQttrul6toSNbkGT0J51dNsynS5R8Z3RK7pUU/KVcfLC6vfnBhRptCy642XdueMn1kHmtGBK h5mPfNCTkgm/3xp3TrVJXD3kmRslPtrL+tRM7Qmf9kTorsDqjAVcihhH5DKX2FvjnCA==; DKIM-Signature: v=1; a=ed25519-sha256; s=202508e; d=foxido.dev; c=relaxed/relaxed; h=Message-ID:Date:Subject:To:From; t=1768156306; bh=Xf4l59yTGNgTpiVOoO0eqv6 lrW07UkUBCfzLt473RJc=; b=Ws2sGOfgJNNoSD2DwsIKX2saC+h+mXtm8t5lgE1vOKIp+i52jz UNLBRTQs3ZLBKculqX4XX/j3Lpic1emjjxCQ==; From: Gladyshev Ilya To: foxido@foxido.dev Cc: "Rafael J. Wysocki" , Len Brown , Miguel Ojeda , Boqun Feng , Gary Guo , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Tamir Duberstein , Armin Wolf , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-acpi@vger.kernel.org Subject: [PATCH v2 1/2] rust: implement wrapper for acpi_object Date: Sun, 11 Jan 2026 21:31:25 +0300 Message-ID: X-Mailer: git-send-email 2.52.0 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" ACPI Object is represented via union on C-side. On Rust side, this union is transparently wrapped for each ACPI Type, with individual methods and Defer implementation to represented type (integer, string, buffer, etc). Signed-off-by: Gladyshev Ilya --- rust/kernel/acpi.rs | 97 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/rust/kernel/acpi.rs b/rust/kernel/acpi.rs index 9b8efa623130..c730c12d3979 100644 --- a/rust/kernel/acpi.rs +++ b/rust/kernel/acpi.rs @@ -2,6 +2,11 @@ =20 //! Advanced Configuration and Power Interface abstractions. =20 +use core::{ + marker::PhantomData, + ops::Deref, // +}; + use crate::{ bindings, device_id::{RawDeviceId, RawDeviceIdIndex}, @@ -63,3 +68,95 @@ macro_rules! acpi_device_table { $crate::module_device_table!("acpi", $module_table_name, $table_na= me); }; } + +/// An ACPI object. +/// +/// This structure represents the Rust abstraction for a C [`struct acpi_o= bject`]. +/// You probably want to convert it into actual object type (e.g [`AcpiBuf= fer`]). +/// +/// # Example +/// ``` +/// # use kernel::prelude::*; +/// use kernel::acpi::{AcpiObject, AcpiBuffer}; +/// +/// fn read_first_acpi_byte(obj: &AcpiObject) -> Result { +/// let buf: &AcpiBuffer =3D obj.try_into()?; +/// +/// Ok(buf[0]) +/// } +/// ``` +/// +/// [`struct acpi_object`]: srctree/include/acpi/actypes.h +#[repr(transparent)] +pub struct AcpiObject<'a> { + inner: bindings::acpi_object, + _p: PhantomData<&'a bindings::acpi_object>, +} + +impl AcpiObject<'_> { + /// Returns object type id (see [`actypes.h`](srctree/include/acpi/act= ypes.h)). + pub fn type_id(&self) -> u32 { + // SAFETY: `type` field is valid in all union variants. + unsafe { self.inner.type_ } + } +} + +/// Generate wrapper type for AcpiObject subtype. +/// +/// For given subtype implements +/// - `#[repr(transparent)]` type wrapper, +/// - `TryFrom<&AcpiObject> for &SubType` trait, +/// - unsafe from_unchecked() for 'trusted' conversion. +macro_rules! acpi_object_subtype { + ($subtype_name:ident <- ($acpi_type:ident, $field_name:ident, $union_t= ype:ty)) =3D> { + /// Wraps `acpi_object` subtype. + #[repr(transparent)] + pub struct $subtype_name($union_type); + + impl<'a> TryFrom<&'a AcpiObject<'a>> for &'a $subtype_name { + type Error =3D Error; + + fn try_from(value: &'a AcpiObject<'a>) -> core::result::Result= { + if (value.type_id() !=3D $subtype_name::ACPI_TYPE) { + return Err(EINVAL); + } + + // SAFETY: Requested cast is valid because we validated ty= pe_id + Ok(unsafe { $subtype_name::from_unchecked(&value) }) + } + } + + impl $subtype_name { + /// Int value, representing this ACPI type (see [`acpitypes.h`= ]). + /// + /// [`acpitypes.h`]: srctree/include/linux/acpitypes.h + pub const ACPI_TYPE: u32 =3D bindings::$acpi_type; + + /// Converts opaque AcpiObject reference into exact ACPI type = reference. + /// + /// # Safety + /// + /// - Requested cast should be valid (value.type_id() is `Self= ::ACPI_TYPE`). + pub unsafe fn from_unchecked<'a>(value: &'a AcpiObject<'a>) ->= &'a Self { + // SAFETY: + // - $field_name is currently active union's field due to = external safety contract, + // - Transmuting to `repr(transparent)` wrapper is safe. + unsafe { + ::core::mem::transmute::<&$union_type, &$subtype_name>= (&value.inner.$field_name) + } + } + } + }; +} + +acpi_object_subtype!(AcpiBuffer + <- (ACPI_TYPE_BUFFER, buffer, bindings::acpi_object__bindgen_ty_3)); + +impl Deref for AcpiBuffer { + type Target =3D [u8]; + + fn deref(&self) -> &Self::Target { + // SAFETY: (pointer, length) indeed represents byte slice. + unsafe { ::core::slice::from_raw_parts(self.0.pointer, self.0.leng= th as usize) } + } +} --=20 2.52.0 From nobody Mon Feb 9 04:30:17 2026 Received: from m.foxido.dev (m.foxido.dev [81.177.217.87]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C559121FF4C; Sun, 11 Jan 2026 18:32:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=81.177.217.87 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1768156330; cv=none; b=sEWJ3zru+vZJ6Rr3YkkCyXWaxud5mc4p31DYdljwDDxR5nHm5qaGcKkiHyVm2Jm3CIqHSRNVzDuFbQXHGMpjG7KkH6y+U5XFWNc7LQjCgDpR+FetrqAog+QHCtv8jHxO+69nX++dDfJAn4W/5ePYFI2n38RGeqFiTAIcNN+Tq3s= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1768156330; c=relaxed/simple; bh=WbhC6EFKKjuMv1cPLZkF+zvOg/8ttTQTKXQQP4Mr0/c=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=rq/twpAoVM1K9WFx/s+USYz8VXghn0ZC6pqwc3FaUNvgIROfHHHkShFQpS0SyqOIdqDSsGZyFiAhNhuwjtRQP2Ijh2oHPFf71m2PYDIeOHdnCXCRy8oGKoke/sTjtrvp4Duj0d5w8oVVQ9cb0Mu52ajsdxfrddI5mjDZQbYw/RA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=foxido.dev; spf=pass smtp.mailfrom=foxido.dev; dkim=pass (2048-bit key) header.d=foxido.dev header.i=@foxido.dev header.b=Xj5E5wc8; dkim=permerror (0-bit key) header.d=foxido.dev header.i=@foxido.dev header.b=2HINTMLu; arc=none smtp.client-ip=81.177.217.87 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=foxido.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=foxido.dev Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=foxido.dev header.i=@foxido.dev header.b="Xj5E5wc8"; dkim=permerror (0-bit key) header.d=foxido.dev header.i=@foxido.dev header.b="2HINTMLu" DKIM-Signature: v=1; a=rsa-sha256; s=202508r; d=foxido.dev; c=relaxed/relaxed; h=Message-ID:Date:Subject:To:From; t=1768156307; bh=Js3PfRacKkqfBS9WvlN8eaq gmgTyO3HuuIh10PvNMrM=; b=Xj5E5wc8KHDopmt8wdh6Yeomvtd7g1vbYtjPuIf+7OkgYEER2M 4kWQ1+9YThNiCtohSAexF6PqzqMX3yzmHmndoeKYMvIWQR1tRHqAQLQsIXtiHbNQrIi2GuRSeNr H4IiOXafIVLEK+Lb4Rxriqqlk7ELMD4EyhLPCExSR+9uF2QVXUx4uCYmALhF4yZ/ODxFyIBNmgu DIZKnfh8YQVSaEK8V8pmwEZveqvkOQPPt6OAPFZSyuVaCy8coY1TGWSXVwTjcm3sZHWiHZSdCLn 7WM13GL5LbXOJsL4xNy3GV39kvFsQ3B8F77cZnaIS69uU1S2fDix7MVhKtAPZLmJFBw==; DKIM-Signature: v=1; a=ed25519-sha256; s=202508e; d=foxido.dev; c=relaxed/relaxed; h=Message-ID:Date:Subject:To:From; t=1768156307; bh=Js3PfRacKkqfBS9WvlN8eaq gmgTyO3HuuIh10PvNMrM=; b=2HINTMLuAsgZMOaOrmGMPxQebpuwUam8CrzoOqNPLaVadyWlRv n93jszgfvom/fpf0BU28DZfdbzdfsUQ+yGCw==; From: Gladyshev Ilya To: foxido@foxido.dev Cc: "Rafael J. Wysocki" , Len Brown , Miguel Ojeda , Boqun Feng , Gary Guo , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Tamir Duberstein , Armin Wolf , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-acpi@vger.kernel.org Subject: [PATCH v2 2/2] rust: add WMI abstractions Date: Sun, 11 Jan 2026 21:31:26 +0300 Message-ID: <42c8729d79c1264a2100b00d58b3f28a4584e585.1768153572.git.foxido@foxido.dev> X-Mailer: git-send-email 2.52.0 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This introduces Rust abstraction for WMI subsystem via wmi::Driver trait and module_wmi_driver/wmi_device_table macros. Driver can be probed, notified on events and removed -- almost everything C-side can do. This abstraction will be used by subsequent redmi_wmi_rs reference driver. Signed-off-by: Gladyshev Ilya --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/wmi.rs | 286 ++++++++++++++++++++++++++++++++ 4 files changed, 290 insertions(+) create mode 100644 rust/kernel/wmi.rs diff --git a/MAINTAINERS b/MAINTAINERS index 765ad2daa218..4909ae8be6e3 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -404,6 +404,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 =20 ACRN HYPERVISOR SERVICE MODULE M: Fei Li diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index a067038b4b42..f9671280c6b5 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -85,6 +85,7 @@ #include #include #include +#include #include #include =20 diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index f812cf120042..db3e649d26eb 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -151,6 +151,8 @@ pub mod uaccess; #[cfg(CONFIG_USB =3D "y")] pub mod usb; +#[cfg(CONFIG_ACPI_WMI)] +pub mod wmi; pub mod workqueue; pub mod xarray; =20 diff --git a/rust/kernel/wmi.rs b/rust/kernel/wmi.rs new file mode 100644 index 000000000000..d6b9bc29a4d6 --- /dev/null +++ b/rust/kernel/wmi.rs @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Abstractions for the WMI devices. +//! +//! C header: [`include/linux/wmi.h`](srctree/include/linux/wmi.h). + +use crate::{ + acpi::AcpiObject, + device, + device_id::{ + RawDeviceId, + RawDeviceIdIndex, // + }, + driver, + error::{ + from_result, + to_result, + VTABLE_DEFAULT_ERROR, // + }, + prelude::*, + types::Opaque, // +}; +use core::{ + marker::PhantomData, + ptr::NonNull, // +}; +use macros::vtable; + +/// [`IdTable`](kernel::device_id::IdTable) type for WMI. +pub type IdTable =3D &'static dyn kernel::device_id::IdTable; + +/// The WMI driver trait. +/// +/// Driver can be called from arbitary thread without any ordering guarant= ees. +#[vtable] +pub trait Driver: Send + Sync { + /// The type holding information about each one of the device ids supp= orted by the driver. + type IdInfo: 'static; + + /// The table of device ids supported by the driver. + const TABLE: IdTable; + + /// WMI driver probe. + /// + /// Called when a new WMI device is bound to this driver. + /// Implementers should attempt to initialize the driver here. + fn probe(dev: &Device, id_info: &Self::IdInfo) -> impl P= inInit; + + /// WMI device notify. + /// + /// Called when new WMI event received from bounded device. + fn notify(self: Pin<&Self>, _dev: &Device, _event: Opti= on<&AcpiObject<'_>>) { + build_error!(VTABLE_DEFAULT_ERROR); + } + + /// WMI driver remove. + /// + /// Called when the WMI driver is unbound from a WMI device. + fn unbind(self: Pin<&Self>, _dev: &Device) { + build_error!(VTABLE_DEFAULT_ERROR); + } +} + +/// A WMI device. +/// +/// This structure represents the Rust abstraction for a C [`struct wmi_de= vice`]. +/// The implementation abstracts the usage of a C [`struct wmi_device`] pa= ssed +/// in from the C side. +pub struct Device { + inner: Opaque, + _p: PhantomData, +} + +impl Device { + fn as_raw(&self) -> *mut bindings::wmi_device { + self.inner.get() + } +} + +/// An adapter for the registration of WMI drivers. +pub struct Adapter(T); + +// SAFETY: A call to `unregister` for a given instance of `RegType` is gua= ranteed to be valid if +// a preceding call to `register` has been successful. +unsafe impl driver::RegistrationOps for Adapter { + type RegType =3D bindings::wmi_driver; + + unsafe fn register( + wdrv: &Opaque, + name: &'static CStr, + module: &'static ThisModule, + ) -> Result { + macro_rules! map_callback { + ($flag:ident -> $callback:ident) =3D> { + if T::$flag { + Some(Self::$callback) + } else { + None + } + }; + } + + // SAFETY: It's safe to set the fields of `struct wmi_driver` on i= nitialization. + unsafe { + (*wdrv.get()).driver.name =3D name.as_char_ptr(); + (*wdrv.get()).driver.probe_type =3D bindings::probe_type_PROBE= _PREFER_ASYNCHRONOUS; + (*wdrv.get()).id_table =3D T::TABLE.as_ptr(); + (*wdrv.get()).probe =3D map_callback!(HAS_PROBE -> probe_callb= ack); + (*wdrv.get()).notify =3D map_callback!(HAS_NOTIFY -> notify_ca= llback); + (*wdrv.get()).remove =3D map_callback!(HAS_UNBIND -> remove_ca= llback); + (*wdrv.get()).shutdown =3D None; + (*wdrv.get()).no_singleton =3D true; + (*wdrv.get()).no_notify_data =3D true; + } + + // SAFETY: `wdrv` is guaranteed to be a valid `RegType`. + to_result(unsafe { bindings::__wmi_driver_register(wdrv.get(), mod= ule.as_ptr()) }) + } + + unsafe fn unregister(wdrv: &Opaque) { + // SAFETY: `wdrv` is guaranteed to be a valid `RegType`. + unsafe { bindings::wmi_driver_unregister(wdrv.get()) }; + } +} + +impl Adapter { + extern "C" fn probe_callback( + wdev: *mut bindings::wmi_device, + id: *const c_void, + ) -> kernel::ffi::c_int { + // SAFETY: The WMI core only ever calls the probe callback with a = valid pointer to a + // `struct wmi_device`. + // + // INVARIANT: `wdev` is valid for the duration of `probe_callback(= )`. + let wdev =3D unsafe { &*wdev.cast::>(= ) }; + + let id =3D id as usize; + let info =3D T::TABLE.info(id); + + from_result(|| { + let data =3D T::probe(wdev, info); + + wdev.as_ref().set_drvdata(data)?; + Ok(0) + }) + } + + extern "C" fn notify_callback( + wdev: *mut bindings::wmi_device, + obj: *mut bindings::acpi_object, + ) { + // SAFETY: The WMI system only ever calls the notify callback with= a valid pointer to a + // `struct wmi_device`. + let wdev =3D unsafe { &*wdev.cast::>(= ) }; + // SAFETY: + // - AcpiObject is repr(transparent) wrapper around FFI object, so= it's safe to cast + // raw pointer to reference (in terms of alignment and etc), + // - Option<&ref> is guaranteed to have same layout as raw pointer= (with NULL representing + // None) by Rust's "nullable pointer optimization". + let obj: Option<&AcpiObject<'_>> =3D + unsafe { core::mem::transmute(obj as *const AcpiObject<'_>) }; + + // SAFETY: `notify_callback` is only ever called after a successfu= l call to + // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called + // and stored a `T`. + let this =3D unsafe { wdev.as_ref().drvdata_borrow::() }; + this.notify(wdev, obj); + } + + extern "C" fn remove_callback(wdev: *mut bindings::wmi_device) { + // SAFETY: The WMI system only ever calls the remove callback with= a valid pointer to a + // `struct wmi_device`. + let wdev =3D unsafe { &*wdev.cast::>(= ) }; + + // SAFETY: `remove_callback` is only ever called after a successfu= l call to + // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called + // and stored a `T`. + let this =3D unsafe { wdev.as_ref().drvdata_borrow::() }; + this.unbind(wdev); + } +} + +impl AsRef> for Device { + fn as_ref(&self) -> &device::Device { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a p= ointer to a valid + // `struct platform_device`. + let dev =3D unsafe { &raw mut (*self.inner.get()).dev }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { device::Device::from_raw(dev) } + } +} + +// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend= on `Device`'s generic +// argument. +kernel::impl_device_context_deref!(unsafe { Device }); +kernel::impl_device_context_into_aref!(Device); + +// SAFETY: Instances of `Device` are always reference-counted. +unsafe impl crate::sync::aref::AlwaysRefCounted for Device { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference guarantees that the= refcount is non-zero. + unsafe { bindings::get_device(self.as_ref().as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is = non-zero. + unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).de= v) } + } +} + +/// Abstraction for the WMI device ID structure, i.e. [`struct wmi_device_= id`]. +/// +/// [`struct wmi_device_id`]: https://docs.kernel.org/driver-api/basics.ht= ml#c.wmi_device_id +#[repr(transparent)] +pub struct DeviceId(bindings::wmi_device_id); + +impl DeviceId { + const GUID_LEN: usize =3D bindings::UUID_STRING_LEN as usize; + + /// Constructs new DeviceId from GUID string. + pub const fn new(guid: &[u8; Self::GUID_LEN]) -> Self { + let mut inner: bindings::wmi_device_id =3D pin_init::zeroed(); + + build_assert!(inner.guid_string.len() =3D=3D Self::GUID_LEN + 1); + + // We are copying UUID_STRING_LEN bytes and we verified that UUID_= STRING_LEN + 1 byte + // exists and will remain '\0'. So we will construct valid C strin= g. + let mut i =3D 0; + while i < Self::GUID_LEN { + inner.guid_string[i] =3D guid[i]; + i +=3D 1; + } + + Self(inner) + } +} + +// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `wmi_device_i= d` and does not add +// additional invariants, so it's safe to transmute to `RawType`. +unsafe impl RawDeviceId for DeviceId { + type RawType =3D bindings::wmi_device_id; +} + +// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `context` field. +unsafe impl RawDeviceIdIndex for DeviceId { + const DRIVER_DATA_OFFSET: usize =3D core::mem::offset_of!(bindings::wm= i_device_id, context); + + fn index(&self) -> usize { + self.0.context as usize + } +} + +/// Declares a kernel module that exposes a single WMI driver. +/// +/// # Examples +/// +/// ```ignore +/// module_wmi_driver! { +/// type: MyDriver, +/// name: "Module name", +/// author: ["Author name"], +/// description: "Description", +/// license: "GPL v2", +/// } +/// ``` +#[macro_export] +macro_rules! module_wmi_driver { + ($($f:tt)*) =3D> { + $crate::module_driver!(, $crate::wmi::Adapter, { $($f)* }); + } +} + +/// Create a WMI `IdTable` with its alias for modpost. +#[macro_export] +macro_rules! wmi_device_table { + ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $tabl= e_data: expr) =3D> { + const $table_name: $crate::device_id::IdArray< + $crate::wmi::DeviceId, + $id_info_type, + { $table_data.len() }, + > =3D $crate::device_id::IdArray::new($table_data); + + $crate::module_device_table!("wmi", $module_table_name, $table_nam= e); + }; +} --=20 2.52.0