Skip to contentSkip to conversation

rust: block: set GenDisk block_device_operations.owner to THIS_MODULE

PATCH Superseded Adarsh Das 2 participants 6 messages Aug 5 – Sep 23

Subsystems (4)
lore
Share & tools
lore

Adarsh Das

author
#0 lore raw

PATCH 1/1 rust: block: set GenDisk block_device_operations.owner to THIS_MODULE

GenDiskBuilder currently installs block_device_operations with owner set to NULL. The block layer uses this field to pin the driver module while block device file operations are in use.

Take the driver's ThisModule in GenDiskBuilder::build() and store the operations table in GenDisk so gendisk->fops stays valid if the disk is moved, such as when rnull keeps it in an Option behind configfs. Update rnull as the in-tree caller.

---
 drivers/block/rnull/configfs.rs  |  1 +
 drivers/block/rnull/rnull.rs     |  3 +-
 rust/kernel/block/mq.rs          |  9 +++--
 rust/kernel/block/mq/gen_disk.rs | 58 +++++++++++++++++++-------------
 4 files changed, 43 insertions(+), 28 deletions(-)
drivers/block/rnull/configfs.rs +1 -0
index 7c2eb5c0b722..bba30d590f68 100644
@@ -147,6 +147,7 @@ fn store(this: &DeviceConfig, page: &[u8]) -> Result {
 
         if !guard.powered && power_op {
             guard.disk = Some(NullBlkDevice::new(
+                &THIS_MODULE,
                 &guard.name,
                 guard.block_size,
                 guard.rotational,
drivers/block/rnull/rnull.rs +2 -1
index 0ca8715febe8..4265a133cbf0 100644
@@ -46,6 +46,7 @@ fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
 
 impl NullBlkDevice {
     fn new(
+        this_module: &'static ThisModule,
         name: &CStr,
         block_size: u32,
         rotational: bool,
@@ -61,7 +62,7 @@ fn new(
             .logical_block_size(block_size)?
             .physical_block_size(block_size)?
             .rotational(rotational)
-            .build(fmt!("{}", name.to_str()?), tagset, queue_data)
+            .build(this_module, fmt!("{}", name.to_str()?), tagset, queue_data)
     }
 }
 
rust/kernel/block/mq.rs +6 -3
index 1fd0d54dd549..33561e0f67af 100644
@@ -8,8 +8,8 @@
 //! - Implement [`Operations`] for a type `T`.
 //! - Create a [`TagSet<T>`].
 //! - Create a [`GenDisk<T>`], via the [`GenDiskBuilder`].
-//! - Add the disk to the system by calling [`GenDiskBuilder::build`] passing in
-//!   the `TagSet` reference.
+//! - Add the disk to the system by calling [`GenDiskBuilder::build`], passing in
+//!   the driver's [`ThisModule`], the disk name, the `TagSet`, and queue data.
 //!
 //! The types available in this module that have direct C counterparts are:
 //!
@@ -86,9 +86,12 @@
 //!
 //! let tagset: Arc<TagSet<MyBlkDevice>> =
 //!     Arc::pin_init(TagSet::new(1, 256, 1), flags::GFP_KERNEL)?;
+//! # // SAFETY: Dummy `ThisModule` for doctest compilation only.
+//! # static THIS_MODULE: ThisModule =
+//! #     unsafe { ThisModule::from_ptr(core::ptr::null_mut()) };
 //! let mut disk = gen_disk::GenDiskBuilder::new()
 //!     .capacity_sectors(4096)
-//!     .build(fmt!("myblk"), tagset, ())?;
+//!     .build(&THIS_MODULE, fmt!("myblk"), tagset, ())?;
 //!
 //! # Ok::<(), kernel::error::Error>(())
 //! ```
rust/kernel/block/mq/gen_disk.rs +34 -24

86 lines not on this page · raw message

Signature · 1 line
2.55.0
author
#1 lore raw

PATCH v2 1/1 rust: block: set GenDisk block_device_operations.owner to THIS_MODULE

GenDiskBuilder left block_device_operations.owner NULL. Pass the driver's ThisModule into GenDiskBuilder::build(), heap-allocate the operations table, and keep it alive until the gendisk is released via free_disk. Update rnull as the in-tree caller.

v2:
- Free fops in free_disk instead of GenDisk::drop to fix use-after-free when the device stays open after removal. (Sashiko)
- Install the cleanup guard before fops allocation to avoid leaking gendisk on -ENOMEM. (Sashiko)
- Link to v1: https://lore.kernel.org/all/[email protected]/

---
 drivers/block/rnull/configfs.rs  |  1 +
 drivers/block/rnull/rnull.rs     |  3 +-
 rust/kernel/block/mq.rs          |  9 ++--
 rust/kernel/block/mq/gen_disk.rs | 82 ++++++++++++++++++++++----------
 4 files changed, 66 insertions(+), 29 deletions(-)
drivers/block/rnull/configfs.rs +1 -0
index 7c2eb5c0b722..bba30d590f68 100644
@@ -147,6 +147,7 @@ fn store(this: &DeviceConfig, page: &[u8]) -> Result {
 
         if !guard.powered && power_op {
             guard.disk = Some(NullBlkDevice::new(
+                &THIS_MODULE,
                 &guard.name,
                 guard.block_size,
                 guard.rotational,
drivers/block/rnull/rnull.rs +2 -1
index 0ca8715febe8..4265a133cbf0 100644
@@ -46,6 +46,7 @@ fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
 
 impl NullBlkDevice {
     fn new(
+        this_module: &'static ThisModule,
         name: &CStr,
         block_size: u32,
         rotational: bool,
@@ -61,7 +62,7 @@ fn new(
             .logical_block_size(block_size)?
             .physical_block_size(block_size)?
             .rotational(rotational)
-            .build(fmt!("{}", name.to_str()?), tagset, queue_data)
+            .build(this_module, fmt!("{}", name.to_str()?), tagset, queue_data)
     }
 }
 
rust/kernel/block/mq.rs +6 -3
index 1fd0d54dd549..33561e0f67af 100644
@@ -8,8 +8,8 @@
 //! - Implement [`Operations`] for a type `T`.
 //! - Create a [`TagSet<T>`].
 //! - Create a [`GenDisk<T>`], via the [`GenDiskBuilder`].
-//! - Add the disk to the system by calling [`GenDiskBuilder::build`] passing in
-//!   the `TagSet` reference.
+//! - Add the disk to the system by calling [`GenDiskBuilder::build`], passing in
+//!   the driver's [`ThisModule`], the disk name, the `TagSet`, and queue data.
 //!
 //! The types available in this module that have direct C counterparts are:
 //!
@@ -86,9 +86,12 @@
 //!
 //! let tagset: Arc<TagSet<MyBlkDevice>> =
 //!     Arc::pin_init(TagSet::new(1, 256, 1), flags::GFP_KERNEL)?;
+//! # // SAFETY: Dummy `ThisModule` for doctest compilation only.
+//! # static THIS_MODULE: ThisModule =
+//! #     unsafe { ThisModule::from_ptr(core::ptr::null_mut()) };
 //! let mut disk = gen_disk::GenDiskBuilder::new()
 //!     .capacity_sectors(4096)
-//!     .build(fmt!("myblk"), tagset, ())?;
+//!     .build(&THIS_MODULE, fmt!("myblk"), tagset, ())?;
 //!
 //! # Ok::<(), kernel::error::Error>(())
 //! ```
rust/kernel/block/mq/gen_disk.rs +57 -25

109 lines not on this page · raw message

Signature · 1 line
2.55.0
maintainer
#2 lore raw
Quoted 5 lines · Adarsh Das

GenDiskBuilder left block_device_operations.owner NULL. Pass the driver's ThisModule into GenDiskBuilder::build(), heap-allocate the operations table, and keep it alive until the gendisk is released via free_disk. Update rnull as the in-tree caller.

Quoted 8 lines

v2:
- Free fops in free_disk instead of GenDisk::drop to fix use-after-free when the device stays open after removal. (Sashiko)
- Install the cleanup guard before fops allocation to avoid leaking gendisk on -ENOMEM. (Sashiko)
- Link to v1: https://lore.kernel.org/all/[email protected]/

The reason owner is not set is that we want to keep the vtable const. But with Alvins recent series [1], we should be able to set owner in const context.

Can you rebase on his series and see if you can make it work in const context?

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]

author
#3 lore raw

PATCH v3 1/1 rust: block: set GenDisk block_device_operations.owner to THIS_MODULE

In reply to Adarsh Das

GenDiskBuilder left block_device_operations.owner NULL. Set owner from a const block_device_operations table using this_module::<M>() and update rnull to pass NullBlkModule.

Add ModuleMetadata::THIS_MODULE and this_module() so the owner pointer is available in const context. Rebased on Alvins fix-fops-owner series [1].

v2:
- Free fops in free_disk instead of GenDisk::drop to fix use-after-free when the device stays open after removal. (Sashiko)
- Install the cleanup guard before fops allocation to avoid leaking gendisk on -ENOMEM. (Sashiko)
- Link to v1: https://lore.kernel.org/all/[email protected]/

v3:
- Use const fops with this_module::<M>() instead of heap allocation
(as suggested by Andreas).
- Integrate ModuleMetadata::THIS_MODULE from [1].
- Dismiss recover_data before fallible build steps after the cleanup guard. (Sashiko)
- Link to v2: https://lore.kernel.org/all/[email protected]/

[1] https://lore.kernel.org/r/[email protected]

---
 drivers/block/rnull/rnull.rs     |  2 +-
 rust/kernel/block/mq.rs          | 13 ++++++--
 rust/kernel/block/mq/gen_disk.rs | 56 +++++++++++++++++---------------
 rust/kernel/lib.rs               |  9 +++++
 rust/macros/module.rs            | 16 +++++++++
 5 files changed, 65 insertions(+), 31 deletions(-)
drivers/block/rnull/rnull.rs +1 -1
index 0ca8715febe8..912526be4ec2 100644
@@ -61,7 +61,7 @@ fn new(
             .logical_block_size(block_size)?
             .physical_block_size(block_size)?
             .rotational(rotational)
-            .build(fmt!("{}", name.to_str()?), tagset, queue_data)
+            .build::<NullBlkModule, Self>(fmt!("{}", name.to_str()?), tagset, queue_data)
     }
 }
 
rust/kernel/block/mq.rs +10 -3
index 1fd0d54dd549..faa9fcbac935 100644
@@ -8,8 +8,8 @@
 //! - Implement [`Operations`] for a type `T`.
 //! - Create a [`TagSet<T>`].
 //! - Create a [`GenDisk<T>`], via the [`GenDiskBuilder`].
-//! - Add the disk to the system by calling [`GenDiskBuilder::build`] passing in
-//!   the `TagSet` reference.
+//! - Add the disk to the system by calling [`GenDiskBuilder::build`], passing in
+//!   the module type, the disk name, the `TagSet`, and queue data.
 //!
 //! The types available in this module that have direct C counterparts are:
 //!
@@ -86,9 +86,16 @@
 //!
 //! let tagset: Arc<TagSet<MyBlkDevice>> =
 //!     Arc::pin_init(TagSet::new(1, 256, 1), flags::GFP_KERNEL)?;
+//! # struct MyModule;
+//! # impl kernel::ModuleMetadata for MyModule {
+//! #     const NAME: &'static kernel::str::CStr = c"myblk";
+//! #     // SAFETY: Doctest stub; no module is loaded.
+//! #     const THIS_MODULE: ThisModule =
+//! #         unsafe { ThisModule::from_ptr(core::ptr::null_mut()) };
+//! # }
 //! let mut disk = gen_disk::GenDiskBuilder::new()
 //!     .capacity_sectors(4096)
-//!     .build(fmt!("myblk"), tagset, ())?;
+//!     .build::<MyModule, MyBlkDevice>(fmt!("myblk"), tagset, ())?;
 //!
 //! # Ok::<(), kernel::error::Error>(())
 //! ```
rust/kernel/block/mq/gen_disk.rs +29 -27

82 lines not on this page · raw message

rust/kernel/lib.rs +9 -0
index 9512af7156df..9bbabaf84e20 100644
@@ -185,6 +185,15 @@ fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, error::Erro
 pub trait ModuleMetadata {
     /// The name of the module as specified in the `module!` macro.
     const NAME: &'static crate::str::CStr;
+
+    /// The module's `THIS_MODULE` pointer.
+    const THIS_MODULE: ThisModule;
+}
+
+/// Returns the [`ThisModule`] pointer for 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 +16 -0
index 06c18e207508..8df38718224b 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.
Signature · 1 line
2.55.0
maintainer
#4 lore raw

Hi Adarsh,

Quoted 9 lines · Adarsh Das

GenDiskBuilder left block_device_operations.owner NULL. Set owner from a const block_device_operations table using this_module::<M>() and update rnull to pass NullBlkModule.

Add ModuleMetadata::THIS_MODULE and this_module() so the owner pointer is available in const context. Rebased on Alvins fix-fops-owner series [1].

We merged LocalModule [1]. Please use this feature to set the owner.

I don't think you need to move the operations vtable.

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]

maintainer
#5 lore raw
Quoted 14 lines · Andreas Hindborg

Hi Adarsh,

Quoted 9 lines · Adarsh Das

GenDiskBuilder left block_device_operations.owner NULL. Set owner from a const block_device_operations table using this_module::<M>() and update rnull to pass NullBlkModule.

Add ModuleMetadata::THIS_MODULE and this_module() so the owner pointer is available in const context. Rebased on Alvins fix-fops-owner series [1].

Quoted 8 lines

We merged LocalModule [1]. Please use this feature to set the owner.

I don't think you need to move the operations vtable.

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]

Actually we are going to pick this one instead [1]. Seems like you have been trying to do the same thing.

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/r/[email protected]