1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Module-related types and helpers. 4 5 /// The entrypoint to implementing a kernel module. 6 /// 7 /// For any teardown or cleanup operations, your type may implement [`Drop`]. 8 pub trait Module: Sized + Sync + Send { 9 /// Called at module initialization time. 10 /// 11 /// Use this method to perform whatever setup or registration your module 12 /// should do. 13 /// 14 /// Equivalent to the `module_init` macro in the C API. 15 fn init(module: &'static ThisModule) -> crate::error::Result<Self>; 16 } 17 18 /// A module that is pinned and initialised in-place. 19 pub trait InPlaceModule: Sync + Send { 20 /// Creates an initialiser for the module. 21 /// 22 /// It is called when the module is loaded. 23 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, crate::error::Error>; 24 } 25 26 impl<T: Module> InPlaceModule for T { 27 fn init(module: &'static ThisModule) -> impl pin_init::PinInit<Self, crate::error::Error> { 28 let initer = move |slot: *mut Self| { 29 let m = <Self as Module>::init(module)?; 30 31 // SAFETY: `slot` is valid for write per the contract with `pin_init_from_closure`. 32 unsafe { slot.write(m) }; 33 Ok(()) 34 }; 35 36 // SAFETY: On success, `initer` always fully initialises an instance of `Self`. 37 unsafe { pin_init::pin_init_from_closure(initer) } 38 } 39 } 40 41 /// Metadata attached to a [`Module`] or [`InPlaceModule`]. 42 pub trait ModuleMetadata { 43 /// The name of the module as specified in the `module!` macro. 44 const NAME: &'static crate::str::CStr; 45 } 46 47 /// Equivalent to `THIS_MODULE` in the C API. 48 /// 49 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h) 50 pub struct ThisModule(*mut crate::bindings::module); 51 52 // SAFETY: `THIS_MODULE` may be used from all threads within a module. 53 unsafe impl Sync for ThisModule {} 54 55 impl ThisModule { 56 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer. 57 /// 58 /// # Safety 59 /// 60 /// The pointer must be equal to the right `THIS_MODULE`. 61 pub const unsafe fn from_ptr(ptr: *mut crate::bindings::module) -> ThisModule { 62 ThisModule(ptr) 63 } 64 65 /// Access the raw pointer for this module. 66 /// 67 /// It is up to the user to use it correctly. 68 pub const fn as_ptr(&self) -> *mut crate::bindings::module { 69 self.0 70 } 71 } 72