rust: Reimplement ThisModule to fix ownership problems
Subsystems (22)
cover rust: Reimplement ThisModule to fix ownership problems
This is RFC and just first patch is ready. First I wanna discuss if this is right way to go. I also need to implement this so that build does not break and do better splitting. There is missing signed-off-by's and commit messages so no need to comment those kind of things. Feel free to cc more people if needed.
So currently we have problem that we are not always filling .owner field 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 usually just pass this trait forward if needed. Or they can use THIS_MODULE impl which is now completly private impl for each module and kernel create does not see this. So we can think if we wanna pass other module data which have through this. This could also be used to give local module storage without using static.
There is also some of github issues for ThisModule handling:
Quoted 1 line
MiscDevice missing module reference counting causes use-after-free crashes [1].
This will be tested and fixed in this series
Quoted 1 line
Ensure ThisModule invariants hold
Yeap. Now it would be really hard for kernel create to create this by accident. Binder is still using .as_ptr() but that is easily solvable and after that we can make .as_ptr() private so it will be nice that kernel create can just use .as_ptr() modules can just use.
Quoted 5 lines
Add
ThisModule::this_module()Add a new function
ThisModule::this_module()-> &'static ThisModule that is only available when MODULE is set. It should return a static reference tobindings::__this_module. [3]
I do not this is actually good idea. But here we take little bit different approx so basically this is done also.
Quoted 1 line
Suggested that ThisModule should have
name()parameter. [4]
And that was good idea. We can remove whole ModuleMetadata and usage is lot nicer. It is also possible that we could have example trait PciModule. which THIS_MODULE impl based on type but that is think for another time.
Quoted 1 line
Initialise the owner field in struct
file_operations. [5]
Yeap. After this is totally possible to do everywhere. This series will already address most of those.
[1]: https://github.com/Rust-for-Linux/linux/issues/1182
[2]: https://github.com/Rust-for-Linux/linux/issues/212
[3]: https://github.com/Rust-for-Linux/linux/issues/1176
[4]: https://github.com/Rust-for-Linux/linux/issues/720
[5]: https://github.com/Rust-for-Linux/linux/issues/720
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]>
---
Kari Argillander (6):
rust: Enable const_refs_to_static feature
rust: WIP: Introduce ThisModule trait and THIS_MODULE impl
rust: WIP: use ThisModule trait for initializing
rust: WIP: use ThisModule trait to fix some missing owners
rust: debugfs: WIP: Use owner for file_operations
rust: WIP: Replace ModuleMetadata with THIS_MODULE
drivers/android/binder/rust_binder_main.rs | 4 +- drivers/block/rnull/configfs.rs | 2 +- drivers/block/rnull/rnull.rs | 3 +- drivers/gpu/drm/nova/driver.rs | 1 + drivers/gpu/drm/tyr/driver.rs | 1 + drivers/gpu/nova-core/nova_core.rs | 2 +- lib/find_bit_benchmark_rust.rs | 2 +- rust/kernel/auxiliary.rs | 15 +++--- rust/kernel/block/mq/gen_disk.rs | 31 ++---------- rust/kernel/block/mq/operations.rs | 12 +++++ rust/kernel/configfs.rs | 19 ++++--- rust/kernel/debugfs.rs | 79 ++++++++++++++++-------------- rust/kernel/debugfs/file_ops.rs | 50 ++++++++++++++----- rust/kernel/driver.rs | 19 ++----- rust/kernel/drm/device.rs | 2 +- rust/kernel/drm/driver.rs | 3 ++ rust/kernel/drm/gem/mod.rs | 4 +- rust/kernel/firmware.rs | 2 +- rust/kernel/i2c.rs | 10 ++-- rust/kernel/lib.rs | 78 ++++++++++++++++++----------- rust/kernel/miscdevice.rs | 4 ++ rust/kernel/net/phy.rs | 16 +++--- rust/kernel/pci.rs | 11 ++--- rust/kernel/platform.rs | 11 ++--- rust/kernel/usb.rs | 11 ++--- rust/macros/module.rs | 43 +++++++++------- samples/rust/rust_configfs.rs | 2 +- samples/rust/rust_debugfs.rs | 6 +-- 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 +- 33 files changed, 245 insertions(+), 215 deletions(-)
---
base-commit: cc3aa43b44bdb43dfbac0fcb51c56594a11338a8
change-id: 20251230-this_module_fix-a390bff24897
Best regards,
Signature · 1 line
Kari Argillander <[email protected]>
RFC PATCH 1/6 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
@@ -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
RFC PATCH 2/6 rust: WIP: Introduce ThisModule trait and THIS_MODULE impl
In reply to Kari Argillander--- rust/kernel/lib.rs | 61 +++++++++++++++++++++++++++++++++++---------------- rust/macros/module.rs | 36 ++++++++++++++++++------------ 2 files changed, 64 insertions(+), 33 deletions(-)
rust/kernel/lib.rs +42 -19
@@ -205,31 +205,54 @@ pub trait ModuleMetadata {const NAME : &'staticcrate ::str::CStr ; } -/// 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 ); +pub mod this_module { +//! TODO +//! +//! # For driver cretors +//! +//! For each module we define own custom THIS_MODULE in +//! [`macros::module::module`]. Mechanism is equivalent to `THIS_MODULE` in +//! the [C API](srctree/include/linux/init.h). +//! +//! TODO +//! +//! # For abstraction creators +//! +//! TODO -// SAFETY: `THIS_MODULE` may be used from all threads within a module. -unsafe impl Sync for ThisModule {} +/// See [`this_module`] +pub trait ThisModule { +/// TODO Doc +const OWNER :ModuleWrapper ; + } -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) +/// See [`this_module`] +pub struct ModuleWrapper { + ptr: *mut bindings::module , } -/// 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 +impl ModuleWrapper { +/// Get the raw pointer to the underlying `struct module`. +/// +/// TODO: Should be only available for kernel create. +pub const fn as_ptr (&self) -> *mut bindings::module { + self.ptr + } + +/// Only meant to use in [`macros::module::module`]. +/// +/// # Safety +/// +/// - Only modules are allowed to create non null `ModuleWrapper`s. +/// - The pointer must point to a valid `struct module` provided by the +/// kernel. +#[doc(hidden)] +pub const unsafe fn from_ptr (ptr: *mut bindings::module ) ->Self { +ModuleWrapper { ptr } + } } } +pub use this_module::*;#[cfg(not(testlib))] #[panic_handler]
rust/macros/module.rs +22 -14
@@ -371,20 +371,28 @@ 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 >; - }} +/// THIS_MODULE for \"{name}\". See more at [`kernel::this_module`]. +#[allow(non_camel_case_types)] +pub struct THIS_MODULE ; + + impl ::kernel::prelude::ThisModule for THIS_MODULE {{ +#[cfg(not( MODULE ))] +const OWNER : ::kernel::this_module::ModuleWrapper =unsafe {{ + ::kernel::this_module::ModuleWrapper ::from_ptr (::core::ptr::null_mut ()) + }}; - ::kernel::ThisModule ::from_ptr (__this_module.get ()) - }}; -#[cfg(not( MODULE ))] -static THIS_MODULE : ::kernel::ThisModule =unsafe {{ - ::kernel::ThisModule ::from_ptr (::core::ptr::null_mut ()) - }}; +#[cfg( MODULE )] +// SAFETY: +// - `__this_module` is constructed by the kernel at module load time. +// - We use check that we are module so we can create non-null ModuleWrapper. +const OWNER : ::kernel::this_module::ModuleWrapper =unsafe {{ + extern \"C\" {{ +static __this_module: ::kernel::types::Opaque <::kernel::bindings::module >; + }} + + ::kernel::this_module::ModuleWrapper ::from_ptr (__this_module.get ()) + }}; + }}/// The `LocalModule` type is the type of the module created by `module!`, /// `module_pci_driver!`, `module_platform_driver!`, etc.
@@ -502,7 +510,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>();// 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`.
Signature · 1 line
2.43.0
RFC PATCH 3/6 rust: WIP: use ThisModule trait for initializing
In reply to Kari ArgillanderNow that ThisModule is trait we can use it for initializing. This way we can also use it in const context. This does matter in later on.
--- drivers/android/binder/rust_binder_main.rs | 2 +- drivers/block/rnull/configfs.rs | 2 +- drivers/block/rnull/rnull.rs | 2 +- rust/kernel/auxiliary.rs | 9 ++------- rust/kernel/configfs.rs | 19 +++++++++---------- rust/kernel/driver.rs | 17 +++++------------ rust/kernel/drm/gem/mod.rs | 4 ++-- rust/kernel/i2c.rs | 8 ++------ rust/kernel/lib.rs | 8 ++++---- rust/kernel/net/phy.rs | 16 ++++++++-------- rust/kernel/pci.rs | 9 ++------- rust/kernel/platform.rs | 9 ++------- rust/kernel/usb.rs | 9 ++------- samples/rust/rust_configfs.rs | 2 +- samples/rust/rust_driver_auxiliary.rs | 6 +++--- 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 +- 19 files changed, 49 insertions(+), 81 deletions(-)
drivers/android/binder/rust_binder_main.rs +1 -1
@@ -282,7 +282,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 <M :ThisModule >() ->Result <Self > {// SAFETY: The module initializer never runs twice, so we only call this once. unsafe {crate ::context::CONTEXTS .init () };
drivers/block/rnull/configfs.rs +1 -1
@@ -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,
drivers/block/rnull/rnull.rs +1 -1
@@ -36,7 +36,7 @@ struct NullBlkModule { }impl kernel::InPlaceModule for NullBlkModule { -fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +fn init <M :ThisModule >() ->impl PinInit <Self ,Error > {pr_info! ("Rust null_blk loaded\n" );try_pin_init! (Self {
rust/kernel/auxiliary.rs +2 -7
@@ -12,7 +12,6 @@ error::{from_result, to_result, Result}, prelude::*, types::Opaque, - ThisModule, };use core::{ marker::PhantomData ,
@@ -28,11 +27,7 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::auxiliary_driver ; -unsafe fn register ( - adrv: &Opaque <Self ::RegType >, - name: &'staticCStr , - module: &'staticThisModule , - ) ->Result { +unsafe fn register <M :ThisModule >(adrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result {// SAFETY: It's safe to set the fields of `struct auxiliary_driver` on initialization. unsafe { (*adrv.get ()).name = name.as_char_ptr ();
@@ -43,7 +38,7 @@ 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 (),M ::OWNER .as_ptr (), name.as_char_ptr ()) }) }
rust/kernel/configfs.rs +9 -10
@@ -744,17 +744,17 @@ macro_rules! impl_item_type { ($tpe:ty) => {impl <Data >ItemType <$tpe,Data > {#[doc(hidden)] -pub const fn new_with_child_ctor <const N :usize ,Child >( - owner: &'staticThisModule , +pub const fn new_with_child_ctor <const N :usize ,Child ,M >( attributes: &'staticAttributeList <N ,Data >, ) ->Self where Data :GroupOperations <Child =Child >,Child : 'static, +M :ThisModule , {Self { item_type:Opaque ::new (bindings::config_item_type { - ct_owner: owner.as_ptr (), + ct_owner:M ::OWNER .as_ptr (), ct_group_ops:GroupOperationsVTable ::<Data ,Child >::vtable_ptr ().cast_mut (), ct_item_ops:ItemOperationsVTable ::<$tpe,Data >::vtable_ptr ().cast_mut (), ct_attrs: core::ptr::from_ref (attributes).cast_mut ().cast (),
@@ -765,13 +765,12 @@ pub const fn new_with_child_ctor<const N: usize, Child>( }#[doc(hidden)] -pub const fn new <const N :usize >( - owner: &'staticThisModule , +pub const fn new <const N :usize ,M :ThisModule >( attributes: &'staticAttributeList <N ,Data >, ) ->Self {Self { item_type:Opaque ::new (bindings::config_item_type { - ct_owner: owner.as_ptr (), + ct_owner:M ::OWNER .as_ptr (), ct_group_ops: core::ptr::null_mut (), ct_item_ops:ItemOperationsVTable ::<$tpe,Data >::vtable_ptr ().cast_mut (), ct_attrs: core::ptr::from_ref (attributes).cast_mut ().cast (),
@@ -1019,8 +1018,8 @@ macro_rules! configfs_attrs { const [<$no_child:upper>]: bool = true; static [< $data:upper _TPE >] : $crate::configfs::ItemType<$container, $data> = - $crate::configfs::ItemType::<$container, $data>::new::<N>( - &THIS_MODULE, &[<$ data:upper _ATTRS >] + $crate::configfs::ItemType::<$container, $data>::new::<N, crate::THIS_MODULE>( + &[<$ data:upper _ATTRS >] ); )?
@@ -1028,8 +1027,8 @@ macro_rules! configfs_attrs { static [< $data:upper _TPE >]: $crate::configfs::ItemType<$container, $data> = $crate::configfs::ItemType ::<$container, $data>:: -new_with_child_ctor ::<N , $child>( - &THIS_MODULE, &[<$ data:upper _ATTRS >] +new_with_child_ctor ::<N , $child,crate ::THIS_MODULE >( + &[<$ data:upper _ATTRS >] ); )?
rust/kernel/driver.rs +5 -12
@@ -118,11 +118,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: &'staticCStr , - module: &'staticThisModule , - ) ->Result ; +unsafe fn register <M :ThisModule >(reg: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result ;/// Unregisters a driver previously registered with [`RegistrationOps::register`]. ///
@@ -155,7 +151,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<M: ThisModule>(name: &'static CStr) -> 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.
@@ -166,7 +162,7 @@ pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Sellet drv =unsafe { &*(ptras *const Opaque <T ::RegType >) };// SAFETY: `drv` is guaranteed to be pinned until `T::unregister`. -unsafe {T ::register (drv, name, module) } +unsafe {T ::register ::<M >(drv, name) } }), }) }
@@ -197,13 +193,10 @@ struct DriverModule { }impl $crate::InPlaceModule for DriverModule { -fn init ( - module: &'static $crate::ThisModule - ) ->impl ::pin_init::PinInit <Self , $crate::error::Error > { +fn init <M : ::kernel::ThisModule >() ->impl ::pin_init::PinInit <Self , $crate::error::Error > { $crate::try_pin_init!(Self { - _driver <- $crate ::driver::Registration ::new ( + _driver <- $crate ::driver::Registration ::new ::<M >( <Self as $crate ::ModuleMetadata >::NAME , - module, ), }) }
rust/kernel/drm/gem/mod.rs +2 -2
@@ -292,10 +292,10 @@ impl<T: DriverObject> AllocImpl for Object<T> { }; } -pub (super )const fn create_fops () -> bindings::file_operations { +pub (super )const fn create_fops <M :ThisModule >() -> bindings::file_operations {let mut fops: bindings::file_operations = pin_init::zeroed (); - fops.owner = core::ptr::null_mut (); + fops.owner =M ::OWNER .as_ptr (); fops.open =Some (bindings::drm_open); fops.release =Some (bindings::drm_release); fops.unlocked_ioctl =Some (bindings::drm_ioctl);
rust/kernel/i2c.rs +2 -6
@@ -97,11 +97,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: &'staticCStr , - module: &'staticThisModule , - ) ->Result { +unsafe fn register <M :ThisModule >(idrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->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"
@@ -134,7 +130,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 (M ::OWNER .as_ptr (), idrv.get ()) }) }unsafe fn unregister (idrv: &Opaque <Self ::RegType >) {
rust/kernel/lib.rs +4 -4
@@ -173,7 +173,7 @@ pub trait Module: Sized + Sync + Send {/// should do. /// /// Equivalent to the `module_init` macro in the C API. -fn init (module: &'staticThisModule ) -> error::Result <Self >; +fn init <M :ThisModule >() -> error::Result <Self >; }/// A module that is pinned and initialised in-place.
@@ -181,13 +181,13 @@ pub trait InPlaceModule: Sync + Send {/// Creates an initialiser for the module. /// /// It is called when the module is loaded. -fn init (module: &'staticThisModule ) ->impl pin_init::PinInit <Self , error::Error >; +fn init <M :ThisModule >() ->impl pin_init::PinInit <Self , error::Error >; }impl <T :Module >InPlaceModule for T { -fn init (module: &'staticThisModule ) ->impl pin_init::PinInit <Self , error::Error > { +fn init <M :ThisModule >() ->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 ::<M >()?;// SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`. unsafe { slot.write (m) };
rust/kernel/net/phy.rs +8 -8
@@ -648,10 +648,7 @@ unsafe impl Send for Registration {}impl Registration {/// Registers a PHY driver. -pub fn register ( - module: &'staticcrate ::ThisModule , - drivers:Pin <&'staticmut [DriverVTable ]>, - ) ->Result <Self > { +pub fn register <M :ThisModule >(drivers:Pin <&'staticmut [DriverVTable ]>) ->Result <Self > {if drivers.is_empty () {return Err (code::EINVAL ); }
@@ -659,7 +656,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 ()?, +M ::OWNER .as_ptr (), + ) })?;// INVARIANT: The `drivers` slice is successfully registered to the kernel via `phy_drivers_register`. Ok (Registration { drivers })
@@ -891,12 +892,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 <M : $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 ::<M >( ::core::pin::Pin ::static_mut (drivers), )?;Ok (Module { _reg: reg })
rust/kernel/pci.rs +2 -7
@@ -20,7 +20,6 @@ prelude::*, str::CStr, types::Opaque, - ThisModule, // };use core::{ marker::PhantomData ,
@@ -55,11 +54,7 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::pci_driver ; -unsafe fn register ( - pdrv: &Opaque <Self ::RegType >, - name: &'staticCStr , - module: &'staticThisModule , - ) ->Result { +unsafe fn register <M :ThisModule >(pdrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result {// SAFETY: It's safe to set the fields of `struct pci_driver` on initialization. unsafe { (*pdrv.get ()).name = name.as_char_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 (),M ::OWNER .as_ptr (), name.as_char_ptr ()) }) }
rust/kernel/platform.rs +2 -7
@@ -14,7 +14,6 @@ of, prelude::*, types::Opaque, - ThisModule, };use core::{
@@ -31,11 +30,7 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::platform_driver ; -unsafe fn register ( - pdrv: &Opaque <Self ::RegType >, - name: &'staticCStr , - module: &'staticThisModule , - ) ->Result { +unsafe fn register <M :ThisModule >(pdrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result {let of_table =match T ::OF_ID_TABLE {Some (table) => table.as_ptr (), None => core::ptr::null(),
@@ -56,7 +51,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 (),M ::OWNER .as_ptr ()) }) }unsafe fn unregister (pdrv: &Opaque <Self ::RegType >) {
rust/kernel/usb.rs +2 -7
@@ -13,7 +13,6 @@ prelude::*, str::CStr, types::{AlwaysRefCounted, Opaque}, - ThisModule, };use core::{ marker::PhantomData ,
@@ -32,11 +31,7 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::usb_driver ; -unsafe fn register ( - udrv: &Opaque <Self ::RegType >, - name: &'staticCStr , - module: &'staticThisModule , - ) ->Result { +unsafe fn register <M :ThisModule >(udrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result {// SAFETY: It's safe to set the fields of `struct usb_driver` on initialization. unsafe { (*udrv.get ()).name = name.as_char_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 (),M ::OWNER .as_ptr (), name.as_char_ptr ()) }) }
samples/rust/rust_configfs.rs +1 -1
@@ -42,7 +42,7 @@ fn new() -> impl PinInit<Self, Error> { }impl kernel::InPlaceModule for RustConfigfs { -fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +fn init <M :ThisModule >() ->impl PinInit <Self ,Error > {pr_info! ("Rust configfs sample (init)\n" );// Define a subsystem with the data type `Configuration`, two
samples/rust/rust_driver_auxiliary.rs +3 -3
@@ -111,10 +111,10 @@ struct SampleModule { }impl InPlaceModule for SampleModule { -fn init (module: &'static kernel::ThisModule ) ->impl PinInit <Self ,Error > { +fn init <M :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 ::<M >(MODULE_NAME ), + _aux_driver <- driver::Registration ::new ::<M >(MODULE_NAME ), }) } }
samples/rust/rust_driver_faux.rs +1 -1
@@ -17,7 +17,7 @@ struct SampleModule { }impl Module for SampleModule { -fn init (_module: &'staticThisModule ) ->Result <Self > { +fn init <M : kernel::ThisModule >() ->Result <Self > {pr_info! ("Initialising Rust Faux Device Sample\n" );let reg = faux::Registration ::new (c_str! ("rust-faux-sample-device" ),None )?;
samples/rust/rust_minimal.rs +1 -1
@@ -23,7 +23,7 @@ struct RustMinimal { }impl kernel::Module for RustMinimal { -fn init (_module: &'staticThisModule ) ->Result <Self > { +fn init <M : kernel::ThisModule >() ->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
@@ -129,7 +129,7 @@ struct RustMiscDeviceModule { }impl kernel::InPlaceModule for RustMiscDeviceModule { -fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +fn init <M :ThisModule >() ->impl PinInit <Self ,Error > {pr_info! ("Initialising Rust Misc Device Sample\n" ); let options = MiscDeviceOptions {
samples/rust/rust_print_main.rs +1 -1
@@ -59,7 +59,7 @@ fn arc_dyn_print(arc: &Arc<dyn Display>) { }impl kernel::Module for RustPrint { -fn init (_module: &'staticThisModule ) ->Result <Self > { +fn init <M : kernel::ThisModule >() ->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
RFC PATCH 4/6 rust: WIP: use ThisModule trait to fix some missing owners
In reply to Kari ArgillanderSome places do not define owner and we have null pointer dereference bugs which we can fix with this. I have tested miscdevice that it actually works.
--- drivers/android/binder/rust_binder_main.rs | 2 +- drivers/block/rnull/rnull.rs | 1 + drivers/gpu/drm/nova/driver.rs | 1 + drivers/gpu/drm/tyr/driver.rs | 1 + lib/find_bit_benchmark_rust.rs | 2 +- rust/kernel/block/mq/gen_disk.rs | 31 ++++-------------------------- rust/kernel/block/mq/operations.rs | 12 ++++++++++++ rust/kernel/drm/device.rs | 2 +- rust/kernel/drm/driver.rs | 3 +++ rust/kernel/miscdevice.rs | 4 ++++ samples/rust/rust_misc_device.rs | 1 + 11 files changed, 30 insertions(+), 30 deletions(-)
drivers/android/binder/rust_binder_main.rs +1 -1
@@ -311,7 +311,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), compat_ioctl:Some (bindings::compat_ptr_ioctl),
drivers/block/rnull/rnull.rs +1 -0
@@ -75,6 +75,7 @@ struct QueueData {#[vtable] impl Operations for NullBlkDevice {type QueueData =KBox <QueueData >; +type ThisModule =THIS_MODULE ;#[inline(always)] fn queue_rq (queue_data: &QueueData , rq:ARef <mq::Request <Self >>, _is_last:bool ) ->Result {
drivers/gpu/drm/nova/driver.rs +1 -0
@@ -57,6 +57,7 @@ fn probe(adev: &auxiliary::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<S#[vtable] impl drm::Driver for NovaDriver { +type ThisModule =crate ::THIS_MODULE ;type Data =NovaData ;type File =File ;type Object = gem::Object <NovaObject >;
drivers/gpu/drm/tyr/driver.rs +1 -0
@@ -180,6 +180,7 @@ fn drop(self: Pin<&mut Self>) {#[vtable] impl drm::Driver for TyrDriver { +type ThisModule =crate ::THIS_MODULE ;type Data =TyrData ;type File =File ;type Object = drm::gem::Object <TyrObject >;
lib/find_bit_benchmark_rust.rs +1 -1
@@ -88,7 +88,7 @@ fn find_bit_test() { }impl kernel::Module for Benchmark { -fn init (_module: &'staticThisModule ) ->Result <Self > { +fn init <M :ThisModule >() ->Result <Self > {find_bit_test ();// Return error so test module can be inserted again without rmmod. Err (code::EINVAL )
rust/kernel/block/mq/gen_disk.rs +4 -27
@@ -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,9 @@ 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 +12 -0
@@ -31,6 +31,8 @@ pub trait Operations: Sized {/// Data associated with the `struct request_queue` that is allocated for /// the `GenDisk` associated with this `Operations` implementation. type QueueData :ForeignOwnable ; +/// TODO Doc +type ThisModule :ThisModule ;/// Called by the kernel to queue a request with the driver. If `is_last` is /// `false`, the driver is allowed to defer committing the request.
@@ -283,4 +285,14 @@ impl<T: Operations> OperationsVTable<T> {pub (crate )const fn build () -> &'static bindings::blk_mq_ops { &Self ::VTABLE } + +const BLOCK_OPS : bindings::block_device_operations = bindings::block_device_operations { + owner:T ::ThisModule ::OWNER .as_ptr (), + ..pin_init::zeroed () + }; + +pub (crate )const fn build_block_device_operations () -> &'static bindings::block_device_operations + { + &Self ::BLOCK_OPS + } }
rust/kernel/drm/device.rs +1 -1
@@ -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 +3 -0
@@ -99,6 +99,9 @@ pub trait AllocImpl: super::private::Sealed + drm::gem::IntoGEMObject {/// drm_driver` to be registered in the DRM subsystem. #[vtable] pub trait Driver { +/// TODO Doc +type ThisModule :ThisModule ; +/// Context data associated with the DRM driver type Data :Sync +Send ;
rust/kernel/miscdevice.rs +4 -0
@@ -116,6 +116,9 @@ pub trait MiscDevice: Sized {/// What kind of pointer should `Self` be wrapped in. type Ptr :ForeignOwnable +Send +Sync ; +/// TODO Docs +type ThisModule :ThisModule ; +/// Called when the misc device is opened. /// /// The returned pointer will be stored as the private data for the file.
@@ -389,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
@@ -157,6 +157,7 @@ struct RustMiscDevice {#[vtable] impl MiscDevice for RustMiscDevice {type Ptr =Pin <KBox <Self >>; +type ThisModule =THIS_MODULE ;fn open (_file: &File , misc: &MiscDeviceRegistration <Self >) ->Result <Pin <KBox <Self >>> {let dev =ARef ::from (misc.device ());
Signature · 1 line
2.43.0
RFC PATCH 5/6 rust: debugfs: WIP: Use owner for file_operations
In reply to Kari Argillander--- rust/kernel/debugfs.rs | 79 ++++++++++++++++++++++------------------- rust/kernel/debugfs/file_ops.rs | 50 +++++++++++++++++++------- samples/rust/rust_debugfs.rs | 6 ++-- 3 files changed, 83 insertions(+), 52 deletions(-)
rust/kernel/debugfs.rs +42 -37
@@ -6,7 +6,8 @@//! C header: [`include/linux/debugfs.h`](srctree/include/linux/debugfs.h) // When DebugFS is disabled, many parameters are dead. Linting for this isn't helpful. -#![cfg_attr(not( CONFIG_DEBUG_FS ), allow(unused_variables))] +// #![cfg_attr(not(CONFIG_DEBUG_FS), allow(unused_variables))] +#![allow(unused_variables)] use crate ::fmt;use crate ::prelude::*;
@@ -46,27 +47,31 @@// able to refer to us. In this case, we need to silently fail. All future child directories/files // will silently fail as well. #[derive( Clone )] -pub struct Dir (#[cfg( CONFIG_DEBUG_FS )] Option <Arc <Entry <'static>>>); +pub struct Dir <M :ThisModule >( +#[cfg( CONFIG_DEBUG_FS )] Option <Arc <Entry <'static>>>, +PhantomData <M >, +); -impl Dir { +impl <M :ThisModule >Dir <M > {/// Create a new directory in DebugFS. If `parent` is [`None`], it will be created at the root. -fn create (name: &CStr , parent:Option <&Dir >) ->Self { +fn create (name: &CStr , parent:Option <&Self >) ->Self {#[cfg( CONFIG_DEBUG_FS )] {let parent_entry =match parent {// If the parent couldn't be allocated, just early-return -Some (Dir (None )) =>return Self (None ), -Some (Dir (Some (entry))) =>Some (entry.clone ()), +Some (Self (None , _)) =>return Self (None ,PhantomData ), +Some (Self (Some (entry), _)) =>Some (entry.clone ()),None =>None , };Self (// If Arc creation fails, the `Entry` will be dropped, so the directory will be // cleaned up. Arc ::new (Entry ::dynamic_dir (name, parent_entry),GFP_KERNEL ).ok (), +PhantomData , ) }#[cfg(not( CONFIG_DEBUG_FS ))] -Self () +Self (PhantomData ) }/// Creates a DebugFS file which will own the data produced by the initializer provided in
@@ -107,7 +112,7 @@ fn create_file<'a, T, E: 'a>(/// let debugfs = Dir::new(c_str!("parent")); /// ``` pub fn new (name: &CStr ) ->Self { -Dir ::create (name,None ) +Self ::create (name,None ) }/// Creates a subdirectory within this directory.
@@ -121,7 +126,7 @@ pub fn new(name: &CStr) -> Self {/// let child = parent.subdir(c_str!("child")); /// ``` pub fn subdir (&self, name: &CStr ) ->Self { -Dir ::create (name,Some (self)) +Self ::create (name,Some (self)) }/// Creates a read-only file in this directory.
@@ -149,7 +154,7 @@ pub fn read_only_file<'a, T, E: 'a>( where T: Writer + Send + Sync + 'static, { -let file_ops = &<T as ReadFile <_ >>::FILE_OPS ; +let file_ops = &<T as ReadFile <M ,_ >>::FILE_OPS ; self.create_file (name, data, file_ops) }
@@ -176,7 +181,7 @@ pub fn read_binary_file<'a, T, E: 'a>( where T: BinaryWriter + Send + Sync + 'static, { - self.create_file (name, data, &T ::FILE_OPS ) + self.create_file (name, data, &<T as BinaryReadFile <M ,_ >>::FILE_OPS ) }/// Creates a read-only file in this directory, with contents from a callback.
@@ -215,7 +220,7 @@ pub fn read_callback_file<'a, T, E: 'a, F>( T: Send + Sync + 'static, F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync, { -let file_ops = <FormatAdapter <T ,F >>::FILE_OPS .adapt (); +let file_ops = <FormatAdapter <T ,F >as ReadFile <M ,FormatAdapter <T ,F >>>::FILE_OPS .adapt (); self.create_file (name, data, file_ops) }
@@ -231,7 +236,7 @@ pub fn read_write_file<'a, T, E: 'a>( where T: Writer + Reader + Send + Sync + 'static, { -let file_ops = &<T as ReadWriteFile <_ >>::FILE_OPS ; +let file_ops = &<T as ReadWriteFile <M ,_ >>::FILE_OPS ; self.create_file (name, data, file_ops) }
@@ -247,7 +252,7 @@ pub fn read_write_binary_file<'a, T, E: 'a>( where T: BinaryWriter + BinaryReader + Send + Sync + 'static, { -let file_ops = &<T as BinaryReadWriteFile <_ >>::FILE_OPS ; +let file_ops = &<T as BinaryReadWriteFile <M ,_ >>::FILE_OPS ; self.create_file (name, data, file_ops) }
@@ -270,7 +275,7 @@ pub fn read_write_callback_file<'a, T, E: 'a, F, W>( W: Fn(&T, &mut UserSliceReader) -> Result + Send + Sync, {let file_ops = - <WritableAdapter <FormatAdapter <T ,F >,W >as file_ops::ReadWriteFile <_ >>::FILE_OPS + <WritableAdapter <FormatAdapter <T ,F >,W >as file_ops::ReadWriteFile <M ,_ >>::FILE_OPS .adapt () .adapt (); self.create_file (name, data, file_ops)
@@ -290,7 +295,7 @@ pub fn write_only_file<'a, T, E: 'a>( where T: Reader + Send + Sync + 'static, { - self.create_file (name, data, &T ::FILE_OPS ) + self.create_file (name, data, &<T as WriteFile <M ,_ >>::FILE_OPS ) }/// Creates a write-only binary file in this directory.
@@ -307,7 +312,7 @@ pub fn write_binary_file<'a, T, E: 'a>( where T: BinaryReader + Send + Sync + 'static, { - self.create_file (name, data, &T ::FILE_OPS ) + self.create_file (name, data, &<T as BinaryWriteFile <M ,_ >>::FILE_OPS ) }/// Creates a write-only file in this directory, with write logic from a callback.
@@ -324,7 +329,7 @@ pub fn write_callback_file<'a, T, E: 'a, W>( T: Send + Sync + 'static, W: Fn(&T, &mut UserSliceReader) -> Result + Send + Sync, { -let file_ops = <WritableAdapter <NoWriter <T >,W >as WriteFile <_ >>::FILE_OPS +let file_ops = <WritableAdapter <NoWriter <T >,W >as WriteFile <M ,_ >>::FILE_OPS .adapt () .adapt (); self.create_file (name, data, file_ops)
@@ -527,7 +532,7 @@ fn create_file<T: Sync>(&self, name: &CStr, data: &'data T, vtable: &'static Fil/// file is removed when the [`Scope`] that this directory belongs /// to is dropped. pub fn read_only_file <T :Writer +Send +Sync + 'static>(&self, name: &CStr , data: &'dataT ) { - self.create_file (name, data, &T ::FILE_OPS ) +// self.create_file(name, data, &<T as ReadFile<M, T>>::FILE_OPS) }/// Creates a read-only binary file in this directory.
@@ -541,7 +546,7 @@ pub fn read_binary_file<T: BinaryWriter + Send + Sync + 'static>( name: &CStr, data: &'data T, ) { - self.create_file (name, data, &T ::FILE_OPS ) + // self.create_file(name, data, &<T as ReadFile<M, T>>::FILE_OPS) } /// Creates a read-only file in this directory, with contents from a callback.
@@ -560,8 +565,8 @@ pub fn read_callback_file<T, F>(&self, name: &CStr, data: &'data T, _f: &'static T: Send + Sync + 'static, F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync, { -let vtable = <FormatAdapter <T ,F >as ReadFile <_ >>::FILE_OPS .adapt (); - self.create_file (name, data, vtable) +// let vtable = <FormatAdapter<T, F> as ReadFile<M, _>>::FILE_OPS.adapt(); +// self.create_file(name, data, vtable) }/// Creates a read-write file in this directory.
@@ -577,8 +582,8 @@ pub fn read_write_file<T: Writer + Reader + Send + Sync + 'static>( name: &CStr, data: &'data T, ) { -let vtable = &<T as ReadWriteFile <_ >>::FILE_OPS ; - self.create_file (name, data, vtable) + // let vtable = &<T as ReadWriteFile<_>>::FILE_OPS; + // self.create_file(name, data, vtable) }/// Creates a read-write binary file in this directory.
@@ -593,8 +598,8 @@ pub fn read_write_binary_file<T: BinaryWriter + BinaryReader + Send + Sync + 'st name: &CStr, data: &'data T, ) { -let vtable = &<T as BinaryReadWriteFile <_ >>::FILE_OPS ; - self.create_file (name, data, vtable) + // let vtable = &<T as BinaryReadWriteFile<_>>::FILE_OPS; + // self.create_file(name, data, vtable) }/// Creates a read-write file in this directory, with logic from callbacks.
@@ -618,10 +623,10 @@ pub fn read_write_callback_file<T, F, W>( F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result + Send + Sync, W: Fn(&T, &mut UserSliceReader) -> Result + Send + Sync, { -let vtable = <WritableAdapter <FormatAdapter <T ,F >,W >as ReadWriteFile <_ >>::FILE_OPS - .adapt () - .adapt (); - self.create_file (name, data, vtable) +// let vtable = <WritableAdapter<FormatAdapter<T, F>, W> as ReadWriteFile<_>>::FILE_OPS +// .adapt() +// .adapt(); +// self.create_file(name, data, vtable) }/// Creates a write-only file in this directory.
@@ -632,8 +637,8 @@ pub fn read_write_callback_file<T, F, W>(/// file is removed when the [`Scope`] that this directory belongs /// to is dropped. pub fn write_only_file <T :Reader +Send +Sync + 'static>(&self, name: &CStr , data: &'dataT ) { -let vtable = &<T as WriteFile <_ >>::FILE_OPS ; - self.create_file (name, data, vtable) +// let vtable = &<T as WriteFile<_>>::FILE_OPS; +// self.create_file(name, data, vtable) }/// Creates a write-only binary file in this directory.
@@ -647,7 +652,7 @@ pub fn write_binary_file<T: BinaryReader + Send + Sync + 'static>( name: &CStr, data: &'data T, ) { - self.create_file (name, data, &T ::FILE_OPS ) + // self.create_file(name, data, &<T as ReadFile<M, T>>::FILE_OPS) } /// Creates a write-only file in this directory, with write logic from a callback.
@@ -665,10 +670,10 @@ pub fn write_only_callback_file<T, W>(&self, name: &CStr, data: &'data T, _w: &' T: Send + Sync + 'static, W: Fn(&T, &mut UserSliceReader) -> Result + Send + Sync, { -let vtable = &<WritableAdapter <NoWriter <T >,W >as WriteFile <_ >>::FILE_OPS - .adapt () - .adapt (); - self.create_file (name, data, vtable) +// let vtable = &<WritableAdapter<NoWriter<T>, W> as WriteFile<_>>::FILE_OPS +// .adapt() +// .adapt(); +// self.create_file(name, data, vtable) }fn empty () ->Self {
rust/kernel/debugfs/file_ops.rs +38 -12
116 lines not on this page · raw message
samples/rust/rust_debugfs.rs +3 -3
@@ -54,7 +54,7 @@ struct RustDebugFs { pdev: ARef<platform::Device>, // As we only hold these for drop effect (to remove the directory/files) we have a leading // underscore to indicate to the compiler that we don't expect to use this field directly. - _debugfs: Dir, + _debugfs: Dir<THIS_MODULE>,#[pin] _compatible: File<CString>,#[pin]
@@ -124,11 +124,11 @@ fn probe( }impl RustDebugFs { -fn build_counter (dir: &Dir ) ->impl PinInit <File <Atomic <usize >>> + '_ { +fn build_counter <M :ThisModule >(dir: &Dir <M >) ->impl PinInit <File <Atomic <usize >>> + '_ { dir.read_write_file (c_str! ("counter" ),Atomic ::<usize >::new (0 )) } -fn build_inner (dir: &Dir ) ->impl PinInit <File <Mutex <Inner >>> + '_ { +fn build_inner <M :ThisModule >(dir: &Dir <M >) ->impl PinInit <File <Mutex <Inner >>> + '_ { dir.read_write_file (c_str! ("pair" ),new_mutex! (Inner { x:3 , y:10 })) }
Signature · 1 line
2.43.0
RFC PATCH 6/6 rust: WIP: Replace ModuleMetadata with THIS_MODULE
In reply to Kari ArgillanderModuleMetadata seems redudant after we have prober THIS_MODULE.
--- drivers/gpu/nova-core/nova_core.rs | 2 +- rust/kernel/auxiliary.rs | 10 +++++++--- rust/kernel/driver.rs | 10 ++++------ rust/kernel/firmware.rs | 2 +- rust/kernel/i2c.rs | 4 ++-- rust/kernel/lib.rs | 8 ++------ rust/kernel/pci.rs | 6 +++--- rust/kernel/platform.rs | 4 ++-- rust/kernel/usb.rs | 6 +++--- rust/macros/module.rs | 13 +++++++------ samples/rust/rust_driver_auxiliary.rs | 6 +++--- 11 files changed, 35 insertions(+), 36 deletions(-)
drivers/gpu/nova-core/nova_core.rs +1 -1
@@ -19,7 +19,7 @@mod util;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 ,
rust/kernel/auxiliary.rs +7 -3
@@ -27,10 +27,10 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::auxiliary_driver ; -unsafe fn register <M :ThisModule >(adrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result { +unsafe fn register <M :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 =M ::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 ();
@@ -38,7 +38,11 @@ unsafe fn register<M: ThisModule>(adrv: &Opaque<Self::RegType>, name: &'static C// SAFETY: `adrv` is guaranteed to be a valid `RegType`. to_result (unsafe { - bindings::__auxiliary_driver_register (adrv.get (),M ::OWNER .as_ptr (), name.as_char_ptr ()) + bindings::__auxiliary_driver_register ( + adrv.get (), +M ::OWNER .as_ptr (), +M ::NAME .as_char_ptr (), + ) }) }
rust/kernel/driver.rs +4 -6
@@ -118,7 +118,7 @@ pub unsafe trait RegistrationOps {/// /// On success, `reg` must remain pinned and valid until the matching call to /// [`RegistrationOps::unregister`]. -unsafe fn register <M :ThisModule >(reg: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result ; +unsafe fn register <M :ThisModule >(reg: &Opaque <Self ::RegType >) ->Result ;/// Unregisters a driver previously registered with [`RegistrationOps::register`]. ///
@@ -151,7 +151,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<M: ThisModule>(name: &'static CStr) -> impl PinInit<Self, Error> { + pub fn new<M: 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.
@@ -162,7 +162,7 @@ pub fn new<M: ThisModule>(name: &'static CStr) -> impl PinInit<Self, Error> {let drv =unsafe { &*(ptras *const Opaque <T ::RegType >) };// SAFETY: `drv` is guaranteed to be pinned until `T::unregister`. -unsafe {T ::register ::<M >(drv, name) } +unsafe {T ::register ::<M >(drv) } }), }) }
@@ -195,9 +195,7 @@ struct DriverModule {impl $crate::InPlaceModule for DriverModule {fn init <M : ::kernel::ThisModule >() ->impl ::pin_init::PinInit <Self , $crate::error::Error > { $crate::try_pin_init!(Self { - _driver <- $crate ::driver::Registration ::new ::<M >( - <Self as $crate ::ModuleMetadata >::NAME , - ), + _driver <- $crate ::driver::Registration ::new ::<M >(), }) } }
rust/kernel/firmware.rs +1 -1
@@ -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 +THIS_MODULE ::name () };#[link_section = ".modinfo" ]
rust/kernel/i2c.rs +2 -2
@@ -97,7 +97,7 @@ macro_rules! i2c_device_table {unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::i2c_driver ; -unsafe fn register <M :ThisModule >(idrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result { +unsafe fn register <M :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"
@@ -120,7 +120,7 @@ unsafe fn register<M: ThisModule>(idrv: &Opaque<Self::RegType>, name: &'static C// 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 =M ::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);
rust/kernel/lib.rs +2 -6
@@ -199,12 +199,6 @@ fn init<M: ThisModule>() -> 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 : &'staticcrate ::str::CStr ; -} -pub mod this_module {//! TODO //!
@@ -224,6 +218,8 @@ pub mod this_module {pub trait ThisModule {/// TODO Doc const OWNER :ModuleWrapper ; +/// TODO Doc +const NAME : &'static kernel::str::CStr ; }/// See [`this_module`]
rust/kernel/pci.rs +3 -3
@@ -54,10 +54,10 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::pci_driver ; -unsafe fn register <M :ThisModule >(pdrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result { +unsafe fn register <M :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 =M ::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 ();
@@ -65,7 +65,7 @@ unsafe fn register<M: ThisModule>(pdrv: &Opaque<Self::RegType>, name: &'static C// SAFETY: `pdrv` is guaranteed to be a valid `RegType`. to_result (unsafe { - bindings::__pci_register_driver (pdrv.get (),M ::OWNER .as_ptr (), name.as_char_ptr ()) + bindings::__pci_register_driver (pdrv.get (),M ::OWNER .as_ptr (),M ::NAME .as_char_ptr ()) }) }
rust/kernel/platform.rs +2 -2
@@ -30,7 +30,7 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::platform_driver ; -unsafe fn register <M :ThisModule >(pdrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result { +unsafe fn register <M :ThisModule >(pdrv: &Opaque <Self ::RegType >) ->Result {let of_table =match T ::OF_ID_TABLE {Some (table) => table.as_ptr (), None => core::ptr::null(),
@@ -43,7 +43,7 @@ unsafe fn register<M: ThisModule>(pdrv: &Opaque<Self::RegType>, name: &'static C// 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 =M ::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;
rust/kernel/usb.rs +3 -3
@@ -31,10 +31,10 @@unsafe impl <T :Driver + 'static> driver::RegistrationOps for Adapter <T > {type RegType = bindings::usb_driver ; -unsafe fn register <M :ThisModule >(udrv: &Opaque <Self ::RegType >, name: &'staticCStr ) ->Result { +unsafe fn register <M :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 =M ::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 ();
@@ -42,7 +42,7 @@ unsafe fn register<M: ThisModule>(udrv: &Opaque<Self::RegType>, name: &'static C// SAFETY: `udrv` is guaranteed to be a valid `RegType`. to_result (unsafe { - bindings::usb_register_driver (udrv.get (),M ::OWNER .as_ptr (), name.as_char_ptr ()) + bindings::usb_register_driver (udrv.get (),M ::OWNER .as_ptr (),M ::NAME .as_char_ptr ()) }) }
rust/macros/module.rs +7 -6
@@ -375,6 +375,13 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {#[allow(non_camel_case_types)] pub struct THIS_MODULE ; + impl THIS_MODULE {{ +/// Returns the name of this module. +pub const fn name () -> &'static ::kernel::str::CStr {{ + c\"{name}\" + }} + }} + impl ::kernel::prelude::ThisModule for THIS_MODULE {{#[cfg(not( MODULE ))] const OWNER: ::kernel::this_module::ModuleWrapper = unsafe {{
@@ -392,13 +399,7 @@ impl ::kernel::prelude::ThisModule for THIS_MODULE {{ ::kernel::this_module::ModuleWrapper ::from_ptr (__this_module.get ()) }}; - }} - -/// 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}\"; }}
samples/rust/rust_driver_auxiliary.rs +3 -3
@@ -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_str! ("auxiliary" );struct AuxiliaryDriver ;
@@ -113,8 +113,8 @@ struct SampleModule {impl InPlaceModule for SampleModule {fn init <M :ThisModule >() ->impl PinInit <Self ,Error > {try_pin_init! (Self { - _pci_driver <- driver::Registration ::new ::<M >(MODULE_NAME ), - _aux_driver <- driver::Registration ::new ::<M >(MODULE_NAME ), + _pci_driver <- driver::Registration ::new ::<M >(), + _aux_driver <- driver::Registration ::new ::<M >(), }) } }
Signature · 1 line
2.43.0
kernel test robot
build botRe: [PATCH RFC 3/6] rust: WIP: use ThisModule trait for initializing
In reply to Kari Argillanderkernel test robot noticed the following build errors:
Hi Kari,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on cc3aa43b44bdb43dfbac0fcb51c56594a11338a8]
url: https://github.com/intel-lab-lkp/linux/commits/Kari-Argillander/rust-Enable-const_refs_to_static-feature/20260101-172411 base: cc3aa43b44bdb43dfbac0fcb51c56594a11338a8 patch link: https://lore.kernel.org/r/20260101-this_module_fix-v1-3-46ae3e5605a0%40gmail.com patch subject: [PATCH RFC 3/6] rust: WIP: use ThisModule trait for initializing config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260101/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) rustc: rustc 1.88.0 (6b00bc388 2025-06-23) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260101/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All error/warnings (new ones prefixed by >>):
PATH=/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INFO PATH=/opt/cross/rustc-1.88.0-bindgen-0.72.1/cargo/bin:/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS= -fno-crash-diagnostics -Wno-error=return-type -Wreturn-type -funsigned-char -Wundef W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck
make: Entering directory '/kbuild/src/consumer'
make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
>> Diff in rust/kernel/pci.rs:5:
//! C header: [`include/linux/pci.h`](srctree/include/linux/pci.h)
use crate::{
- bindings,
- container_of,
- device,
+ bindings, container_of, device,
device_id::{
RawDeviceId,
RawDeviceIdIndex, //
>> Diff in rust/kernel/pci.rs:5:
//! C header: [`include/linux/pci.h`](srctree/include/linux/pci.h)
use crate::{
- bindings,
- container_of,
- device,
+ bindings, container_of, device,
device_id::{
RawDeviceId,
RawDeviceIdIndex, // make[2]: *** [Makefile:1877: rustfmt] Error 123
make[2]: Target 'rustfmtcheck' not remade because of errors. make[1]: *** [Makefile:248: __sub-make] Error 2
make[1]: Target 'rustfmtcheck' not remade because of errors. make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
make: *** [Makefile:248: __sub-make] Error 2
make: Target 'rustfmtcheck' not remade because of errors.
make: Leaving directory '/kbuild/src/consumer'
--
>> warning: `crate` references the macro call's crate
--> rust/kernel/configfs.rs:1021:83
|
1021 | $crate::configfs::ItemType::<$container, $data>::new::<N, crate::THIS_MODULE>(
| ^^^^^ help: to reference the macro definition's crate, use: $crate
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#crate_in_macro_def
= note: -W clippy::crate-in-macro-def implied by -W clippy::all
= help: to override -W clippy::all add #[allow(clippy::crate_in_macro_def)]
--
>> warning: unresolved link to `macros::module::module`
--> rust/kernel/lib.rs:214:11
|
214 | //! [macros::module::module]. Mechanism is equivalent to THIS_MODULE in
| ^^^^^^^^^^^^^^^^^^^^^^ module is a macro, not a module or type, and cannot have associated items
|
= note: #[warn(rustdoc::broken_intra_doc_links)] on by default
--
>> warning: unresolved link to `this_module`
--> rust/kernel/lib.rs:223:15
|
223 | /// See [this_module]
| ^^^^^^^^^^^ no item named this_module in scope
|
= help: to escape [ and ] characters, add '' before them like [ or ]
--
>> warning: unresolved link to `this_module`
--> rust/kernel/lib.rs:229:15
|
229 | /// See [this_module]
| ^^^^^^^^^^^ no item named this_module in scope
|
= help: to escape [ and ] characters, add '' before them like [ or ]
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [PATCH RFC 5/6] rust: debugfs: WIP: Use owner for file_operations
In reply to Kari Argillanderkernel test robot noticed the following build warnings:
Hi Kari,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build warnings:
[auto build test WARNING on cc3aa43b44bdb43dfbac0fcb51c56594a11338a8]
url: https://github.com/intel-lab-lkp/linux/commits/Kari-Argillander/rust-Enable-const_refs_to_static-feature/20260101-172411 base: cc3aa43b44bdb43dfbac0fcb51c56594a11338a8 patch link: https://lore.kernel.org/r/20260101-this_module_fix-v1-5-46ae3e5605a0%40gmail.com patch subject: [PATCH RFC 5/6] rust: debugfs: WIP: Use owner for file_operations config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260101/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) rustc: rustc 1.88.0 (6b00bc388 2025-06-23) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260101/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> warning: method `create_file` is never used
--> rust/kernel/debugfs.rs:522:8
|
508 | impl<'data, 'dir> ScopedDir<'data, 'dir> {
| ---------------------------------------- method in this implementation
...
522 | fn create_file<T: Sync>(&self, name: &CStr, data: &'data T, vtable: &'static FileOps<T>) {
| ^^^^^^^^^^^
|
= note: #[warn(dead_code)] on by default
--
>> warning: associated function `file` is never used
--> rust/kernel/debugfs/entry.rs:103:19
|
83 | impl<'a> Entry<'a> {
| ------------------ associated function in this implementation
...
103 | pub(crate) fn file<T>(
| ^^^^
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [PATCH RFC 6/6] rust: WIP: Replace ModuleMetadata with THIS_MODULE
In reply to Kari Argillanderkernel test robot noticed the following build warnings:
Hi Kari,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build warnings:
[auto build test WARNING on cc3aa43b44bdb43dfbac0fcb51c56594a11338a8]
url: https://github.com/intel-lab-lkp/linux/commits/Kari-Argillander/rust-Enable-const_refs_to_static-feature/20260101-172411 base: cc3aa43b44bdb43dfbac0fcb51c56594a11338a8 patch link: https://lore.kernel.org/r/20260101-this_module_fix-v1-6-46ae3e5605a0%40gmail.com patch subject: [PATCH RFC 6/6] rust: WIP: Replace ModuleMetadata with THIS_MODULE config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260101/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) rustc: rustc 1.88.0 (6b00bc388 2025-06-23) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260101/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> warning: unused import: `str::CStr`
--> rust/kernel/driver.rs:94:31
|
94 | use crate::{acpi, device, of, str::CStr, try_pin_init, types::Opaque, ThisModule};
| ^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
--
>> warning: unused import: `str::CStr`
--> rust/kernel/pci.rs:21:5
|
21 | str::CStr,
| ^^^^^^^^^
--
>> warning: unused import: `str::CStr`
--> rust/kernel/usb.rs:14:5
|
14 | str::CStr,
| ^^^^^^^^^
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki