kernel/module_param.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Support for module parameters.
4//!
5//! C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
6
7use crate::prelude::*;
8use crate::str::{kstrtobool_bytes, BStr};
9use bindings;
10use kernel::sync::SetOnce;
11
12/// Newtype to make `bindings::kernel_param` [`Sync`].
13#[repr(transparent)]
14#[doc(hidden)]
15pub struct KernelParam(bindings::kernel_param);
16
17impl KernelParam {
18 #[doc(hidden)]
19 pub const fn new(val: bindings::kernel_param) -> Self {
20 Self(val)
21 }
22}
23
24// SAFETY: C kernel handles serializing access to this type. We never access it
25// from Rust module.
26unsafe impl Sync for KernelParam {}
27
28/// Types that can be used for module parameters.
29// NOTE: This trait is `Copy` because drop could produce unsoundness during teardown.
30pub trait ModuleParam: Sized + Copy {
31 /// Parse a parameter argument into the parameter value.
32 fn try_from_param_arg(arg: &BStr) -> Result<Self>;
33}
34
35/// Set the module parameter from a string.
36///
37/// Used to set the parameter value at kernel initialization, when loading
38/// the module or when set through `sysfs`.
39///
40/// See `struct kernel_param_ops.set`.
41///
42/// # Safety
43///
44/// - If `val` is non-null then it must point to a valid null-terminated string that must be valid
45/// for reads for the duration of the call.
46/// - `param` must be a pointer to a `bindings::kernel_param` initialized by the rust module macro.
47/// The pointee must be valid for reads for the duration of the call.
48///
49/// # Note
50///
51/// - The safety requirements are satisfied by C API contract when this function is invoked by the
52/// module subsystem C code.
53/// - Currently, we only support read-only parameters that are not readable from `sysfs`. Thus, this
54/// function is only called at kernel initialization time, or at module load time, and we have
55/// exclusive access to the parameter for the duration of the function.
56///
57/// [`module!`]: macros::module
58unsafe extern "C" fn set_param<T>(val: *const c_char, param: *const bindings::kernel_param) -> c_int
59where
60 T: ModuleParam,
61{
62 // NOTE: If we start supporting arguments without values, val _is_ allowed
63 // to be null here.
64 if val.is_null() {
65 crate::pr_warn_once!("Null pointer passed to `module_param::set_param`\n");
66 return EINVAL.to_errno();
67 }
68
69 // SAFETY: By function safety requirement, val is non-null, null-terminated
70 // and valid for reads for the duration of this function.
71 let arg = unsafe { CStr::from_char_ptr(val) };
72 let arg: &BStr = arg.as_ref();
73
74 crate::error::from_result(|| {
75 let new_value = T::try_from_param_arg(arg)?;
76
77 // SAFETY: By function safety requirements, `param` is valid for read.
78 let arg = unsafe { (*param).__bindgen_anon_1.arg };
79 let param_access_ptr = arg.cast::<ModuleParamAccess<T>>();
80 // SAFETY: The `arg` field is initialized with a pointer to a `static ModuleAccessParam` by
81 // the rust module macro. Thus, the pointer is valid for use as a reference.
82 let param_access = unsafe { &*(param_access_ptr) };
83 let container = ¶m_access.value;
84
85 container
86 .populate(new_value)
87 .then_some(0)
88 .ok_or(kernel::error::code::EEXIST)
89 })
90}
91
92macro_rules! impl_int_module_param {
93 ($ty:ident) => {
94 impl ModuleParam for $ty {
95 fn try_from_param_arg(arg: &BStr) -> Result<Self> {
96 <$ty as crate::str::parse_int::ParseInt>::from_str(arg)
97 }
98 }
99 };
100}
101
102impl_int_module_param!(i8);
103impl_int_module_param!(u8);
104impl_int_module_param!(i16);
105impl_int_module_param!(u16);
106impl_int_module_param!(i32);
107impl_int_module_param!(u32);
108impl_int_module_param!(i64);
109impl_int_module_param!(u64);
110impl_int_module_param!(isize);
111impl_int_module_param!(usize);
112
113impl ModuleParam for bool {
114 fn try_from_param_arg(arg: &BStr) -> Result<Self> {
115 kstrtobool_bytes(arg)
116 }
117}
118
119/// A wrapper for kernel parameters.
120///
121/// This type is instantiated by the [`module!`] macro when module parameters are
122/// defined. You should never need to instantiate this type directly.
123///
124/// Note: This type is `pub` because it is used by module crates to access
125/// parameter values.
126pub struct ModuleParamAccess<T> {
127 value: SetOnce<T>,
128 default: T,
129}
130
131// SAFETY: We only create shared references to the contents of this container,
132// so if `T` is `Sync`, so is `ModuleParamAccess`.
133unsafe impl<T: Sync> Sync for ModuleParamAccess<T> {}
134
135impl<T> ModuleParamAccess<T> {
136 #[doc(hidden)]
137 pub const fn new(default: T) -> Self {
138 Self {
139 value: SetOnce::new(),
140 default,
141 }
142 }
143
144 /// Get a copy of the parameter value.
145 ///
146 /// Returns the value supplied at module load time, or the default value
147 /// if the parameter has not been set.
148 #[inline]
149 pub fn value(&self) -> T
150 where
151 T: Copy,
152 {
153 self.value.copy().unwrap_or(self.default)
154 }
155
156 /// Get a shared reference to the parameter value.
157 ///
158 /// Returns a reference to the value supplied at module load time, or a
159 /// reference to the default value if the parameter has not been set.
160 // Note: When sysfs access to parameters are enabled, we have to pass in a
161 // held lock guard here.
162 #[inline]
163 pub fn value_ref(&self) -> &T {
164 self.value.as_ref().unwrap_or(&self.default)
165 }
166
167 /// Get a mutable pointer to `self`.
168 ///
169 /// NOTE: In most cases it is not safe deref the returned pointer.
170 pub const fn as_void_ptr(&self) -> *mut c_void {
171 core::ptr::from_ref(self).cast_mut().cast()
172 }
173}
174
175#[doc(hidden)]
176/// Generate a static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) struct.
177///
178/// # Examples
179///
180/// ```ignore
181/// make_param_ops!(
182/// /// Documentation for new param ops.
183/// PARAM_OPS_MYTYPE, // Name for the static.
184/// MyType // A type which implements [`ModuleParam`].
185/// );
186/// ```
187macro_rules! make_param_ops {
188 ($ops:ident, $ty:ty) => {
189 #[doc(hidden)]
190 pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops {
191 flags: 0,
192 set: Some(set_param::<$ty>),
193 get: None,
194 free: None,
195 };
196 };
197}
198
199make_param_ops!(PARAM_OPS_I8, i8);
200make_param_ops!(PARAM_OPS_U8, u8);
201make_param_ops!(PARAM_OPS_I16, i16);
202make_param_ops!(PARAM_OPS_U16, u16);
203make_param_ops!(PARAM_OPS_I32, i32);
204make_param_ops!(PARAM_OPS_U32, u32);
205make_param_ops!(PARAM_OPS_I64, i64);
206make_param_ops!(PARAM_OPS_U64, u64);
207make_param_ops!(PARAM_OPS_ISIZE, isize);
208make_param_ops!(PARAM_OPS_USIZE, usize);
209make_param_ops!(PARAM_OPS_BOOL, bool);