[PATCH 1/8] rust: module: add `MODULE_PTR` const to `ModuleMetadata` trait

From: Alvin Sun

Date: Tue May 19 2026 - 02:35:43 EST


Add a `MODULE_PTR` const to the `ModuleMetadata` trait so that
modules can provide a constant pointer to their `struct module`
usable in const contexts such as static file_operations.

Signed-off-by: Alvin Sun <alvin.sun@xxxxxxxxx>
---
rust/kernel/lib.rs | 3 +++
rust/macros/module.rs | 14 ++++++++++++++
2 files changed, 17 insertions(+)

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index b72b2fbe046d6..c7e809636e1a9 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -184,6 +184,9 @@ fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Erro
pub trait ModuleMetadata {
/// The name of the module as specified in the `module!` macro.
const NAME: &'static crate::str::CStr;
+
+ /// The pointer to the kernel `struct module` for this module.
+ const MODULE_PTR: *mut bindings::module;
}

/// Equivalent to `THIS_MODULE` in the C API.
diff --git a/rust/macros/module.rs b/rust/macros/module.rs
index 06c18e2075083..7204fe604f24a 100644
--- a/rust/macros/module.rs
+++ b/rust/macros/module.rs
@@ -519,6 +519,20 @@ pub(crate) fn module(info: ModuleInfo) -> Result<TokenStream> {

impl ::kernel::ModuleMetadata for #type_ {
const NAME: &'static ::kernel::str::CStr = #name_cstr;
+
+ #[cfg(MODULE)]
+ const MODULE_PTR: *mut ::kernel::bindings::module = {
+ extern "C" {
+ static __this_module: ::kernel::types::Opaque<::kernel::bindings::module>;
+ }
+
+ // SAFETY: `__this_module` is constructed by the kernel at load time
+ // and lives until the module is unloaded.
+ unsafe { __this_module.get() }
+ };
+
+ #[cfg(not(MODULE))]
+ const MODULE_PTR: *mut ::kernel::bindings::module = ::core::ptr::null_mut();
}

// Double nested modules, since then nobody can access the public items inside.

--
2.43.0