at commit 2e42cade

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 /// The module's `THIS_MODULE` pointer.
47 const THIS_MODULE: ThisModule;
48 }
49
50 /// Returns a reference to the `THIS_MODULE` of the given module type.
51 #[inline]
52 pub const fn this_module<M: ModuleMetadata>() -> &'static ThisModule {
53 &M::THIS_MODULE
54 }
55
56 /// Equivalent to `THIS_MODULE` in the C API.
57 ///
58 /// C header: [`include/linux/init.h`](srctree/include/linux/init.h)
59 pub struct ThisModule(*mut crate::bindings::module);
60
61 // SAFETY: `THIS_MODULE` may be used from all threads within a module.
62 unsafe impl Sync for ThisModule {}
63
64 impl ThisModule {
65 /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
66 ///
67 /// # Safety
68 ///
69 /// The pointer must be equal to the right `THIS_MODULE`.
70 pub const unsafe fn from_ptr(ptr: *mut crate::bindings::module) -> ThisModule {
71 ThisModule(ptr)
72 }
73
74 /// Access the raw pointer for this module.
75 ///
76 /// It is up to the user to use it correctly.
77 pub const fn as_ptr(&self) -> *mut crate::bindings::module {
78 self.0
79 }
80 }