Skip to contentSkip to conversation

Fix missing fops.owner in Rust DRM/misc abstractions

PATCH Applied Alvin Sun 4 participants 22 messages Aug 11 – Aug 13

Subsystems (23)
lore
Share & tools
lore

Alvin Sun

author
#0 lore raw

v10 cover Fix missing fops.owner in Rust DRM/misc abstractions

During tyr debugfs development, a kernel NULL pointer dereference was encountered after rmmod tyr while gnome-shell still held /dev/card1 open:

```
  [158827.868132] Unable to handle kernel NULL pointer dereference at virtual address 0000000000000000
  [158827.868918] Mem abort info:
  [158827.869177]   ESR = 0x0000000086000004
  [158827.869519]   EC = 0x21: IABT (current EL), IL = 32 bits
  [158827.870000]   SET = 0, FnV = 0
  [158827.870281]   EA = 0, S1PTW = 0
  [158827.870571]   FSC = 0x04: level 0 translation fault
  [158827.871043] user pgtable: 4k pages, 48-bit VAs, pgdp=0000000108dec000
  [158827.871623] [0000000000000000] pgd=0000000000000000, p4d=0000000000000000
  [158827.872242] Internal error: Oops: 0000000086000004 [#1]  SMP
  [158827.872246] Modules linked in: tyr sunrpc snd_soc_simple_card rk805_pwrkey snd_soc_simple_card_utils rtw88_8822bu display_connector rtw88_usb rtw88_8822b snd_soc_rockchip_i2s_tdm snd_soc_hdmi_codec
  rtw88_core]
  [158827.872337] CPU: 4 UID: 1000 PID: 11276 Comm: gnome-s:disk$0 Tainted: G                 N  7.1.0-rc1+ #331 PREEMPT
  [158827.880534] Tainted: [N]=TEST
  [158827.880535] Hardware name: FriendlyElec NanoPi R6C/NanoPi R6C, BIOS v1.1 04/09/2025
  [158827.880538] pstate: 60400009 (nZCv daif +PAN -UAO -TCO -DIT -SSBS BTYPE=--)
  [158827.880542] pc : 0x0
  [158827.880547] lr : _RNvNtCs257m05FHVbX_3tyr2vm8pt_unmap+0x8c/0x12c [tyr]
  [158827.880578] sp : ffff800083c236b0
  [158827.880579] x29: ffff800083c236d0 x28: ffff00013f8a0000 x27: 0000000000000000
  [158827.880585] x26: 000000000000007c x25: ffff000108e6ed80 x24: 0000000000401000
  [158827.880590] x23: 0000000000000000 x22: 0000000040000000 x21: 0000000000001000
  [158827.880595] x20: ffff00010f778138 x19: 0000000000400000 x18: 00000000ffffffff
  [158827.880600] x17: 000000040044ffff x16: 045000f2b5503510 x15: 0720072007200720
  [158827.880606] x14: 0720072007200720 x13: 0000000000401000 x12: 0000000000400000
  [158827.880611] x11: ffff800083c239d0 x10: ffff000141e4fd88 x9 : 0000000000000000
  [158827.880615] x8 : 0000000000000000 x7 : 0000000000000000 x6 : 0000000000400000
  [158827.880620] x5 : ffff00013f8a0000 x4 : 0000000000000000 x3 : 0000000000000001
  [158827.880625] x2 : 0000000000001000 x1 : 0000000000400000 x0 : ffff00010f778138
  [158827.880630] Call trace:
  [158827.880632]  0x0 (P)
  [158827.880635]  _RNvXs6_NtCs257m05FHVbX_3tyr2vmNtB5_9GpuVmDataNtNtNtCsgmSOfgXi5CZ_6kernel3drm5gpuvm11DriverGpuVm13sm_step_unmap+0x3c/0x120 [tyr]
  [158827.891166]  _RNvMs4_NtNtNtCsgmSOfgXi5CZ_6kernel3drm5gpuvm6sm_opsINtB7_5GpuVmNtNtCs257m05FHVbX_3tyr2vm9GpuVmDataE13sm_step_unmapB13_+0x18/0x34 [tyr]
  [158827.891187]  op_unmap_cb+0x78/0xb0
  [158827.891196]  __drm_gpuvm_sm_unmap+0x18c/0x1b4
  [158827.891204]  drm_gpuvm_sm_unmap+0x38/0x4c
  [158827.891209]  _RNvMs5_NtCs257m05FHVbX_3tyr2vmNtB5_2Vm7exec_op+0x1cc/0x254 [tyr]
  [158827.894085]  _RNvMs5_NtCs257m05FHVbX_3tyr2vmNtB5_2Vm11unmap_range+0x124/0x188 [tyr]
  [158827.894105]  _RINvNtCs5hGKnPbRUFW_4core3ptr13drop_in_placeNtNtCs257m05FHVbX_3tyr3gem8KernelBoEBK_+0x44/0xd8 [tyr]
  [158827.894125]  _RINvNtCs5hGKnPbRUFW_4core3ptr13drop_in_placeINtNtNtCsgmSOfgXi5CZ_6kernel5alloc4kvec3VecNtNtCs257m05FHVbX_3tyr2fw7SectionNtNtBL_9allocator7KmallocEEB1r_+0x3c/0x100 [tyr]
  [158827.894147]  _RINvNtCs5hGKnPbRUFW_4core3ptr13drop_in_placeINtNtNtCsgmSOfgXi5CZ_6kernel4sync3arc3ArcNtNtCs257m05FHVbX_3tyr2fw8FirmwareEEB1p_+0x94/0x190 [tyr]
  [158827.894167]  _RNvMs4_NtNtCsgmSOfgXi5CZ_6kernel3drm6deviceINtB5_6DeviceNtNtCs257m05FHVbX_3tyr6driver12TyrDrmDriverE7releaseBW_+0x30/0x98 [tyr]
  [158827.899550]  drm_dev_put.part.0+0x88/0xc0
  [158827.899557]  drm_minor_release+0x18/0x28
  [158827.899562]  drm_release+0x144/0x170
  [158827.899567]  __fput+0xe4/0x30c
  [158827.899573]  ____fput+0x14/0x20
  [158827.899579]  task_work_run+0x7c/0xe8
  [158827.899586]  do_exit+0x2a8/0xac4
  [158827.899590]  do_group_exit+0x34/0x90
  [158827.899594]  get_signal+0xaac/0xabc
  [158827.899599]  arch_do_signal_or_restart+0x90/0x3e8
  [158827.899606]  exit_to_user_mode_loop+0x140/0x1d0
  [158827.899613]  el0_svc+0x2f4/0x2f8
  [158827.899620]  el0t_64_sync_handler+0xa0/0xe4
  [158827.899627]  el0t_64_sync+0x198/0x19c
  [158827.899632] ---[ end trace 0000000000000000 ]---
```

The root cause: fops.owner was NULL in Rust DRM drivers, so the kernel never blocked module unloading while file descriptors were open. This leads to use-after-free when drm_release (or other fops) is called on freed module code.

The series moves THIS_MODULE into the ModuleMetadata as a const, threads it through #[vtable] to set fops.owner in DRM/miscdevice, and updates configfs and rnull to use this_module::<LocalModule>().

Assisted-by opencode:glm-5.2

---
Changes in v10:
- Drop prerequisite patches that have been merged, to
resolve rebase conflicts.
- Link to v9: https://lore.kernel.org/r/[email protected]

Changes in v9:
- Rename the binder commit prefix from rust: binder: to rust_binder:
to match the in-tree module name.
- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- Remove unused crate::LocalModule import in rnull configfs.
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- Use crate::LocalModule in configfs_attrs! and silence clippy::crate_in_macro_def, per Gary's review.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Update MAINTAINERS to cover the new rust/kernel/module.rs.
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- Add #[inline] to the this_module() helper.
- Fix configfs doc comment to reference crate::LocalModule instead of
bare LocalModule.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Move module-related types into a new rust/kernel/module.rs.
- Migrate binder from the module!-generated THIS_MODULE static to this_module::<LocalModule>().
- Reorganise the series so that every commit builds independently, and
drop the legacy THIS_MODULE static once all users are migrated.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Renamed vtable associated type ThisModule to OwnerModule
- Added this_module() helper for ergonomic THIS_MODULE access
- Refined vtable macro implementation: one-liner detection and single defined_items set
- Reordered commits to place doctest fallback before vtable auto-insert
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Merged old static THIS_MODULE and v1's MODULE_PTR into a single ModuleMetadata::THIS_MODULE const
- #[vtable] macro now auto-inserts type ThisModule, removing all per-driver manual patches from v1
- Added configfs & rnull usage site updates and doctest LocalModule fallback
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alvin Sun (10):
rust: module: move module types into module.rs
rust: module: add THIS_MODULE const to ModuleMetadata trait
rust: doctest: add LocalModule fallback for #[vtable] ThisModule
rust: macros: auto-insert OwnerModule in #[vtable]
rust: drm: set fops.owner from driver module pointer
rust: miscdevice: set fops.owner from driver module pointer
rust: configfs: use LocalModule for THIS_MODULE
rust_binder: use LocalModule for THIS_MODULE
rust: macros: remove THIS_MODULE static from module!
rust: module: update MAINTAINERS to cover module.rs

 MAINTAINERS                                |  2 +-
 drivers/android/binder/rust_binder_main.rs |  3 +-
 drivers/block/rnull/configfs.rs            |  5 +-
 rust/kernel/auxiliary.rs                   |  2 +-
 rust/kernel/configfs.rs                    |  9 ++--
 rust/kernel/drm/device.rs                  |  3 +-
 rust/kernel/drm/gem/mod.rs                 |  4 +-
 rust/kernel/i2c.rs                         |  2 +-
 rust/kernel/lib.rs                         | 75 +++-------------------------
 rust/kernel/miscdevice.rs                  |  4 +-
 rust/kernel/module.rs                      | 80 ++++++++++++++++++++++++++++++
 rust/kernel/net/phy.rs                     |  6 ++-
 rust/kernel/pci.rs                         |  2 +-
 rust/kernel/platform.rs                    |  2 +-
 rust/kernel/usb.rs                         |  2 +-
 rust/macros/lib.rs                         |  6 +++
 rust/macros/module.rs                      | 34 ++++++-------
 rust/macros/vtable.rs                      | 41 +++++++++++++--
 scripts/rustdoc_test_gen.rs                | 16 ++++++
 19 files changed, 189 insertions(+), 109 deletions(-)

---
base-commit: 2ee859ebf156157609f71060ae472711c8cbc326
change-id: 20260519-fix-fops-owner-e3a77bb27c6c
prerequisite-patch-id: 347c5a3c6dbef9832bfce8419fc23e6e08ba477f

Best regards,

Signature · 1 line
Alvin Sun <[email protected]>
author
#1 lore raw

PATCH v10 1/10 rust: module: move module types into `module.rs`

Move Module, InPlaceModule, ModuleMetadata and ThisModule from lib.rs into a new rust/kernel/module.rs. Re-export them from lib.rs to avoid tree-wide changes.

Switch six bus driver registrations from module.0 to the public ThisModule::as_ptr() accessor, since the field is no longer visible outside the new module submodule.

No functional change.

---
 rust/kernel/auxiliary.rs |  2 +-
 rust/kernel/i2c.rs       |  2 +-
 rust/kernel/lib.rs       | 75 +++++-------------------------------------------
 rust/kernel/module.rs    | 71 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/net/phy.rs   |  6 +++-
 rust/kernel/pci.rs       |  2 +-
 rust/kernel/platform.rs  |  2 +-
 rust/kernel/usb.rs       |  2 +-
 8 files changed, 88 insertions(+), 74 deletions(-)
rust/kernel/auxiliary.rs +1 -1
index c42928d5a2393..cc9745fbf179e 100644
@@ -69,7 +69,7 @@ unsafe fn register(
 
         // SAFETY: `adrv` is guaranteed to be a valid `DriverType`.
         to_result(unsafe {
-            bindings::__auxiliary_driver_register(adrv.get(), module.0, name.as_char_ptr())
+            bindings::__auxiliary_driver_register(adrv.get(), module.as_ptr(), name.as_char_ptr())
         })
     }
 
rust/kernel/i2c.rs +1 -1
index 624b971ca8b0b..dd9271af5eb8b 100644
@@ -142,7 +142,7 @@ unsafe fn register(
         }
 
         // SAFETY: `idrv` is guaranteed to be a valid `DriverType`.
-        to_result(unsafe { bindings::i2c_register_driver(module.0, idrv.get()) })
+        to_result(unsafe { bindings::i2c_register_driver(module.as_ptr(), idrv.get()) })
     }
 
     unsafe fn unregister(idrv: &Opaque<Self::DriverType>) {
rust/kernel/lib.rs +7 -68

92 lines not on this page · raw message

rust/kernel/module.rs new file +71 -0

71 lines not on this page · raw message

rust/kernel/net/phy.rs +5 -1
index 3ca99db5cccf2..8b7036b8fe480 100644
@@ -659,7 +659,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()?,
+                module.as_ptr(),
+            )
         })?;
         // INVARIANT: The `drivers` slice is successfully registered to the kernel via `phy_drivers_register`.
         Ok(Registration { drivers })
rust/kernel/pci.rs +1 -1
index 5071cae6543fd..4def9ca1824ce 100644
@@ -86,7 +86,7 @@ unsafe fn register(
 
         // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`.
         to_result(unsafe {
-            bindings::__pci_register_driver(pdrv.get(), module.0, name.as_char_ptr())
+            bindings::__pci_register_driver(pdrv.get(), module.as_ptr(), name.as_char_ptr())
         })
     }
 
rust/kernel/platform.rs +1 -1
index d41555a4b31d2..5a5f4156d79be 100644
@@ -83,7 +83,7 @@ unsafe fn register(
 
         // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`.
         to_result(unsafe {
-            bindings::__platform_driver_register(pdrv.get(), module.0, name.as_char_ptr())
+            bindings::__platform_driver_register(pdrv.get(), module.as_ptr(), name.as_char_ptr())
         })
     }
 
rust/kernel/usb.rs +1 -1
index 7aff0c82d0afc..870423806e4f5 100644
@@ -63,7 +63,7 @@ unsafe fn register(
 
         // SAFETY: `udrv` is guaranteed to be a valid `DriverType`.
         to_result(unsafe {
-            bindings::usb_register_driver(udrv.get(), module.0, name.as_char_ptr())
+            bindings::usb_register_driver(udrv.get(), module.as_ptr(), name.as_char_ptr())
         })
     }
 
Signature · 1 line
2.43.0
author
#2 lore raw

PATCH v10 2/10 rust: module: add `THIS_MODULE` const to `ModuleMetadata` trait

In reply to Alvin Sun

Since const_refs_to_static has been stable as of the MSRV bump, a ThisModule pointer can now be used in const contexts.

Add a THIS_MODULE const to the ModuleMetadata trait so that modules can provide their ThisModule pointer in const contexts such as static file_operations.

Add a this_module() helper to retrieve the THIS_MODULE pointer of a given module type, and update __init to use it instead of the THIS_MODULE static generated by the module! macro.

The static THIS_MODULE generated by the module! macro is retained for backwards compatibility with existing users and removed in a later patch once all references have been migrated.

---
 rust/kernel/module.rs |  9 +++++++++
 rust/macros/module.rs | 18 +++++++++++++++++-
 2 files changed, 26 insertions(+), 1 deletion(-)
rust/kernel/module.rs +9 -0
index be242a82e86d2..d713705984477 100644
@@ -42,6 +42,15 @@ fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, crate::erro
 pub trait ModuleMetadata {
     /// The name of the module as specified in the `module!` macro.
     const NAME: &'static crate::str::CStr;
+
+    /// The module's `THIS_MODULE` pointer.
+    const THIS_MODULE: ThisModule;
+}
+
+/// Returns a reference to the `THIS_MODULE` of the given module type.
+#[inline]
+pub const fn this_module<M: ModuleMetadata>() -> &'static ThisModule {
+    &M::THIS_MODULE
 }
 
 /// Equivalent to `THIS_MODULE` in the C API.
rust/macros/module.rs +17 -1
index 06c18e2075083..aa9a618d5d19e 100644
@@ -519,6 +519,22 @@ pub(crate) fn module(info: ModuleInfo) -> Result<TokenStream> {
 
         impl ::kernel::ModuleMetadata for #type_ {
             const NAME: &'static ::kernel::str::CStr = #name_cstr;
+
+            #[cfg(MODULE)]
+            const THIS_MODULE: ::kernel::ThisModule = {
+                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 { ::kernel::ThisModule::from_ptr(__this_module.get()) }
+            };
+
+            #[cfg(not(MODULE))]
+            const THIS_MODULE: ::kernel::ThisModule = unsafe {
+                ::kernel::ThisModule::from_ptr(::core::ptr::null_mut())
+            };
         }
 
         // Double nested modules, since then nobody can access the public items inside.
@@ -616,7 +632,7 @@ pub extern "C" fn #ident_exit() {
                 /// This function must only be called once.
                 unsafe fn __init() -> ::kernel::ffi::c_int {
                     let initer = <super::super::LocalModule as ::kernel::InPlaceModule>::init(
-                        &super::super::THIS_MODULE
+                        ::kernel::module::this_module::<super::super::LocalModule>()
                     );
                     // 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
Signature · 1 line
2.43.0
author
#3 lore raw

PATCH v10 3/10 rust: doctest: add LocalModule fallback for #[vtable] ThisModule

In reply to Alvin Sun

Add a LocalModule struct with a null-pointer ModuleMetadata impl in the doctest harness, so that crate::LocalModule (auto-inserted by #[vtable]) resolves correctly when there is no module! macro.

---
 scripts/rustdoc_test_gen.rs | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
scripts/rustdoc_test_gen.rs +16 -0
index d61a77219a8c2..9913f78650365 100644
@@ -232,6 +232,22 @@ macro_rules! assert_eq {{
 
 const __LOG_PREFIX: &[u8] = b"rust_doctests_kernel\0";
 
+/// Dummy module type for doctest context.
+struct LocalModule;
+
+use kernel::{{
+    str::CStr,
+    ModuleMetadata,
+    ThisModule, //
+}};
+use core::ptr::null_mut;
+
+impl ModuleMetadata for LocalModule {{
+    const NAME: &'static CStr = c"rust_doctests_kernel";
+    // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully.
+    const THIS_MODULE: ThisModule = unsafe {{ ThisModule::from_ptr(null_mut()) }};
+}}
+
 {rust_tests}
 "#
     )
Signature · 1 line
2.43.0
author
#4 lore raw

PATCH v10 4/10 rust: macros: auto-insert OwnerModule in #[vtable]

In reply to Alvin Sun

Auto-add type OwnerModule: ::kernel::ModuleMetadata; as a required associated type on the trait side if not already defined, and auto-insert type OwnerModule = crate::LocalModule; on the impl side if not explicitly provided, eliminating the need to manually declare and implement OwnerModule in every vtable trait and impl.

---
 rust/macros/lib.rs    |  6 ++++++
 rust/macros/vtable.rs | 41 ++++++++++++++++++++++++++++++++++++-----
 2 files changed, 42 insertions(+), 5 deletions(-)
rust/macros/lib.rs +6 -0
index 4a48fabbc2682..3f4a980f5ae68 100644
@@ -177,6 +177,12 @@ pub fn module(input: TokenStream) -> TokenStream {
 ///
 /// This macro should not be used when all functions are required.
 ///
+/// Additionally, this macro automatically handles the `OwnerModule`
+/// associated type: on the trait side, `type OwnerModule: ModuleMetadata;`
+/// is added as a required associated type if not already defined; on the
+/// impl side, `type OwnerModule = LocalModule;` is automatically inserted
+/// if not explicitly defined.
+///
 /// # Examples
 ///
 /// ```
rust/macros/vtable.rs +36 -5

67 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#5 lore raw

PATCH v10 5/10 rust: drm: set fops.owner from driver module pointer

In reply to Alvin Sun

Change create_fops() to accept an owner module pointer instead of hardcoding null_mut(), ensuring the kernel correctly tracks the module owning the DRM device's file operations.

---
 rust/kernel/drm/device.rs  | 3 ++-
 rust/kernel/drm/gem/mod.rs | 4 ++--
 2 files changed, 4 insertions(+), 3 deletions(-)
rust/kernel/drm/device.rs +2 -1
index 477cf771fb10e..73fbd551f0811 100644
@@ -203,7 +203,8 @@ const fn compute_features() -> u32 {
         fops: &Self::GEM_FOPS,
     };
 
-    const GEM_FOPS: bindings::file_operations = drm::gem::create_fops();
+    const GEM_FOPS: bindings::file_operations =
+        drm::gem::create_fops(crate::module::this_module::<T::OwnerModule>().as_ptr());
 
     /// Create a new `UnregisteredDevice` for a `drm::Driver`.
     ///
rust/kernel/drm/gem/mod.rs +2 -2
index c8b66d8168719..a7ba1453d40b9 100644
@@ -387,10 +387,10 @@ impl<T: DriverObject, Ctx: DeviceContext> AllocImpl for Object<T, Ctx> {
     };
 }
 
-pub(super) const fn create_fops() -> bindings::file_operations {
+pub(super) const fn create_fops(owner: *mut bindings::module) -> bindings::file_operations {
     let mut fops: bindings::file_operations = pin_init::zeroed();
 
-    fops.owner = core::ptr::null_mut();
+    fops.owner = owner;
     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
author
#6 lore raw

PATCH v10 6/10 rust: miscdevice: set fops.owner from driver module pointer

In reply to Alvin Sun

Set the miscdevice fops owner field from the driver module pointer via the this_module::<T::OwnerModule>() helper, instead of defaulting to null.

---
 rust/kernel/miscdevice.rs | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
rust/kernel/miscdevice.rs +3 -1
index 83ce50def5ac9..2a4329f98614e 100644
@@ -24,12 +24,13 @@
         IovIterSource, //
     },
     mm::virt::VmaNew,
+    module::this_module,
     prelude::*,
     seq_file::SeqFile,
     types::{
         ForeignOwnable,
         Opaque, //
-    },
+    }, //
 };
 use core::marker::PhantomData;
 
@@ -430,6 +431,7 @@ impl<T: MiscDevice> MiscdeviceVTable<T> {
         } else {
             None
         },
+        owner: this_module::<T::OwnerModule>().as_ptr(),
         ..pin_init::zeroed()
     };
 
Signature · 1 line
2.43.0
author
#7 lore raw

PATCH v10 7/10 rust: configfs: use `LocalModule` for `THIS_MODULE`

In reply to Alvin Sun

Replace the THIS_MODULE static reference in the configfs_attrs! macro with this_module::<LocalModule>(), and update rnull to import LocalModule instead of THIS_MODULE, consistent with the move of THIS_MODULE into the ModuleMetadata trait.

---
 drivers/block/rnull/configfs.rs | 5 +----
 rust/kernel/configfs.rs         | 9 ++++++---
 2 files changed, 7 insertions(+), 7 deletions(-)
drivers/block/rnull/configfs.rs +1 -4
index c10a55fc58948..9b28be2150933 100644
@@ -1,9 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use super::{
-    NullBlkDevice,
-    THIS_MODULE, //
-};
+use super::NullBlkDevice;
 use kernel::{
     block::mq::gen_disk::{
         GenDisk,
rust/kernel/configfs.rs +6 -3
index 2339c6467325d..cd082b83e9e74 100644
@@ -875,13 +875,14 @@ fn as_ptr(&self) -> *const bindings::config_item_type {
 ///                 configfs::Subsystem<Configuration>,
 ///                 Configuration
 ///                 >::new_with_child_ctor::<N,Child>(
-///             &THIS_MODULE,
+///             ::kernel::module::this_module::<crate::LocalModule>(),
 ///             &CONFIGURATION_ATTRS
 ///         );
 ///
 ///     &CONFIGURATION_TPE
 /// }
 /// ```
+#[allow(clippy::crate_in_macro_def)]
 #[macro_export]
 macro_rules! configfs_attrs {
     (
@@ -1021,7 +1022,8 @@ 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 >]
+                            $crate::module::this_module::<crate::LocalModule>(),
+                            &[<$ data:upper _ATTRS >]
                         );
                 )?
 
@@ -1030,7 +1032,8 @@ 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 >]
+                                $crate::module::this_module::<crate::LocalModule>(),
+                                &[<$ data:upper _ATTRS >]
                             );
                 )?
 
Signature · 1 line
2.43.0
author
#8 lore raw

PATCH v10 8/10 rust_binder: use `LocalModule` for `THIS_MODULE`

In reply to Alvin Sun

Replace the THIS_MODULE static reference in the binder fops with this_module::<LocalModule>(), consistent with the move of THIS_MODULE into the ModuleMetadata trait.

---
 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 dc1941cd2407b..d6ceebbd5f94e 100644
@@ -17,6 +17,7 @@
     bindings::{self, seq_file},
     fs::File,
     list::{ListArc, ListArcSafe, ListLinksSelfPtr, TryNewListArc},
+    module::this_module,
     prelude::*,
     seq_file::SeqFile,
     seq_print,
@@ -318,7 +319,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::<LocalModule>().as_ptr(),
         poll: Some(rust_binder_poll),
         unlocked_ioctl: Some(rust_binder_ioctl),
         compat_ioctl: bindings::compat_ptr_ioctl,
Signature · 1 line
2.43.0
author
#9 lore raw

PATCH v10 9/10 rust: macros: remove `THIS_MODULE` static from `module!`

In reply to Alvin Sun

All users have been migrated to ModuleMetadata::THIS_MODULE const or this_module::<LocalModule>() helper. The static THIS_MODULE generated by the module! macro is no longer referenced anywhere, so remove it to avoid having two sources of the same ThisModule pointer.

---
 rust/macros/module.rs | 16 ----------------
 1 file changed, 16 deletions(-)
rust/macros/module.rs +0 -16
index aa9a618d5d19e..23b6a1b456b80 100644
@@ -497,22 +497,6 @@ pub(crate) fn module(info: ModuleInfo) -> Result<TokenStream> {
         /// Used by the printing macros, e.g. [`info!`].
         const __LOG_PREFIX: &[u8] = #name_cstr.to_bytes_with_nul();
 
-        // 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::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.
         type LocalModule = #type_;
Signature · 1 line
2.43.0
author
#10 lore raw

PATCH v10 10/10 rust: module: update MAINTAINERS to cover module.rs

In reply to Alvin Sun

Module types now live in rust/kernel/module.rs alongside rust/kernel/module_param.rs. Update the MODULE SUPPORT file pattern from rust/kernel/module_param.rs to rust/kernel/module*.rs so both files are covered.

---
 MAINTAINERS | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
MAINTAINERS +1 -1
index 8014b9f8253ed..ce84c56f21375 100644
@@ -18189,7 +18189,7 @@ F:	include/linux/module*.h
 F:	kernel/module/
 F:	lib/test_kmod.c
 F:	lib/tests/module/
-F:	rust/kernel/module_param.rs
+F:	rust/kernel/module*.rs
 F:	rust/macros/module.rs
 F:	scripts/module*
 F:	tools/testing/selftests/kmod/
Signature · 1 line
2.43.0
Applied
#11 lore raw
In reply to Alvin Sun
Quoted 4 lines · Alvin Sun

The series moves THIS_MODULE into the ModuleMetadata as a const, threads it through #[vtable] to set fops.owner in DRM/miscdevice, and updates configfs and rnull to use this_module::<LocalModule>().

Applied to rust-next -- thanks everyone!

[ Fixed clippy::undocumented_unsafe_blocks lint by wrapping with
a block. Added interim #[allow(dead_code)]. - Miguel ]

[ Fixed rusttest by adding a dummy LocalModule. Removed interim
#[allow(dead_code)]. - Miguel ]

[ Rebased to avoid the imports cleanup patch. - Miguel ]

[ Removed Acked-by and Cc. - Miguel ]

By the way, I removed the Acked-by in that last patch since I think it came from an older version as a series-tag that didn't have the patch. Please let me know if I should re-add it.

And since I was editing that commit for that reason, I took the chance to remove the Cc because Petr already gave the Acked-by which you collected, so normally you don't need to keep both in that case.

I hope that clarifies! :)

Cheers,
Miguel

maintainer
#12 lore raw

(Cc: Mark)

Quoted 7 lines · Miguel Ojeda
Quoted 4 lines · Alvin Sun

The series moves THIS_MODULE into the ModuleMetadata as a const, threads it through #[vtable] to set fops.owner in DRM/miscdevice, and updates configfs and rnull to use this_module::<LocalModule>().

Applied to rust-next -- thanks everyone!

This series has a semantic conflict with both the driver-core and the drm-rust tree:

@Mark: When you merge driver-core-next after rust-next (which I think is the case) then you need to include the diff in [1] into the merge.

In drm-rust-next the build fails with:

	error[E0425]: cannot find type `LocalModule` in the crate root
	   --> rust/kernel/drm/gem/shmem.rs:628:5
	    |
	628 |     #[vtable]
	    |     ^^^^^^^^^ not found in the crate root
	    |
	    = note: this error originates in the attribute macro `vtable` (in Nightly builds, run with -Z macro-backtrace for more info)

which is because the kunit test in rust/kernel/drm/gem/shmem.rs uses the #[vtable] macro.

This should be fixed up with a patch on top of this series in rust-next.

I came up with to potential solutions [2] and [3]. I think with the new build system we want [3], but I'm not entirely sure this works correctly with the current build system in all cases (at least it did survive my tests).

Alternatively, we could just open-code a dummy module as in [2] for now.

[1] driver-core-next merge fixup

rust/kernel/serdev.rs +1 -1
index a4927452016e..17ca504b7f8d 100644
@@ -87,7 +87,7 @@ unsafe fn register(
         }
 
         // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
-        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.0) })
+        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.as_ptr()) })
     }
 
     unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {

[2] Open-coded dummy module

rust/kernel/lib.rs +9 -0
index c04e6c5aa7e0..274924cfcc05 100644
@@ -157,6 +157,15 @@
 /// Prefix to appear before log messages printed from within the `kernel` crate.
 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
 
+/// Dummy module type for `#[vtable]` impl blocks within the kernel crate (e.g. kunit tests).
+struct LocalModule;
+
+impl ModuleMetadata for LocalModule {
+    const NAME: &'static str::CStr = c"rust_kernel";
+    // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully.
+    const THIS_MODULE: ThisModule = unsafe { ThisModule::from_ptr(core::ptr::null_mut()) };
+}
+
 #[cfg(not(testlib))]
 #[panic_handler]
 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {

[3] Allow module!() for kernel crate

rust/Makefile +4 -0
index 48adcd9b7851..4f6bf1b4d194 100644
@@ -279,6 +279,7 @@ rustdoc-pin_init: $(src)/pin-init/src/lib.rs rustdoc-pin_init_internal \
        +$(call if_changed,rustdoc)
 
 rustdoc-kernel: private is-kernel-object := y
+rustdoc-kernel: private rustc_target_envs = RUST_MODFILE=kernel/lib.rs
 rustdoc-kernel: private rustc_target_flags = --extern ffi --extern pin_init \
     --extern build_error --extern macros \
     --extern bindings --extern uapi \
@@ -351,6 +352,7 @@ rusttestlib-pin_init: $(src)/pin-init/src/lib.rs rusttestlib-macros \
     rusttestlib-pin_init_internal $(obj)/$(libpin_init_internal_name) FORCE
        +$(call if_changed,rustc_test_library)
 
+rusttestlib-kernel: private rustc_target_envs = RUST_MODFILE=kernel/lib.rs
 rusttestlib-kernel: private rustc_target_flags = --extern ffi \
     --extern build_error --extern macros --extern pin_init \
     --extern bindings --extern uapi \
@@ -386,6 +388,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $<
        rm -rf $(objtree)/$(obj)/test/doctests/kernel; \
        mkdir -p $(objtree)/$(obj)/test/doctests/kernel; \
        $(rustc_target_envs) \
+       RUST_MODFILE=kernel/lib.rs \
        OBJTREE=$(abspath $(objtree)) \
        $(RUSTDOC) --test $(filter-out --remap-path-scope=%,$(rust_flags)) \
                -L$(objtree)/$(obj) --extern ffi --extern pin_init \
@@ -788,6 +791,7 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \
     $(obj)/uapi/uapi_generated.rs FORCE
        +$(call if_changed_rule,rustc_library)
 
+$(obj)/kernel.o: private rustc_target_envs = RUST_MODFILE=kernel/lib.rs
 $(obj)/kernel.o: private rustc_target_flags = --extern ffi --extern pin_init \
     --extern build_error --extern macros --extern bindings --extern uapi \
     --extern zerocopy --extern zerocopy_derive
rust/kernel/lib.rs +15 -2
index c04e6c5aa7e0..7df9159788ad 100644
@@ -154,8 +154,21 @@
 };
 pub use uapi;
 
-/// Prefix to appear before log messages printed from within the `kernel` crate.
-const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
+struct KernelCrateModule;
+
+impl Module for KernelCrateModule {
+    fn init(_module: &'static ThisModule) -> error::Result<Self> {
+        Ok(Self)
+    }
+}
+
+macros::module! {
+    type: KernelCrateModule,
+    name: "rust_kernel",
+    authors: ["Rust for Linux Contributors"],
+    description: "The kernel crate",
+    license: "GPL",
+}
 
 #[cfg(not(testlib))]
 #[panic_handler]
reviewer
#13 lore raw
Quoted 45 lines · Danilo Krummrich

(Cc: Mark)

Quoted 7 lines · Miguel Ojeda
Quoted 4 lines · Alvin Sun

The series moves THIS_MODULE into the ModuleMetadata as a const, threads it through #[vtable] to set fops.owner in DRM/miscdevice, and updates configfs and rnull to use this_module::<LocalModule>().

Applied to rust-next -- thanks everyone!

This series has a semantic conflict with both the driver-core and the drm-rust tree:

@Mark: When you merge driver-core-next after rust-next (which I think is the case) then you need to include the diff in [1] into the merge.

In drm-rust-next the build fails with:

	error[E0425]: cannot find type `LocalModule` in the crate root
	   --> rust/kernel/drm/gem/shmem.rs:628:5
	    |
	628 |     #[vtable]
	    |     ^^^^^^^^^ not found in the crate root
	    |
	    = note: this error originates in the attribute macro `vtable` (in Nightly builds, run with -Z macro-backtrace for more info)

which is because the kunit test in rust/kernel/drm/gem/shmem.rs uses the #[vtable] macro.

This should be fixed up with a patch on top of this series in rust-next.

I came up with to potential solutions [2] and [3]. I think with the new build system we want [3], but I'm not entirely sure this works correctly with the current build system in all cases (at least it did survive my tests).

Alternatively, we could just open-code a dummy module as in [2] for now.

[1] driver-core-next merge fixup

rust/kernel/serdev.rs +0 -0
index a4927452016e..17ca504b7f8d 100644

rust/kernel/serdev.rs unsafe fn register( · line 90

Quoted 5 lines
rust/kernel/serdev.rs +1 -1
@@ -87,7 +87,7 @@ unsafe fn register(
         }
 
         // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
-        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.0) })
+        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.as_ptr()) })

module.0 shouldn't be used in the first place, it just happens to be visible due to the unfortunate placement at crate root.

Perhaps you can update driver-core tree to use as_ptr()? It was already there and not newly introduced in the series.

Quoted 16 lines
rust/kernel/serdev.rs +0 -0
     }
 
     unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {

[2] Open-coded dummy module

rust/kernel/lib.rs +2 -0
index c04e6c5aa7e0..274924cfcc05 100644
@@ -157,6 +157,15 @@
 /// Prefix to appear before log messages printed from within the `kernel` crate.
 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
 
+/// Dummy module type for `#[vtable]` impl blocks within the kernel crate (e.g. kunit tests).
+struct LocalModule;

rust/kernel/lib.rs line 171

Quoted 10 lines
rust/kernel/lib.rs +7 -0
+
+impl ModuleMetadata for LocalModule {
+    const NAME: &'static str::CStr = c"rust_kernel";
+    // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully.
+    const THIS_MODULE: ThisModule = unsafe { ThisModule::from_ptr(core::ptr::null_mut()) };
+}
+
 #[cfg(not(testlib))]
 #[panic_handler]
 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {

IMO this is the correct way, also consistent with

https://lore.kernel.org/rust-for-linux/[email protected]/

It might make sense to add this to rust-next.

Best,
Gary

maintainer
#14 lore raw
Quoted 55 lines · Gary Guo
Quoted 45 lines · Danilo Krummrich

(Cc: Mark)

Quoted 7 lines · Miguel Ojeda
Quoted 4 lines · Alvin Sun

The series moves THIS_MODULE into the ModuleMetadata as a const, threads it through #[vtable] to set fops.owner in DRM/miscdevice, and updates configfs and rnull to use this_module::<LocalModule>().

Applied to rust-next -- thanks everyone!

This series has a semantic conflict with both the driver-core and the drm-rust tree:

@Mark: When you merge driver-core-next after rust-next (which I think is the case) then you need to include the diff in [1] into the merge.

In drm-rust-next the build fails with:

	error[E0425]: cannot find type `LocalModule` in the crate root
	   --> rust/kernel/drm/gem/shmem.rs:628:5
	    |
	628 |     #[vtable]
	    |     ^^^^^^^^^ not found in the crate root
	    |
	    = note: this error originates in the attribute macro `vtable` (in Nightly builds, run with -Z macro-backtrace for more info)

which is because the kunit test in rust/kernel/drm/gem/shmem.rs uses the #[vtable] macro.

This should be fixed up with a patch on top of this series in rust-next.

I came up with to potential solutions [2] and [3]. I think with the new build system we want [3], but I'm not entirely sure this works correctly with the current build system in all cases (at least it did survive my tests).

Alternatively, we could just open-code a dummy module as in [2] for now.

[1] driver-core-next merge fixup

rust/kernel/serdev.rs +0 -0
index a4927452016e..17ca504b7f8d 100644

rust/kernel/serdev.rs unsafe fn register( · line 90

Quoted 5 lines
rust/kernel/serdev.rs +1 -1
@@ -87,7 +87,7 @@ unsafe fn register(
         }
 
         // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
-        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.0) })
+        to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.as_ptr()) })

module.0 shouldn't be used in the first place, it just happens to be visible due to the unfortunate placement at crate root.

Quoted 2 lines

Perhaps you can update driver-core tree to use as_ptr()? It was already there and not newly introduced in the series.

Heh, I just remembered that patch 1 of this series did fix this in a couple of places and assumed that it was introduced in the same patch without looking further.

In that case I can throw in a patch in the driver-core tree; will send it tomorrow.

Quoted 29 lines
Quoted 16 lines
rust/kernel/serdev.rs +0 -0
     }
 
     unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {

[2] Open-coded dummy module

rust/kernel/lib.rs +2 -0
index c04e6c5aa7e0..274924cfcc05 100644
@@ -157,6 +157,15 @@
 /// Prefix to appear before log messages printed from within the `kernel` crate.
 const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
 
+/// Dummy module type for `#[vtable]` impl blocks within the kernel crate (e.g. kunit tests).
+struct LocalModule;

rust/kernel/lib.rs line 171

Quoted 10 lines
rust/kernel/lib.rs +7 -0
+
+impl ModuleMetadata for LocalModule {
+    const NAME: &'static str::CStr = c"rust_kernel";
+    // SAFETY: `try_module_get`/`module_put` handle null module pointers gracefully.
+    const THIS_MODULE: ThisModule = unsafe { ThisModule::from_ptr(core::ptr::null_mut()) };
+}
+
 #[cfg(not(testlib))]
 #[panic_handler]
 fn panic(info: &core::panic::PanicInfo<'_>) -> ! {

IMO this is the correct way, also consistent with

Quoted 3 lines

https://lore.kernel.org/rust-for-linux/[email protected]/

It might make sense to add this to rust-next.

I feel like [3] is the superior solution (just unsure about the build system implications); once we have the new build system some subsystem crates will be actual modules, some will be always built-in. So, in general I think we want to use the module!() macro.

#15 lore raw
In reply to Gary Guo
Quoted 6 lines · Gary Guo

IMO this is the correct way, also consistent with

https://lore.kernel.org/rust-for-linux/[email protected]/

It might make sense to add this to rust-next.

Yeah, it is also consistent (in the sense of adding a fallback) with the other fix I added when applying the series for the macros doctest; and the kernel crate is not an actual module yet.

I guess yet another solution would be to have an even more local fallback, but that would be too local in my opinion, i.e. we will want to use it elsewhere sooner or later.

So I could fold [2] into commit 98f256e27262, but a commit on top is fine, I will reference that commit from the new one instead.

Ok, done -- Danilo, I took your diff and converted it into a proper commit, please double-check you are OK with the Signed-off-by:

ec6fcf8a175a ("rust: kernel: add LocalModule fallback for
#[vtable] impls")

Thanks!

Cheers,
Miguel

maintainer
#16 lore raw
Quoted 2 lines · Miguel Ojeda

Ok, done -- Danilo, I took your diff and converted it into a proper commit, please double-check you are OK with the Signed-off-by:

Of course, thanks!

- Danilo

#17 lore raw
In reply to Miguel Ojeda
Quoted 6 lines · Miguel Ojeda

Ok, done -- Danilo, I took your diff and converted it into a proper commit, please double-check you are OK with the Signed-off-by:

ec6fcf8a175a ("rust: kernel: add LocalModule fallback for
#[vtable] impls")

We also need an allow(dead_code) until we actually use it
unconditionally: a2595ed13816 instead.

Cheers,
Miguel

author
#18 lore raw
In reply to Miguel Ojeda
Quoted 14 lines · Miguel Ojeda
Quoted 5 lines · Gary Guo

IMO this is the correct way, also consistent with

https://lore.kernel.org/rust-for-linux/[email protected]/

It might make sense to add this to rust-next.

Yeah, it is also consistent (in the sense of adding a fallback) with the other fix I added when applying the series for the macros doctest; and the kernel crate is not an actual module yet.

I guess yet another solution would be to have an even more local fallback, but that would be too local in my opinion, i.e. we will want to use it elsewhere sooner or later.

Quoted 8 lines

So I could fold [2] into commit 98f256e27262, but a commit on top is fine, I will reference that commit from the new one instead.

Ok, done -- Danilo, I took your diff and converted it into a proper commit, please double-check you are OK with the Signed-off-by:

ec6fcf8a175a ("rust: kernel: add LocalModule fallback for
#[vtable] impls")

I was just looking at the difference between the doctest and in-crate #[kunit_tests] test paths — thanks for taking care of this.

I'll look into [3] once the new build system lands.

Best regards,
Alvin

Quoted 5 lines

Thanks!

Cheers,
Miguel

#19 lore raw
In reply to Danilo Krummrich
Quoted 6 lines · Danilo Krummrich

This series has a semantic conflict with both the driver-core and the drm-rust tree:

@Mark: When you merge driver-core-next after rust-next (which I think is the case) then you need to include the diff in [1] into the merge.

Mark: in case it helps to make it clearer and so you don't have to read much, that [1] diff still needs to be included (i.e. the rest of the discussion and the commit I added is independent).

Thanks!

Cheers,
Miguel

author
#20 lore raw
In reply to Miguel Ojeda
Quoted 3 lines · Miguel Ojeda

By the way, I removed the Acked-by in that last patch since I think it came from an older version as a series-tag that didn't have the patch. Please let me know if I should re-add it.

Hi Miguel,

Thanks for applying the series and catching the stray Acked-by. It was a v5 series-tag, from before the MAINTAINERS patch existed, so no need to re-add it. I'll be more careful with tags in future submissions.

Best regards,
Alvin

#21 lore raw
Quoted 5 lines · Alvin Sun

Thanks for applying the series and catching the stray Acked-by. It was a v5 series-tag, from before the MAINTAINERS patch existed, so no need to re-add it. I'll be more careful with tags in future submissions.

Thanks for confirming! :)

Cheers,
Miguel