Skip to contentSkip to conversation

rust: Reimplement ThisModule to fix ownership problems

RFC PATCH In review Kari Argillander 5 participants 21 messages Jan 10 – Jan 27

Subsystems (25)
lore
Share & tools
lore
#0 lore raw

v3 cover rust: Reimplement ThisModule to fix ownership problems

Still RFC. Not all people for each subsystems are not included yet as this touch quite lot of things. I would like to get feed back is this resonable seperation and how we will land this. I have tried my best so that it can be applied in multiple staged if needed. I have not receive any feedback on this series and that is little bit worrying.

Introduce new ThisModule trait and THIS_MODULE impl.

So currently we have problem that we are not always filling .owner field example for file_operations. I think we can enable const_refs_to_static already as that is in 1.78 and is stable in 1.83. So that fits perfecly for us. This also seems to be quite request feature but I did not found that no one has ever suggested that we just enable this.

So basic idea is that we will have ThisModule trait which is used kernel side. Module side we will always use THIS_MODULE. That is completly private for modules and kernel crate cannot use it. Currently we have THIS_MODULE, LocalModule and

module: &' static ThisModule

on init functions. As we anyway need THIS_MODULE just use that for all of these things.

Patches 1-2 introduce THIS_MODULE and ThisModule trait. Patches 3-12 can be applied any order after 1-2. Patch 13 depends on patches 11-12.
Patches 14-15 are clean up patches and depends 1-13.

Argillander

To: Miguel Ojeda <[email protected]>
To: Boqun Feng <[email protected]>
To: Gary Guo <[email protected]>
To: Björn Roy Baron <[email protected]>
To: Benno Lossin <[email protected]>
To: Andreas Hindborg <[email protected]>
To: Alice Ryhl <[email protected]>
To: Trevor Gross <[email protected]>
To: Danilo Krummrich <[email protected]>

To: Alexandre Courbot <[email protected]>

Cc Luis Chamberlain <[email protected]>
Cc Petr Pavlu <[email protected]>
Cc Daniel Gomez <[email protected]>
Cc Sami Tolvanen <[email protected]>
Cc Aaron Tomlin <[email protected]>

---
Changes in v3:
- Edit cover.
- Seperate module name changes to seperate patches.
- Rebase top of next 20260109
- Seperate configfs changes to own commit.
- Fix one place still used M over TM for ThisModule.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Patches are now sepereted properly.
- Removed debugfs changes as that is not so clear to me.
- Remove module parameter and just used THIS_MODULE everywhere.
- Made macro to make THIS_MODULE.
- Doc tests also have THIS_MODULE.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Kari Argillander (15):
rust: enable const_refs_to_static feature
rust: add new ThisModule trait and THIS_MODULE impl
rust: miscdevice: fix use after free because missing .owner
rust: block: fix missing owner field in block_device_operations
rust: drm: fix missing owner in file_operations
rust: configfs: use new THIS_MODULE
rust: binder: use new THIS_MODULE
rust: firmware: use THIS_MODULE over LocalModule for name
gpu: nova-core: use THIS_MODULE over LocalModule for name
samples: rust: auxiliary: use THIS_MODULE over LocalModule for name
rust: driver: make RegistrationOps::register() to use new ThisModule
rust: phy: make Registration::register() use new ThisModule
rust: remove module argument from InPlaceModule::init()
rust: remove kernel::ModuleMetadata
rust: remove old version of ThisModule

 drivers/android/binder/rust_binder_main.rs |   5 +-
 drivers/block/rnull/configfs.rs            |   2 +-
 drivers/block/rnull/rnull.rs               |   3 +-
 drivers/gpu/drm/nova/driver.rs             |   2 +
 drivers/gpu/drm/tyr/driver.rs              |   2 +
 drivers/gpu/nova-core/nova_core.rs         |   2 +-
 lib/find_bit_benchmark_rust.rs             |   3 +-
 rust/kernel/auxiliary.rs                   |  16 +--
 rust/kernel/block/mq.rs                    |   1 +
 rust/kernel/block/mq/gen_disk.rs           |  30 +-----
 rust/kernel/block/mq/operations.rs         |  30 ++++++
 rust/kernel/configfs.rs                    |  49 ++++-----
 rust/kernel/driver.rs                      |  31 +++---
 rust/kernel/drm/device.rs                  |   2 +-
 rust/kernel/drm/driver.rs                  |   4 +
 rust/kernel/drm/gem/mod.rs                 |   5 +-
 rust/kernel/firmware.rs                    |   4 +-
 rust/kernel/i2c.rs                         |  11 +-
 rust/kernel/lib.rs                         | 161 ++++++++++++++++++++++++-----
 rust/kernel/miscdevice.rs                  |   5 +
 rust/kernel/net/phy.rs                     |  29 ++++--
 rust/kernel/pci.rs                         |  15 +--
 rust/kernel/platform.rs                    |  12 +--
 rust/kernel/prelude.rs                     |   2 +-
 rust/kernel/sync/lock/global.rs            |   4 +-
 rust/kernel/usb.rs                         |  13 +--
 rust/macros/lib.rs                         |   4 +-
 rust/macros/module.rs                      |  24 +----
 samples/rust/rust_configfs.rs              |   2 +-
 samples/rust/rust_debugfs_scoped.rs        |   2 +-
 samples/rust/rust_driver_auxiliary.rs      |   8 +-
 samples/rust/rust_driver_faux.rs           |   2 +-
 samples/rust/rust_minimal.rs               |   2 +-
 samples/rust/rust_misc_device.rs           |   3 +-
 samples/rust/rust_print_main.rs            |   2 +-
 scripts/rustdoc_test_gen.rs                |   2 +
 36 files changed, 298 insertions(+), 196 deletions(-)

---
base-commit: f417b7ffcbef7d76b0d8860518f50dae0e7e5eda
change-id: 20251230-this_module_fix-a390bff24897

Best regards,

Signature · 1 line
Kari Argillander <[email protected]>
#1 lore raw

RFC PATCH v3 1/15 rust: enable const_refs_to_static feature

Enable the const_refs_to_static Rust feature to allow taking references to static items in const contexts. This is required for using ThisModule when constructing static Rust structures.

The Rust support already relies on features available in Rust 1.83, and const_refs_to_static has been available since Rust 1.78.

---
 rust/kernel/lib.rs | 1 +
 1 file changed, 1 insertion(+)
rust/kernel/lib.rs +1 -0
index 6d637e2fed1b..510d4bfc7c2b 100644
@@ -36,6 +36,7 @@
 #![feature(const_option)]
 #![feature(const_ptr_write)]
 #![feature(const_refs_to_cell)]
+#![feature(const_refs_to_static)]
 //
 // Expected to become stable.
 #![feature(arbitrary_self_types)]
Signature · 1 line
2.43.0
#2 lore raw

RFC PATCH v3 2/15 rust: add new ThisModule trait and THIS_MODULE impl

In reply to Kari Argillander

To make clear separation between module crates and kernel crate we introduce ThisModule trait which is meant to be used by kernel space. THIS_MODULE is meant to be used by modules. So kernel create will be unable to even accidentally use THIS_MODULE.

As ThisModule is trait we can pass that around in const context. This is needed so that we can read ownership information in const context when we create example file_operations structs for modules.

New ThisModule will also eventually replace kernel::ModuleMetadata trait and for this reason it also have NAME field.

To make transition smooth use mod this_module so we can have two ThisModule same time. Also some functionality is added to THIS_MODULE temporarily so that we do not have to change everything at once.

Also docs examples will need THIS_MODULE so also define that in docs.

---
 rust/kernel/configfs.rs     |   6 +-
 rust/kernel/lib.rs          | 159 ++++++++++++++++++++++++++++++++++++++++++++
 rust/macros/module.rs       |  16 +----
 scripts/rustdoc_test_gen.rs |   2 +
 4 files changed, 166 insertions(+), 17 deletions(-)
rust/kernel/configfs.rs +3 -3
index 466fb7f40762..fe80439ab21f 100644
@@ -876,7 +876,7 @@ fn as_ptr(&self) -> *const bindings::config_item_type {
 ///                 configfs::Subsystem<Configuration>,
 ///                 Configuration
 ///                 >::new_with_child_ctor::<N,Child>(
-///             &THIS_MODULE,
+///             THIS_MODULE.as_ref(),
 ///             &CONFIGURATION_ATTRS
 ///         );
 ///
@@ -1020,7 +1020,7 @@ macro_rules! configfs_attrs {
 
                     static [< $data:upper _TPE >] : $crate::configfs::ItemType<$container, $data>  =
                         $crate::configfs::ItemType::<$container, $data>::new::<N>(
-                            &THIS_MODULE, &[<$ data:upper _ATTRS >]
+                            THIS_MODULE.as_ref(), &[<$ data:upper _ATTRS >]
                         );
                 )?
 
@@ -1029,7 +1029,7 @@ macro_rules! configfs_attrs {
                         $crate::configfs::ItemType<$container, $data>  =
                             $crate::configfs::ItemType::<$container, $data>::
                             new_with_child_ctor::<N, $child>(
-                                &THIS_MODULE, &[<$ data:upper _ATTRS >]
+                                THIS_MODULE.as_ref(), &[<$ data:upper _ATTRS >]
                             );
                 )?
 
rust/kernel/lib.rs +159 -0

165 lines not on this page · raw message

rust/macros/module.rs +2 -14
index 80cb9b16f5aa..1bcd703735fe 100644
@@ -371,20 +371,8 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
             /// Used by the printing macros, e.g. [`info!`].
             const __LOG_PREFIX: &[u8] = b\"{name}\\0\";
 
-            // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
-            // freed until the module is unloaded.
-            #[cfg(MODULE)]
-            static THIS_MODULE: ::kernel::ThisModule = unsafe {{
-                extern \"C\" {{
-                    static __this_module: ::kernel::types::Opaque<::kernel::bindings::module>;
-                }}
+            ::kernel::create_this_module!(\"{name}\");
 
-                ::kernel::ThisModule::from_ptr(__this_module.get())
-            }};
-            #[cfg(not(MODULE))]
-            static THIS_MODULE: ::kernel::ThisModule = unsafe {{
-                ::kernel::ThisModule::from_ptr(::core::ptr::null_mut())
-            }};
 
             /// The `LocalModule` type is the type of the module created by `module!`,
             /// `module_pci_driver!`, `module_platform_driver!`, etc.
@@ -502,7 +490,7 @@ mod __module_init {{
                     /// This function must only be called once.
                     unsafe fn __init() -> ::kernel::ffi::c_int {{
                         let initer =
-                            <{type_} as ::kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
+                            <{type_} as ::kernel::InPlaceModule>::init(&super::super::THIS_MODULE.as_ref());
                         // SAFETY: No data race, since `__MOD` can only be accessed by this module
                         // and there only `__init` and `__exit` access it. These functions are only
                         // called once and `__exit` cannot be called before or during `__init`.
scripts/rustdoc_test_gen.rs +2 -0
index 6fd9f5c84e2e..089e38b49cdd 100644
@@ -232,6 +232,8 @@ macro_rules! assert_eq {{
 
 const __LOG_PREFIX: &[u8] = b"rust_doctests_kernel\0";
 
+::kernel::create_this_module!("rust_doctests_kernel");
+
 {rust_tests}
 "#
     )
Signature · 1 line
2.43.0
maintainer
#3 lore raw

Re: [PATCH RFC v3 02/15] rust: add new ThisModule trait and THIS_MODULE impl

Quoted 12 lines · Kari Argillander

To make clear separation between module crates and kernel crate we introduce ThisModule trait which is meant to be used by kernel space. THIS_MODULE is meant to be used by modules. So kernel create will be unable to even accidentally use THIS_MODULE.

As ThisModule is trait we can pass that around in const context. This is needed so that we can read ownership information in const context when we create example file_operations structs for modules.

New ThisModule will also eventually replace kernel::ModuleMetadata trait and for this reason it also have NAME field.

Quoted 7 lines

To make transition smooth use mod this_module so we can have two ThisModule same time. Also some functionality is added to THIS_MODULE temporarily so that we do not have to change everything at once.

Also docs examples will need THIS_MODULE so also define that in docs.

Is this pattern common in other Rust code in the kernel? The situation on the C side is that THIS_MODULE is a variable of the module struct. On the Rust side, it is currently quite similar, with THIS_MODULE being a variable of the ThisModule struct/wrapper. The patch shifts this and makes THIS_MODULE a type that implements the ThisModule trait.

Naively, it seems somewhat confusing to me, coming mostly from the C side and expecting THIS_MODULE to be a variable.

I'd like to understand this better. Would enabling const_refs_to_static alone be sufficient, or is it necessary to make THIS_MODULE a type for this to work? Should we be concerned that this new model could confuse people, or do you think it actually simplifies things? Does making the functions generic on ThisModule impact code size in any significant way, or could it in the future?

Signature · 2 lines
Thanks,
Petr
#4 lore raw

RFC PATCH v3 3/15 rust: miscdevice: fix use after free because missing .owner

In reply to Kari Argillander

Currently if miscdevice driver is compiled as module it can cause use after free when unloading. To reproduce problem with Rust sample driver we can do:

tail -f /dev/rust-misc-device
# And same time as device is open
sudo rmmod rust_misc_device_module

This will crash system. Fix is to have .owner field filled with module information. We pass this owner information through vtable.

Fixes f893691e7426 ("rust: miscdevice: add base miscdevice abstraction")
---
 rust/kernel/miscdevice.rs        | 5 +++++
 samples/rust/rust_misc_device.rs | 1 +
 2 files changed, 6 insertions(+)
rust/kernel/miscdevice.rs +5 -0
index ba64c8a858f0..d4b0c35c4b60 100644
@@ -18,6 +18,7 @@
     mm::virt::VmaNew,
     prelude::*,
     seq_file::SeqFile,
+    this_module::ThisModule,
     types::{ForeignOwnable, Opaque},
 };
 use core::{marker::PhantomData, pin::Pin};
@@ -112,6 +113,9 @@ fn drop(self: Pin<&mut Self>) {
 /// Trait implemented by the private data of an open misc device.
 #[vtable]
 pub trait MiscDevice: Sized {
+    /// Module ownership for this device, provided via `THIS_MODULE`.
+    type ThisModule: ThisModule;
+
     /// What kind of pointer should `Self` be wrapped in.
     type Ptr: ForeignOwnable + Send + Sync;
 
@@ -388,6 +392,7 @@ impl<T: MiscDevice> MiscdeviceVTable<T> {
     }
 
     const VTABLE: bindings::file_operations = bindings::file_operations {
+        owner: T::ThisModule::OWNER.as_ptr(),
         open: Some(Self::open),
         release: Some(Self::release),
         mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },
samples/rust/rust_misc_device.rs +1 -0
index 49dd5814e1ab..464e3026e6e3 100644
@@ -155,6 +155,7 @@ struct RustMiscDevice {
 
 #[vtable]
 impl MiscDevice for RustMiscDevice {
+    type ThisModule = THIS_MODULE;
     type Ptr = Pin<KBox<Self>>;
 
     fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Self>>> {
Signature · 1 line
2.43.0
#5 lore raw

RFC PATCH v3 4/15 rust: block: fix missing owner field in block_device_operations

In reply to Kari Argillander

Kernel has now enabled "const_refs_to_static" feature. We can fix TODO item now. Fix this by defining owner in vtable so we can read it from there. As this table needs to be const we need to define it in operations so we do not need pass THIS_MODULE alongside with GenDiskBuilder::build().

This will probably fix some use after free.

Fixes 3253aba3408a ("rust: block: introduce `kernel::block::mq` module")
---
 drivers/block/rnull/rnull.rs       |  1 +
 rust/kernel/block/mq.rs            |  1 +
 rust/kernel/block/mq/gen_disk.rs   | 30 ++++--------------------------
 rust/kernel/block/mq/operations.rs | 30 ++++++++++++++++++++++++++++++
 4 files changed, 36 insertions(+), 26 deletions(-)
drivers/block/rnull/rnull.rs +1 -0
index a9d5e575a2c4..862369ab9b5c 100644
@@ -74,6 +74,7 @@ struct QueueData {
 
 #[vtable]
 impl Operations for NullBlkDevice {
+    type ThisModule = THIS_MODULE;
     type QueueData = KBox<QueueData>;
 
     #[inline(always)]
rust/kernel/block/mq.rs +1 -0
index 1fd0d54dd549..0c8e9e316952 100644
@@ -68,6 +68,7 @@
 //!
 //! #[vtable]
 //! impl Operations for MyBlkDevice {
+//!     type ThisModule = THIS_MODULE;
 //!     type QueueData = ();
 //!
 //!     fn queue_rq(_queue_data: (), rq: ARef<Request<Self>>, _is_last: bool) -> Result {
rust/kernel/block/mq/gen_disk.rs +4 -26
index 1ce815c8cdab..4d5d378577ec 100644
@@ -7,7 +7,7 @@
 
 use crate::{
     bindings,
-    block::mq::{Operations, TagSet},
+    block::mq::{operations::OperationsVTable, Operations, TagSet},
     error::{self, from_err_ptr, Result},
     fmt::{self, Write},
     prelude::*,
@@ -126,32 +126,10 @@ pub fn build<T: Operations>(
             )
         })?;
 
-        const TABLE: bindings::block_device_operations = bindings::block_device_operations {
-            submit_bio: None,
-            open: None,
-            release: None,
-            ioctl: None,
-            compat_ioctl: None,
-            check_events: None,
-            unlock_native_capacity: None,
-            getgeo: None,
-            set_read_only: None,
-            swap_slot_free_notify: None,
-            report_zones: None,
-            devnode: None,
-            alternative_gpt_sector: None,
-            get_unique_id: None,
-            // TODO: Set to THIS_MODULE. Waiting for const_refs_to_static feature to
-            // be merged (unstable in rustc 1.78 which is staged for linux 6.10)
-            // <https://github.com/rust-lang/rust/issues/119618>
-            owner: core::ptr::null_mut(),
-            pr_ops: core::ptr::null_mut(),
-            free_disk: None,
-            poll_bio: None,
-        };
-
         // SAFETY: `gendisk` is a valid pointer as we initialized it above
-        unsafe { (*gendisk).fops = &TABLE };
+        unsafe {
+            (*gendisk).fops = OperationsVTable::<T>::build_block_device_operations();
+        }
 
         let mut writer = NullTerminatedFormatter::new(
             // SAFETY: `gendisk` points to a valid and initialized instance. We
rust/kernel/block/mq/operations.rs +30 -0
index 8ad46129a52c..0f8f616590fb 100644
@@ -10,6 +10,7 @@
     error::{from_result, Result},
     prelude::*,
     sync::{aref::ARef, Refcount},
+    this_module::ThisModule,
     types::ForeignOwnable,
 };
 use core::marker::PhantomData;
@@ -28,6 +29,9 @@
 /// [module level documentation]: kernel::block::mq
 #[macros::vtable]
 pub trait Operations: Sized {
+    /// Module ownership for this device, provided via `THIS_MODULE`.
+    type ThisModule: ThisModule;
+
     /// Data associated with the `struct request_queue` that is allocated for
     /// the `GenDisk` associated with this `Operations` implementation.
     type QueueData: ForeignOwnable;
@@ -280,7 +284,33 @@ impl<T: Operations> OperationsVTable<T> {
         show_rq: None,
     };
 
+    const BLOCK_OPS: bindings::block_device_operations = bindings::block_device_operations {
+        submit_bio: None,
+        open: None,
+        release: None,
+        ioctl: None,
+        compat_ioctl: None,
+        check_events: None,
+        unlock_native_capacity: None,
+        getgeo: None,
+        set_read_only: None,
+        swap_slot_free_notify: None,
+        report_zones: None,
+        devnode: None,
+        alternative_gpt_sector: None,
+        get_unique_id: None,
+        owner: T::ThisModule::OWNER.as_ptr(),
+        pr_ops: core::ptr::null_mut(),
+        free_disk: None,
+        poll_bio: None,
+    };
+
     pub(crate) const fn build() -> &'static bindings::blk_mq_ops {
         &Self::VTABLE
     }
+
+    pub(crate) const fn build_block_device_operations() -> &'static bindings::block_device_operations
+    {
+        &Self::BLOCK_OPS
+    }
 }
Signature · 1 line
2.43.0
#6 lore raw

RFC PATCH v3 5/15 rust: drm: fix missing owner in file_operations

In reply to Kari Argillander

Fix missing .owner field in file_operations. This has been previosly left out because Rust feature const_refs_to_static has not been enabled. Now that it is we can make define owner even in const context.

This should probably fix use-after-free problems in situations where file is opened and module driver is unloaded during that.

---
 drivers/gpu/drm/nova/driver.rs | 2 ++
 drivers/gpu/drm/tyr/driver.rs  | 2 ++
 rust/kernel/drm/device.rs      | 2 +-
 rust/kernel/drm/driver.rs      | 4 ++++
 rust/kernel/drm/gem/mod.rs     | 5 +++--
 5 files changed, 12 insertions(+), 3 deletions(-)
drivers/gpu/drm/nova/driver.rs +2 -0
index b1af0a099551..7ce505802716 100644
@@ -14,6 +14,7 @@
 
 use crate::file::File;
 use crate::gem::NovaObject;
+use crate::THIS_MODULE;
 
 pub(crate) struct NovaDriver {
     #[expect(unused)]
@@ -65,6 +66,7 @@ fn probe(adev: &auxiliary::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<S
 
 #[vtable]
 impl drm::Driver for NovaDriver {
+    type ThisModule = THIS_MODULE;
     type Data = NovaData;
     type File = File;
     type Object = gem::Object<NovaObject>;
drivers/gpu/drm/tyr/driver.rs +2 -0
index f0da58932702..11932d3f03ff 100644
@@ -25,6 +25,7 @@
 use crate::gpu;
 use crate::gpu::GpuInfo;
 use crate::regs;
+use crate::THIS_MODULE;
 
 pub(crate) type IoMem = kernel::io::mem::IoMem<SZ_2M>;
 
@@ -179,6 +180,7 @@ fn drop(self: Pin<&mut Self>) {
 
 #[vtable]
 impl drm::Driver for TyrDriver {
+    type ThisModule = THIS_MODULE;
     type Data = TyrData;
     type File = File;
     type Object = drm::gem::Object<TyrObject>;
rust/kernel/drm/device.rs +1 -1
index 3ce8f62a0056..a740c87933d0 100644
@@ -92,7 +92,7 @@ impl<T: drm::Driver> Device<T> {
         fops: &Self::GEM_FOPS,
     };
 
-    const GEM_FOPS: bindings::file_operations = drm::gem::create_fops();
+    const GEM_FOPS: bindings::file_operations = drm::gem::create_fops::<T::ThisModule>();
 
     /// Create a new `drm::Device` for a `drm::Driver`.
     pub fn new(dev: &device::Device, data: impl PinInit<T::Data, Error>) -> Result<ARef<Self>> {
rust/kernel/drm/driver.rs +4 -0
index f30ee4c6245c..a157db2ea02b 100644
@@ -9,6 +9,7 @@
     error::{to_result, Result},
     prelude::*,
     sync::aref::ARef,
+    this_module::ThisModule,
 };
 use macros::vtable;
 
@@ -99,6 +100,9 @@ pub trait AllocImpl: super::private::Sealed + drm::gem::IntoGEMObject {
 /// drm_driver` to be registered in the DRM subsystem.
 #[vtable]
 pub trait Driver {
+    /// Module ownership for this device, provided via `THIS_MODULE`.
+    type ThisModule: ThisModule;
+
     /// Context data associated with the DRM driver
     type Data: Sync + Send;
 
rust/kernel/drm/gem/mod.rs +3 -2
index d49a9ba02635..705afea65ff6 100644
@@ -11,6 +11,7 @@
     error::{to_result, Result},
     prelude::*,
     sync::aref::{ARef, AlwaysRefCounted},
+    this_module::ThisModule,
     types::Opaque,
 };
 use core::{ops::Deref, ptr::NonNull};
@@ -292,10 +293,10 @@ impl<T: DriverObject> AllocImpl for Object<T> {
     };
 }
 
-pub(super) const fn create_fops() -> bindings::file_operations {
+pub(super) const fn create_fops<TM: ThisModule>() -> bindings::file_operations {
     let mut fops: bindings::file_operations = pin_init::zeroed();
 
-    fops.owner = core::ptr::null_mut();
+    fops.owner = TM::OWNER.as_ptr();
     fops.open = Some(bindings::drm_open);
     fops.release = Some(bindings::drm_release);
     fops.unlocked_ioctl = Some(bindings::drm_ioctl);
Signature · 1 line
2.43.0
#7 lore raw

RFC PATCH v3 6/15 rust: configfs: use new THIS_MODULE

In reply to Kari Argillander

We have new THIS_MODULE and ThisModule is now trait. Pass THIS_MODULE as generic type parameter which is current convention.

---
 drivers/block/rnull/configfs.rs |  2 +-
 rust/kernel/configfs.rs         | 46 +++++++++++++++++++++--------------------
 2 files changed, 25 insertions(+), 23 deletions(-)
drivers/block/rnull/configfs.rs +1 -1
index 2f5a7da03af5..7223ee7c3032 100644
@@ -1,6 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use super::{NullBlkDevice, THIS_MODULE};
+use super::NullBlkDevice;
 use kernel::{
     block::mq::gen_disk::{GenDisk, GenDiskBuilder},
     c_str,
rust/kernel/configfs.rs +24 -22

92 lines not on this page · raw message

Signature · 1 line
2.43.0
#8 lore raw

RFC PATCH v3 7/15 rust: binder: use new THIS_MODULE

In reply to Kari Argillander

We have new THIS_MODULE. ThisModule is now crate. This is ugly for reason that drivers should not use as_ptr() directly. Currently binder still needs it so ugly cast is totally ok.

---
 drivers/android/binder/rust_binder_main.rs | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/android/binder/rust_binder_main.rs +2 -1
index d84c3c360be0..fc921c0e1116 100644
@@ -21,6 +21,7 @@
     sync::poll::PollTable,
     sync::Arc,
     task::Pid,
+    this_module::ThisModule,
     transmute::AsBytes,
     types::ForeignOwnable,
     uaccess::UserSliceWriter,
@@ -319,7 +320,7 @@ unsafe impl<T> Sync for AssertSync<T> {}
     let zeroed_ops = unsafe { core::mem::MaybeUninit::zeroed().assume_init() };
 
     let ops = kernel::bindings::file_operations {
-        owner: THIS_MODULE.as_ptr(),
+        owner: <THIS_MODULE as ThisModule>::OWNER.as_ptr(),
         poll: Some(rust_binder_poll),
         unlocked_ioctl: Some(rust_binder_ioctl),
         #[cfg(CONFIG_COMPAT)]
Signature · 1 line
2.43.0
#9 lore raw

RFC PATCH v3 8/15 rust: firmware: use THIS_MODULE over LocalModule for name

In reply to Kari Argillander

THIS_MODULE now contains also name so there is no need to use LocalModule anymore. LocalModule will be removed in future.

---
 rust/kernel/firmware.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/firmware.rs +1 -1
index 71168d8004e2..2702f01c0403 100644
@@ -206,7 +206,7 @@ macro_rules! module_firmware {
             const __MODULE_FIRMWARE_PREFIX: &'static $crate::str::CStr = if cfg!(MODULE) {
                 c""
             } else {
-                <LocalModule as $crate::ModuleMetadata>::NAME
+                crate::THIS_MODULE::name()
             };
 
             #[link_section = ".modinfo"]
Signature · 1 line
2.43.0
#10 lore raw

RFC PATCH v3 9/15 gpu: nova-core: use THIS_MODULE over LocalModule for name

In reply to Kari Argillander

THIS_MODULE now contains also name so there is no need to use LocalModule anymore. LocalModule will be removed in future.

---
 drivers/gpu/nova-core/nova_core.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/nova-core/nova_core.rs +1 -1
index c1121e7c64c5..c8d6f9e3be1c 100644
@@ -18,7 +18,7 @@
 mod sbuffer;
 mod vbios;
 
-pub(crate) const MODULE_NAME: &kernel::str::CStr = <LocalModule as kernel::ModuleMetadata>::NAME;
+pub(crate) const MODULE_NAME: &kernel::str::CStr = THIS_MODULE::name();
 
 kernel::module_pci_driver! {
     type: driver::NovaCore,
Signature · 1 line
2.43.0
#11 lore raw

RFC PATCH v3 10/15 samples: rust: auxiliary: use THIS_MODULE over LocalModule for name

In reply to Kari Argillander

THIS_MODULE now contains also name so there is no need to use LocalModule anymore. LocalModule will be removed in future.

---
 samples/rust/rust_driver_auxiliary.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
samples/rust/rust_driver_auxiliary.rs +1 -1
index 1e4fb23cfcb0..84d67c5c87c8 100644
@@ -18,7 +18,7 @@
 use core::any::TypeId;
 use pin_init::PinInit;
 
-const MODULE_NAME: &CStr = <LocalModule as kernel::ModuleMetadata>::NAME;
+const MODULE_NAME: &CStr = THIS_MODULE::name();
 const AUXILIARY_NAME: &CStr = c"auxiliary";
 
 struct AuxiliaryDriver;
Signature · 1 line
2.43.0
#12 lore raw

RFC PATCH v3 11/15 rust: driver: make RegistrationOps::register() to use new ThisModule

In reply to Kari Argillander

New version of ThisModule is trait which can be passed in const context. To have unified way to pass THIS_MODULE to abstactions have const parameter which can be used to get owner and name.

---
 rust/kernel/auxiliary.rs              | 16 ++++++++--------
 rust/kernel/driver.rs                 | 29 +++++++++++++----------------
 rust/kernel/i2c.rs                    | 11 ++++-------
 rust/kernel/pci.rs                    | 15 +++++----------
 rust/kernel/platform.rs               | 12 ++++--------
 rust/kernel/usb.rs                    | 13 ++++---------
 samples/rust/rust_driver_auxiliary.rs |  6 +++---
 7 files changed, 41 insertions(+), 61 deletions(-)
rust/kernel/auxiliary.rs +8 -8
index 56f3c180e8f6..102b0349af16 100644
@@ -11,8 +11,8 @@
     driver,
     error::{from_result, to_result, Result},
     prelude::*,
+    this_module::ThisModule,
     types::Opaque,
-    ThisModule,
 };
 use core::{
     marker::PhantomData,
@@ -28,14 +28,10 @@
 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
     type RegType = bindings::auxiliary_driver;
 
-    unsafe fn register(
-        adrv: &Opaque<Self::RegType>,
-        name: &'static CStr,
-        module: &'static ThisModule,
-    ) -> Result {
+    unsafe fn register<TM: ThisModule>(adrv: &Opaque<Self::RegType>) -> Result {
         // SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization.
         unsafe {
-            (*adrv.get()).name = name.as_char_ptr();
+            (*adrv.get()).name = TM::NAME.as_char_ptr();
             (*adrv.get()).probe = Some(Self::probe_callback);
             (*adrv.get()).remove = Some(Self::remove_callback);
             (*adrv.get()).id_table = T::ID_TABLE.as_ptr();
@@ -43,7 +39,11 @@ unsafe fn register(
 
         // SAFETY: `adrv` is guaranteed to be a valid `RegType`.
         to_result(unsafe {
-            bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())
+            bindings::__auxiliary_driver_register(
+                adrv.get(),
+                TM::OWNER.as_ptr(),
+                TM::NAME.as_char_ptr(),
+            )
         })
     }
 
rust/kernel/driver.rs +13 -16
index 649d06468f41..dc7522c4ebda 100644
@@ -94,10 +94,14 @@
 //! [`device_id`]: kernel::device_id
 //! [`module_driver`]: kernel::module_driver
 
-use crate::error::{Error, Result};
-use crate::{acpi, device, of, str::CStr, try_pin_init, types::Opaque, ThisModule};
-use core::pin::Pin;
-use pin_init::{pin_data, pinned_drop, PinInit};
+use crate::{
+    acpi,
+    device,
+    of,
+    prelude::*,
+    this_module::ThisModule,
+    types::Opaque, //
+};
 
 /// The [`RegistrationOps`] trait serves as generic interface for subsystems (e.g., PCI, Platform,
 /// Amba, etc.) to provide the corresponding subsystem specific implementation to register /
@@ -122,11 +126,7 @@ pub unsafe trait RegistrationOps {
     ///
     /// On success, `reg` must remain pinned and valid until the matching call to
     /// [`RegistrationOps::unregister`].
-    unsafe fn register(
-        reg: &Opaque<Self::RegType>,
-        name: &'static CStr,
-        module: &'static ThisModule,
-    ) -> Result;
+    unsafe fn register<TM: ThisModule>(reg: &Opaque<Self::RegType>) -> Result;
 
     /// Unregisters a driver previously registered with [`RegistrationOps::register`].
     ///
@@ -159,7 +159,7 @@ unsafe impl<T: RegistrationOps> Send for Registration<T> {}
 
 impl<T: RegistrationOps> Registration<T> {
     /// Creates a new instance of the registration object.
-    pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> {
+    pub fn new<TM: ThisModule>() -> impl PinInit<Self, Error> {
         try_pin_init!(Self {
             reg <- Opaque::try_ffi_init(|ptr: *mut T::RegType| {
                 // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write.
@@ -170,7 +170,7 @@ pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Sel
                 let drv = unsafe { &*(ptr as *const Opaque<T::RegType>) };
 
                 // SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.
-                unsafe { T::register(drv, name, module) }
+                unsafe { T::register::<TM>(drv) }
             }),
         })
     }
@@ -202,13 +202,10 @@ struct DriverModule {
 
         impl $crate::InPlaceModule for DriverModule {
             fn init(
-                module: &'static $crate::ThisModule
+                _module: &'static $crate::ThisModule
             ) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {
                 $crate::try_pin_init!(Self {
-                    _driver <- $crate::driver::Registration::new(
-                        <Self as $crate::ModuleMetadata>::NAME,
-                        module,
-                    ),
+                    _driver <- $crate::driver::Registration::new::<crate::THIS_MODULE>(),
                 })
             }
         }
rust/kernel/i2c.rs +4 -7
index 491e6cc25cf4..b23a26a445cd 100644
@@ -16,6 +16,7 @@
     error::*,
     of,
     prelude::*,
+    this_module::ThisModule,
     types::{
         AlwaysRefCounted,
         Opaque, //
@@ -97,11 +98,7 @@ macro_rules! i2c_device_table {
 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
     type RegType = bindings::i2c_driver;
 
-    unsafe fn register(
-        idrv: &Opaque<Self::RegType>,
-        name: &'static CStr,
-        module: &'static ThisModule,
-    ) -> Result {
+    unsafe fn register<TM: ThisModule>(idrv: &Opaque<Self::RegType>) -> Result {
         build_assert!(
             T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I2C_ID_TABLE.is_some(),
             "At least one of ACPI/OF/Legacy tables must be present when registering an i2c driver"
@@ -124,7 +121,7 @@ unsafe fn register(
 
         // SAFETY: It's safe to set the fields of `struct i2c_client` on initialization.
         unsafe {
-            (*idrv.get()).driver.name = name.as_char_ptr();
+            (*idrv.get()).driver.name = TM::NAME.as_char_ptr();
             (*idrv.get()).probe = Some(Self::probe_callback);
             (*idrv.get()).remove = Some(Self::remove_callback);
             (*idrv.get()).shutdown = Some(Self::shutdown_callback);
@@ -134,7 +131,7 @@ unsafe fn register(
         }
 
         // SAFETY: `idrv` is guaranteed to be a valid `RegType`.
-        to_result(unsafe { bindings::i2c_register_driver(module.0, idrv.get()) })
+        to_result(unsafe { bindings::i2c_register_driver(TM::OWNER.as_ptr(), idrv.get()) })
     }
 
     unsafe fn unregister(idrv: &Opaque<Self::RegType>) {
rust/kernel/pci.rs +5 -10
index 82e128431f08..88a5416fb44b 100644
@@ -18,9 +18,8 @@
         to_result, //
     },
     prelude::*,
-    str::CStr,
-    types::Opaque,
-    ThisModule, //
+    this_module::ThisModule,
+    types::Opaque, //
 };
 use core::{
     marker::PhantomData,
@@ -55,14 +54,10 @@
 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
     type RegType = bindings::pci_driver;
 
-    unsafe fn register(
-        pdrv: &Opaque<Self::RegType>,
-        name: &'static CStr,
-        module: &'static ThisModule,
-    ) -> Result {
+    unsafe fn register<TM: ThisModule>(pdrv: &Opaque<Self::RegType>) -> Result {
         // SAFETY: It's safe to set the fields of `struct pci_driver` on initialization.
         unsafe {
-            (*pdrv.get()).name = name.as_char_ptr();
+            (*pdrv.get()).name = TM::NAME.as_char_ptr();
             (*pdrv.get()).probe = Some(Self::probe_callback);
             (*pdrv.get()).remove = Some(Self::remove_callback);
             (*pdrv.get()).id_table = T::ID_TABLE.as_ptr();
@@ -70,7 +65,7 @@ unsafe fn register(
 
         // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
         to_result(unsafe {
-            bindings::__pci_register_driver(pdrv.get(), module.0, name.as_char_ptr())
+            bindings::__pci_register_driver(pdrv.get(), TM::OWNER.as_ptr(), TM::NAME.as_char_ptr())
         })
     }
 
rust/kernel/platform.rs +4 -8
index bddb593cee7b..a4678af3b891 100644
@@ -13,8 +13,8 @@
     irq::{self, IrqRequest},
     of,
     prelude::*,
+    this_module::ThisModule,
     types::Opaque,
-    ThisModule,
 };
 
 use core::{
@@ -31,11 +31,7 @@
 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
     type RegType = bindings::platform_driver;
 
-    unsafe fn register(
-        pdrv: &Opaque<Self::RegType>,
-        name: &'static CStr,
-        module: &'static ThisModule,
-    ) -> Result {
+    unsafe fn register<TM: ThisModule>(pdrv: &Opaque<Self::RegType>) -> Result {
         let of_table = match T::OF_ID_TABLE {
             Some(table) => table.as_ptr(),
             None => core::ptr::null(),
@@ -48,7 +44,7 @@ unsafe fn register(
 
         // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
         unsafe {
-            (*pdrv.get()).driver.name = name.as_char_ptr();
+            (*pdrv.get()).driver.name = TM::NAME.as_char_ptr();
             (*pdrv.get()).probe = Some(Self::probe_callback);
             (*pdrv.get()).remove = Some(Self::remove_callback);
             (*pdrv.get()).driver.of_match_table = of_table;
@@ -56,7 +52,7 @@ unsafe fn register(
         }
 
         // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
-        to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
+        to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), TM::OWNER.as_ptr()) })
     }
 
     unsafe fn unregister(pdrv: &Opaque<Self::RegType>) {
rust/kernel/usb.rs +4 -9
index d10b65e9fb6a..e7e07360f953 100644
@@ -11,9 +11,8 @@
     driver,
     error::{from_result, to_result, Result},
     prelude::*,
-    str::CStr,
+    this_module::ThisModule,
     types::{AlwaysRefCounted, Opaque},
-    ThisModule,
 };
 use core::{
     marker::PhantomData,
@@ -32,14 +31,10 @@
 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
     type RegType = bindings::usb_driver;
 
-    unsafe fn register(
-        udrv: &Opaque<Self::RegType>,
-        name: &'static CStr,
-        module: &'static ThisModule,
-    ) -> Result {
+    unsafe fn register<TM: ThisModule>(udrv: &Opaque<Self::RegType>) -> Result {
         // SAFETY: It's safe to set the fields of `struct usb_driver` on initialization.
         unsafe {
-            (*udrv.get()).name = name.as_char_ptr();
+            (*udrv.get()).name = TM::NAME.as_char_ptr();
             (*udrv.get()).probe = Some(Self::probe_callback);
             (*udrv.get()).disconnect = Some(Self::disconnect_callback);
             (*udrv.get()).id_table = T::ID_TABLE.as_ptr();
@@ -47,7 +42,7 @@ unsafe fn register(
 
         // SAFETY: `udrv` is guaranteed to be a valid `RegType`.
         to_result(unsafe {
-            bindings::usb_register_driver(udrv.get(), module.0, name.as_char_ptr())
+            bindings::usb_register_driver(udrv.get(), TM::OWNER.as_ptr(), TM::NAME.as_char_ptr())
         })
     }
 
samples/rust/rust_driver_auxiliary.rs +3 -3
index 84d67c5c87c8..8536a8eba45d 100644
@@ -111,10 +111,10 @@ struct SampleModule {
 }
 
 impl InPlaceModule for SampleModule {
-    fn init(module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
+    fn init(_module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
         try_pin_init!(Self {
-            _pci_driver <- driver::Registration::new(MODULE_NAME, module),
-            _aux_driver <- driver::Registration::new(MODULE_NAME, module),
+            _pci_driver <- driver::Registration::new::<THIS_MODULE>(),
+            _aux_driver <- driver::Registration::new::<THIS_MODULE>(),
         })
     }
 }
Signature · 1 line
2.43.0
#13 lore raw

RFC PATCH v3 12/15 rust: phy: make Registration::register() use new ThisModule

In reply to Kari Argillander

Switch Registration::register() to take the owning module via the ThisModule abstraction instead of an explicit module parameter.

The function is now generic over TM: ThisModule, allowing the module owner to be resolved at compile time through TM::OWNER. This unifies the way THIS_MODULE is passed to Rust abstractions and avoids threading module pointers manually through the API.

This also removes redundant parameters and prevents accidental mismatches between the registered drivers and their owning module.

---
 rust/kernel/net/phy.rs | 29 +++++++++++++++++++----------
 1 file changed, 19 insertions(+), 10 deletions(-)
rust/kernel/net/phy.rs +19 -10
index 3ca99db5cccf..ef9c4be4f1ad 100644
@@ -6,8 +6,17 @@
 //!
 //! C headers: [`include/linux/phy.h`](srctree/include/linux/phy.h).
 
-use crate::{device_id::RawDeviceId, error::*, prelude::*, types::Opaque};
-use core::{marker::PhantomData, ptr::addr_of_mut};
+use crate::{
+    device_id::RawDeviceId,
+    error::*,
+    prelude::*,
+    this_module::ThisModule,
+    types::Opaque, //
+};
+use core::{
+    marker::PhantomData,
+    ptr::addr_of_mut, //
+};
 
 pub mod reg;
 
@@ -648,10 +657,7 @@ unsafe impl Send for Registration {}
 
 impl Registration {
     /// Registers a PHY driver.
-    pub fn register(
-        module: &'static crate::ThisModule,
-        drivers: Pin<&'static mut [DriverVTable]>,
-    ) -> Result<Self> {
+    pub fn register<TM: ThisModule>(drivers: Pin<&'static mut [DriverVTable]>) -> Result<Self> {
         if drivers.is_empty() {
             return Err(code::EINVAL);
         }
@@ -659,7 +665,11 @@ pub fn register(
         // the `drivers` slice are initialized properly. `drivers` will not be moved.
         // So it's just an FFI call.
         to_result(unsafe {
-            bindings::phy_drivers_register(drivers[0].0.get(), drivers.len().try_into()?, module.0)
+            bindings::phy_drivers_register(
+                drivers[0].0.get(),
+                drivers.len().try_into()?,
+                TM::OWNER.as_ptr(),
+            )
         })?;
         // INVARIANT: The `drivers` slice is successfully registered to the kernel via `phy_drivers_register`.
         Ok(Registration { drivers })
@@ -889,12 +899,11 @@ struct Module {
                 [$($crate::net::phy::create_phy_driver::<$driver>()),+];
 
             impl $crate::Module for Module {
-                fn init(module: &'static $crate::ThisModule) -> Result<Self> {
+                fn init(_module: &'static $crate::ThisModule) -> Result<Self> {
                     // SAFETY: The anonymous constant guarantees that nobody else can access
                     // the `DRIVERS` static. The array is used only in the C side.
                     let drivers = unsafe { &mut DRIVERS };
-                    let mut reg = $crate::net::phy::Registration::register(
-                        module,
+                    let mut reg = $crate::net::phy::Registration::register::<crate::THIS_MODULE>(
                         ::core::pin::Pin::static_mut(drivers),
                     )?;
                     Ok(Module { _reg: reg })
Signature · 1 line
2.43.0
#14 lore raw

RFC PATCH v3 13/15 rust: remove module argument from InPlaceModule::init()

In reply to Kari Argillander

InPlaceModule::init() has ThisModule argument. However modules always have THIS_MODULE made by module! macro. So it is unnecessary to pass same information through this function. End goal is to make idea of THIS_MODULE simpler. Driver getting this THIS_MODULE from multiple places is confusing. So let's just stick with THIS_MODULE as that also works in const context very easily.

---
 drivers/android/binder/rust_binder_main.rs | 2 +-
 drivers/block/rnull/rnull.rs               | 2 +-
 lib/find_bit_benchmark_rust.rs             | 3 +--
 rust/kernel/configfs.rs                    | 3 +--
 rust/kernel/driver.rs                      | 4 +---
 rust/kernel/firmware.rs                    | 2 +-
 rust/kernel/lib.rs                         | 8 ++++----
 rust/kernel/net/phy.rs                     | 2 +-
 rust/kernel/sync/lock/global.rs            | 4 ++--
 rust/macros/lib.rs                         | 4 ++--
 rust/macros/module.rs                      | 2 +-
 samples/rust/rust_configfs.rs              | 2 +-
 samples/rust/rust_debugfs_scoped.rs        | 2 +-
 samples/rust/rust_driver_auxiliary.rs      | 2 +-
 samples/rust/rust_driver_faux.rs           | 2 +-
 samples/rust/rust_minimal.rs               | 2 +-
 samples/rust/rust_misc_device.rs           | 2 +-
 samples/rust/rust_print_main.rs            | 2 +-
 18 files changed, 23 insertions(+), 27 deletions(-)
drivers/android/binder/rust_binder_main.rs +1 -1
index fc921c0e1116..8b865112e60c 100644
@@ -291,7 +291,7 @@ fn ptr_align(value: usize) -> Option<usize> {
 struct BinderModule {}
 
 impl kernel::Module for BinderModule {
-    fn init(_module: &'static kernel::ThisModule) -> Result<Self> {
+    fn init() -> Result<Self> {
         // SAFETY: The module initializer never runs twice, so we only call this once.
         unsafe { crate::context::CONTEXTS.init() };
 
drivers/block/rnull/rnull.rs +1 -1
index 862369ab9b5c..a9be1b2187f4 100644
@@ -36,7 +36,7 @@ struct NullBlkModule {
 }
 
 impl kernel::InPlaceModule for NullBlkModule {
-    fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
+    fn init() -> impl PinInit<Self, Error> {
         pr_info!("Rust null_blk loaded\n");
 
         try_pin_init!(Self {
lib/find_bit_benchmark_rust.rs +1 -2
index 6bdc51de2f30..5c231569d887 100644
@@ -7,7 +7,6 @@
 use kernel::error::{code, Result};
 use kernel::prelude::module;
 use kernel::time::{Instant, Monotonic};
-use kernel::ThisModule;
 use kernel::{pr_cont, pr_err};
 
 const BITMAP_LEN: usize = 4096 * 8 * 10;
@@ -88,7 +87,7 @@ fn find_bit_test() {
 }
 
 impl kernel::Module for Benchmark {
-    fn init(_module: &'static ThisModule) -> Result<Self> {
+    fn init() -> Result<Self> {
         find_bit_test();
         // Return error so test module can be inserted again without rmmod.
         Err(code::EINVAL)
rust/kernel/configfs.rs +1 -2
index 908cb98d404f..2af63f7daef2 100644
@@ -27,7 +27,6 @@
 //! use kernel::new_mutex;
 //! use kernel::page::PAGE_SIZE;
 //! use kernel::sync::Mutex;
-//! use kernel::ThisModule;
 //!
 //! #[pin_data]
 //! struct RustConfigfs {
@@ -36,7 +35,7 @@
 //! }
 //!
 //! impl kernel::InPlaceModule for RustConfigfs {
-//!     fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
+//!     fn init() -> impl PinInit<Self, Error> {
 //!         pr_info!("Rust configfs sample (init)\n");
 //!
 //!         let item_type = configfs_attrs! {
rust/kernel/driver.rs +1 -3
index dc7522c4ebda..de77f95d7fe0 100644
@@ -201,9 +201,7 @@ struct DriverModule {
         }
 
         impl $crate::InPlaceModule for DriverModule {
-            fn init(
-                _module: &'static $crate::ThisModule
-            ) -> impl ::pin_init::PinInit<Self, $crate::error::Error> {
+            fn init() -> impl ::pin_init::PinInit<Self, $crate::error::Error> {
                 $crate::try_pin_init!(Self {
                     _driver <- $crate::driver::Registration::new::<crate::THIS_MODULE>(),
                 })
rust/kernel/firmware.rs +1 -1
index 2702f01c0403..42bae71f6af1 100644
@@ -157,7 +157,7 @@ unsafe impl Sync for Firmware {}
 /// # struct MyModule;
 /// #
 /// # impl kernel::Module for MyModule {
-/// #     fn init(_module: &'static ThisModule) -> Result<Self> {
+/// #     fn init() -> Result<Self> {
 /// #         Ok(Self)
 /// #     }
 /// # }
rust/kernel/lib.rs +4 -4
index 4b899f75e56d..d6111a44fb3a 100644
@@ -175,7 +175,7 @@ pub trait Module: Sized + Sync + Send {
     /// should do.
     ///
     /// Equivalent to the `module_init` macro in the C API.
-    fn init(module: &'static ThisModule) -> error::Result<Self>;
+    fn init() -> error::Result<Self>;
 }
 
 /// A module that is pinned and initialised in-place.
@@ -183,13 +183,13 @@ pub trait InPlaceModule: Sync + Send {
     /// Creates an initialiser for the module.
     ///
     /// It is called when the module is loaded.
-    fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error>;
+    fn init() -> impl pin_init::PinInit<Self, error::Error>;
 }
 
 impl<T: Module> InPlaceModule for T {
-    fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Error> {
+    fn init() -> impl pin_init::PinInit<Self, error::Error> {
         let initer = move |slot: *mut Self| {
-            let m = <Self as Module>::init(module)?;
+            let m = <Self as Module>::init()?;
 
             // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`.
             unsafe { slot.write(m) };
rust/kernel/net/phy.rs +1 -1
index ef9c4be4f1ad..4c4dc376bd5a 100644
@@ -899,7 +899,7 @@ struct Module {
                 [$($crate::net::phy::create_phy_driver::<$driver>()),+];
 
             impl $crate::Module for Module {
-                fn init(_module: &'static $crate::ThisModule) -> Result<Self> {
+                fn init() -> Result<Self> {
                     // SAFETY: The anonymous constant guarantees that nobody else can access
                     // the `DRIVERS` static. The array is used only in the C side.
                     let drivers = unsafe { &mut DRIVERS };
rust/kernel/sync/lock/global.rs +2 -2
index eab48108a4ae..7fde464462d1 100644
@@ -203,7 +203,7 @@ pub fn get_mut(&mut self) -> &mut T {
 /// }
 ///
 /// impl kernel::Module for MyModule {
-///     fn init(_module: &'static ThisModule) -> Result<Self> {
+///     fn init() -> Result<Self> {
 ///         // SAFETY: Called exactly once.
 ///         unsafe { MY_COUNTER.init() };
 ///
@@ -243,7 +243,7 @@ pub fn get_mut(&mut self) -> &mut T {
 /// }
 ///
 /// impl kernel::Module for MyModule {
-///     fn init(_module: &'static ThisModule) -> Result<Self> {
+///     fn init() -> Result<Self> {
 ///         // SAFETY: Called exactly once.
 ///         unsafe { MY_MUTEX.init() };
 ///
rust/macros/lib.rs +2 -2
index b38002151871..d22a93696209 100644
@@ -80,7 +80,7 @@
 /// struct MyModule(i32);
 ///
 /// impl kernel::Module for MyModule {
-///     fn init(_module: &'static ThisModule) -> Result<Self> {
+///     fn init() -> Result<Self> {
 ///         let foo: i32 = 42;
 ///         pr_info!("I contain:  {}\n", foo);
 ///         pr_info!("i32 param is:  {}\n", module_parameters::my_parameter.read());
@@ -114,7 +114,7 @@
 /// struct MyDeviceDriverModule;
 ///
 /// impl kernel::Module for MyDeviceDriverModule {
-///     fn init(_module: &'static ThisModule) -> Result<Self> {
+///     fn init() -> Result<Self> {
 ///         Ok(Self)
 ///     }
 /// }
rust/macros/module.rs +1 -1
index 1bcd703735fe..7473a377a3bd 100644
@@ -490,7 +490,7 @@ mod __module_init {{
                     /// This function must only be called once.
                     unsafe fn __init() -> ::kernel::ffi::c_int {{
                         let initer =
-                            <{type_} as ::kernel::InPlaceModule>::init(&super::super::THIS_MODULE.as_ref());
+                            <{type_} as ::kernel::InPlaceModule>::init();
                         // SAFETY: No data race, since `__MOD` can only be accessed by this module
                         // and there only `__init` and `__exit` access it. These functions are only
                         // called once and `__exit` cannot be called before or during `__init`.
samples/rust/rust_configfs.rs +1 -1
index 0ccc7553ef39..f34260793677 100644
@@ -42,7 +42,7 @@ fn new() -> impl PinInit<Self, Error> {
 }
 
 impl kernel::InPlaceModule for RustConfigfs {
-    fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
+    fn init() -> impl PinInit<Self, Error> {
         pr_info!("Rust configfs sample (init)\n");
 
         // Define a subsystem with the data type `Configuration`, two
samples/rust/rust_debugfs_scoped.rs +1 -1
index 6a575a15a2c2..75897e02766b 100644
@@ -134,7 +134,7 @@ fn init_control(base_dir: &Dir, dyn_dirs: Dir) -> impl PinInit<Scope<ModuleData>
 }
 
 impl kernel::Module for RustScopedDebugFs {
-    fn init(_module: &'static kernel::ThisModule) -> Result<Self> {
+    fn init() -> Result<Self> {
         let base_dir = Dir::new(c"rust_scoped_debugfs");
         let dyn_dirs = base_dir.subdir(c"dynamic");
         Ok(Self {
samples/rust/rust_driver_auxiliary.rs +1 -1
index 8536a8eba45d..528866b953aa 100644
@@ -111,7 +111,7 @@ struct SampleModule {
 }
 
 impl InPlaceModule for SampleModule {
-    fn init(_module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
+    fn init() -> impl PinInit<Self, Error> {
         try_pin_init!(Self {
             _pci_driver <- driver::Registration::new::<THIS_MODULE>(),
             _aux_driver <- driver::Registration::new::<THIS_MODULE>(),
samples/rust/rust_driver_faux.rs +1 -1
index 5330b77ea986..2653b2ec3338 100644
@@ -21,7 +21,7 @@ struct SampleModule {
 }
 
 impl Module for SampleModule {
-    fn init(_module: &'static ThisModule) -> Result<Self> {
+    fn init() -> Result<Self> {
         pr_info!("Initialising Rust Faux Device Sample\n");
 
         let reg = faux::Registration::new(c"rust-faux-sample-device", None)?;
samples/rust/rust_minimal.rs +1 -1
index 8eb9583571d7..c024f8083499 100644
@@ -23,7 +23,7 @@ struct RustMinimal {
 }
 
 impl kernel::Module for RustMinimal {
-    fn init(_module: &'static ThisModule) -> Result<Self> {
+    fn init() -> Result<Self> {
         pr_info!("Rust minimal sample (init)\n");
         pr_info!("Am I built-in? {}\n", !cfg!(MODULE));
         pr_info!(
samples/rust/rust_misc_device.rs +1 -1
index 464e3026e6e3..709adf4a6026 100644
@@ -128,7 +128,7 @@ struct RustMiscDeviceModule {
 }
 
 impl kernel::InPlaceModule for RustMiscDeviceModule {
-    fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
+    fn init() -> impl PinInit<Self, Error> {
         pr_info!("Initialising Rust Misc Device Sample\n");
 
         let options = MiscDeviceOptions {
samples/rust/rust_print_main.rs +1 -1
index 4095c72afeab..de1bf7b80153 100644
@@ -59,7 +59,7 @@ fn arc_dyn_print(arc: &Arc<dyn Display>) {
 }
 
 impl kernel::Module for RustPrint {
-    fn init(_module: &'static ThisModule) -> Result<Self> {
+    fn init() -> Result<Self> {
         pr_info!("Rust printing macros sample (init)\n");
 
         pr_emerg!("Emergency message (level 0) without args\n");
Signature · 1 line
2.43.0
#15 lore raw

RFC PATCH v3 14/15 rust: remove kernel::ModuleMetadata

In reply to Kari Argillander

We have all information available also in THIS_MODULE. All users use that already so there is no users for this anymore so remove it.

---
 rust/kernel/lib.rs    | 6 ------
 rust/macros/module.rs | 8 --------
 2 files changed, 14 deletions(-)
rust/kernel/lib.rs +0 -6
index d6111a44fb3a..3acc60a83b09 100644
@@ -201,12 +201,6 @@ fn init() -> impl pin_init::PinInit<Self, error::Error> {
     }
 }
 
-/// Metadata attached to a [`Module`] or [`InPlaceModule`].
-pub trait ModuleMetadata {
-    /// The name of the module as specified in the `module!` macro.
-    const NAME: &'static crate::str::CStr;
-}
-
 /// Equivalent to `THIS_MODULE` in the C API.
 ///
 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
rust/macros/module.rs +0 -8
index 7473a377a3bd..97635aed1598 100644
@@ -374,14 +374,6 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
             ::kernel::create_this_module!(\"{name}\");
 
 
-            /// The `LocalModule` type is the type of the module created by `module!`,
-            /// `module_pci_driver!`, `module_platform_driver!`, etc.
-            type LocalModule = {type_};
-
-            impl ::kernel::ModuleMetadata for {type_} {{
-                const NAME: &'static ::kernel::str::CStr = c\"{name}\";
-            }}
-
             // Double nested modules, since then nobody can access the public items inside.
             mod __module_init {{
                 mod __module_init {{
Signature · 1 line
2.43.0
#16 lore raw

RFC PATCH v3 15/15 rust: remove old version of ThisModule

In reply to Kari Argillander

There are now users anymore which use old ThisModule. Also new ThisModule did have couple quirks which where there only to probide fucntionality what old ThisModule provided. Those also are not needed anymore.

---
 rust/kernel/lib.rs     | 47 -----------------------------------------------
 rust/kernel/prelude.rs |  2 +-
 2 files changed, 1 insertion(+), 48 deletions(-)
rust/kernel/lib.rs +0 -47
index 3acc60a83b09..e709f85ec4b5 100644
@@ -201,32 +201,6 @@ fn init() -> impl pin_init::PinInit<Self, error::Error> {
     }
 }
 
-/// Equivalent to `THIS_MODULE` in the C API.
-///
-/// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
-pub struct ThisModule(*mut bindings::module);
-
-// SAFETY: `THIS_MODULE` may be used from all threads within a module.
-unsafe impl Sync for ThisModule {}
-
-impl ThisModule {
-    /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
-    ///
-    /// # Safety
-    ///
-    /// The pointer must be equal to the right `THIS_MODULE`.
-    pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
-        ThisModule(ptr)
-    }
-
-    /// Access the raw pointer for this module.
-    ///
-    /// It is up to the user to use it correctly.
-    pub const fn as_ptr(&self) -> *mut bindings::module {
-        self.0
-    }
-}
-
 pub mod this_module {
     //! Access to the module identity and ownership information.
     //!
@@ -360,27 +334,6 @@ impl THIS_MODULE {
                 pub const fn name() -> &'static ::kernel::str::CStr {
                     $crate::c_str!($name)
                 }
-
-                // TODO: Temporary to provide functionality old `THIS_MODULE` provided.
-                // SAFETY: `__this_module` is constructed by the kernel at load time and
-                // will not be freed until the module is unloaded.
-                const ThisModule: ::kernel::ThisModule = unsafe {{
-                    ::kernel::ThisModule::from_ptr(
-                        <Self as ::kernel::this_module::ThisModule>::OWNER.as_ptr()
-                    )
-                }};
-
-                /// Gets a pointer to the underlying `struct module`.
-                // TODO: Temporary to provide functionality old `THIS_MODULE` provided.
-                pub const fn as_ptr(&self) -> *mut ::kernel::bindings::module {{
-                    Self::ThisModule.as_ptr()
-                }}
-
-                /// Gets a reference to the underlying `ThisModule`.
-                /// TODO: Temporary to provide functionality old `THIS_MODULE` provided.
-                pub const fn as_ref(&self) -> &'static ::kernel::ThisModule {{
-                    &Self::ThisModule
-                }}
             }
         };
     }
rust/kernel/prelude.rs +1 -1
index 2877e3f7b6d3..66974ec20ef4 100644
@@ -43,7 +43,7 @@
 
 pub use super::error::{code::*, Error, Result};
 
-pub use super::{str::CStrExt as _, ThisModule};
+pub use super::str::CStrExt as _;
 
 pub use super::init::InPlaceInit;
 
Signature · 1 line
2.43.0
#17 lore raw
In reply to Kari Argillander

Le 10/01/2026 à 16:07, Kari Argillander a écrit :

Quoted 7 lines

Still RFC. Not all people for each subsystems are not included yet as this touch quite lot of things. I would like to get feed back is this resonable seperation and how we will land this. I have tried my best so that it can be applied in multiple staged if needed. I have not receive any feedback on this series and that is little bit worrying.

Introduce new ThisModule trait and THIS_MODULE impl.

Shouldn't it be called this_module instead of ThisModule ?

I don't know much about rust but this naming looks wrong, it is the kind of crap we see in C++.
Linux Kernel codying style says: ... mixed-case names are frowned upon ... [Documentation/process/coding-style.rst, §4) Naming]

Is THIS_MODULE a constant or an enum ? [Documentation/process/coding-style.rst, §12) Macros, Enums and RTL]

Christophe

#18 lore raw
Quoted 2 lines · Christophe Leroy (CS GROUP)

Shouldn't it be called this_module instead of ThisModule ?

The common Rust style, which we use in the kernel as well, uses several kinds of casing to make it easy to distinguish between types of entities at a glance.

Traits use CamelCase, like structs and enums. So if ThisModule is a trait, that would be its case.

But, for instance, if it were a constant, then it would be THIS_MODULE.

Details at https://rust-lang.github.io/api-guidelines/naming.html -- sometimes we may diverge from that, but in general we follow the usual style.

Cheers,
Miguel

#19 lore raw
In reply to Kari Argillander
Quoted 6 lines · Kari Argillander

So currently we have problem that we are not always filling .owner field example for file_operations. I think we can enable const_refs_to_static already as that is in 1.78 and is stable in 1.83. So that fits perfecly for us. This also seems to be quite request feature but I did not found that no one has ever suggested that we just enable this.

For context, we have been tracking that feature (as well as const_mut_refs) precisely for THIS_MODULE:

https://github.com/Rust-for-Linux/linux/issues/2

There is also a test that Ralf added upstream back then:

https://github.com/rust-lang/rust/blob/main/tests/ui/consts/const-ref-to-static-linux-vtable.rs

(Not sure what you mean by "quite request" though)

Cheers,
Miguel

maintainer
#20 lore raw
In reply to Kari Argillander
Quoted 14 lines · Kari Argillander

Still RFC. Not all people for each subsystems are not included yet as this touch quite lot of things. I would like to get feed back is this resonable seperation and how we will land this. I have tried my best so that it can be applied in multiple staged if needed. I have not receive any feedback on this series and that is little bit worrying.

Introduce new ThisModule trait and THIS_MODULE impl.

So currently we have problem that we are not always filling .owner field example for file_operations. I think we can enable const_refs_to_static already as that is in 1.78 and is stable in 1.83. So that fits perfecly for us. This also seems to be quite request feature but I did not found that no one has ever suggested that we just enable this.

Quoted 4 lines

So basic idea is that we will have ThisModule trait which is used kernel side. Module side we will always use THIS_MODULE. That is completly private for modules and kernel crate cannot use it. Currently we have THIS_MODULE, LocalModule and

Why is trait needed? Couldn't this just be a const THIS_MODULE required for vtable?

Best,
Gary

Quoted 109 lines

module: &' static ThisModule

on init functions. As we anyway need THIS_MODULE just use that for all of these things.

Patches 1-2 introduce THIS_MODULE and ThisModule trait. Patches 3-12 can be applied any order after 1-2. Patch 13 depends on patches 11-12.
Patches 14-15 are clean up patches and depends 1-13.

Argillander

To: Miguel Ojeda <[email protected]>
To: Boqun Feng <[email protected]>
To: Gary Guo <[email protected]>
To: Björn Roy Baron <[email protected]>
To: Benno Lossin <[email protected]>
To: Andreas Hindborg <[email protected]>
To: Alice Ryhl <[email protected]>
To: Trevor Gross <[email protected]>
To: Danilo Krummrich <[email protected]>

To: Alexandre Courbot <[email protected]>

Cc Luis Chamberlain <[email protected]>
Cc Petr Pavlu <[email protected]>
Cc Daniel Gomez <[email protected]>
Cc Sami Tolvanen <[email protected]>
Cc Aaron Tomlin <[email protected]>

---
Changes in v3:
- Edit cover.
- Seperate module name changes to seperate patches.
- Rebase top of next 20260109
- Seperate configfs changes to own commit.
- Fix one place still used M over TM for ThisModule.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Patches are now sepereted properly.
- Removed debugfs changes as that is not so clear to me.
- Remove module parameter and just used THIS_MODULE everywhere.
- Made macro to make THIS_MODULE.
- Doc tests also have THIS_MODULE.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Kari Argillander (15):
rust: enable const_refs_to_static feature
rust: add new ThisModule trait and THIS_MODULE impl
rust: miscdevice: fix use after free because missing .owner
rust: block: fix missing owner field in block_device_operations
rust: drm: fix missing owner in file_operations
rust: configfs: use new THIS_MODULE
rust: binder: use new THIS_MODULE
rust: firmware: use THIS_MODULE over LocalModule for name
gpu: nova-core: use THIS_MODULE over LocalModule for name
samples: rust: auxiliary: use THIS_MODULE over LocalModule for name
rust: driver: make RegistrationOps::register() to use new ThisModule
rust: phy: make Registration::register() use new ThisModule
rust: remove module argument from InPlaceModule::init()
rust: remove kernel::ModuleMetadata
rust: remove old version of ThisModule

 drivers/android/binder/rust_binder_main.rs |   5 +-
 drivers/block/rnull/configfs.rs            |   2 +-
 drivers/block/rnull/rnull.rs               |   3 +-
 drivers/gpu/drm/nova/driver.rs             |   2 +
 drivers/gpu/drm/tyr/driver.rs              |   2 +
 drivers/gpu/nova-core/nova_core.rs         |   2 +-
 lib/find_bit_benchmark_rust.rs             |   3 +-
 rust/kernel/auxiliary.rs                   |  16 +--
 rust/kernel/block/mq.rs                    |   1 +
 rust/kernel/block/mq/gen_disk.rs           |  30 +-----
 rust/kernel/block/mq/operations.rs         |  30 ++++++
 rust/kernel/configfs.rs                    |  49 ++++-----
 rust/kernel/driver.rs                      |  31 +++---
 rust/kernel/drm/device.rs                  |   2 +-
 rust/kernel/drm/driver.rs                  |   4 +
 rust/kernel/drm/gem/mod.rs                 |   5 +-
 rust/kernel/firmware.rs                    |   4 +-
 rust/kernel/i2c.rs                         |  11 +-
 rust/kernel/lib.rs                         | 161 ++++++++++++++++++++++++-----
 rust/kernel/miscdevice.rs                  |   5 +
 rust/kernel/net/phy.rs                     |  29 ++++--
 rust/kernel/pci.rs                         |  15 +--
 rust/kernel/platform.rs                    |  12 +--
 rust/kernel/prelude.rs                     |   2 +-
 rust/kernel/sync/lock/global.rs            |   4 +-
 rust/kernel/usb.rs                         |  13 +--
 rust/macros/lib.rs                         |   4 +-
 rust/macros/module.rs                      |  24 +----
 samples/rust/rust_configfs.rs              |   2 +-
 samples/rust/rust_debugfs_scoped.rs        |   2 +-
 samples/rust/rust_driver_auxiliary.rs      |   8 +-
 samples/rust/rust_driver_faux.rs           |   2 +-
 samples/rust/rust_minimal.rs               |   2 +-
 samples/rust/rust_misc_device.rs           |   3 +-
 samples/rust/rust_print_main.rs            |   2 +-
 scripts/rustdoc_test_gen.rs                |   2 +
 36 files changed, 298 insertions(+), 196 deletions(-)

---
base-commit: f417b7ffcbef7d76b0d8860518f50dae0e7e5eda
change-id: 20251230-this_module_fix-a390bff24897

Best regards,