rust: add `module_params` macro
Subsystems (3)
PATCH v2 1/1 rust: add `module_params` macro
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without sysfs support.
This code is a reduced and updated version of code by Adam available in the original rust branch [1].
---
Changes since v1 [2]:
- Remove support for params without values (NOARG_ALLOWED).
- Improve documentation for try_from_param_arg.
- Use prelude import.
- Refactor try_from_param_arg to return Result.
- Refactor ParseInt::from_str to return Result.
- Move C callable functions out of ModuleParam trait.
- Rename literal string field parser to expect_string_field.
- Move parameter parsing from generation to parsing stage.
- Use absolute type paths in macro code.
- Inline kparamand read_func values.
- Resolve TODO regarding alignment attributes.
- Remove unnecessary unsafe blocks in macro code.
- Improve error message for unrecognized parameter types.
- Do not use self receiver when reading parameter value.
- Add parameter documentation to module! macro.
- Use empty enum for parameter type.
- Use addr_of_mut to get address of parameter value variable.
- Enabled building of docs for for module_param module.
--- rust/kernel/error.rs | 2 - rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 339 +++++++++++++++++++++++++++++++++++ rust/macros/helpers.rs | 8 + rust/macros/lib.rs | 40 ++++- rust/macros/module.rs | 229 ++++++++++++++++++++--- samples/rust/rust_minimal.rs | 10 ++ scripts/Makefile.build | 2 +- 8 files changed, 593 insertions(+), 38 deletions(-) create mode 100644 rust/kernel/module_param.rs
rust/kernel/error.rs +0 -2
@@ -312,8 +312,6 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {/// }) /// } /// ``` -// TODO: Remove `dead_code` marker once an in-kernel client is available. -#[allow(dead_code)] pub (crate )fn from_result <T ,F >(f:F ) ->T where T :From <i16 >,
rust/kernel/lib.rs +1 -0
@@ -38,6 +38,7 @@pub mod ioctl;#[cfg( CONFIG_KUNIT )] pub mod kunit; +pub mod module_param;#[cfg( CONFIG_NET )] pub mod net;pub mod page;
rust/kernel/module_param.rs new file +339 -0
339 lines not on this page · raw message
rust/macros/helpers.rs +8 -0
@@ -107,6 +107,14 @@ pub(crate) struct Generics { pub(crate) ty_generics: Vec<TokenTree>, } +pub (crate )fn expect_string_field (it: &mut token_stream::IntoIter , expected_name: &str ) ->String { +assert_eq! (expect_ident (it), expected_name); +assert_eq! (expect_punct (it),':' ); +let string =expect_string (it); +assert_eq! (expect_punct (it),',' ); + string +} +/// Parses the given `TokenStream` into `Generics` and the rest. /// /// The generics are not present in the rest, but a where clause might remain.
rust/macros/lib.rs +31 -9
@@ -20,6 +20,30 @@/// The `type` argument should be a type which implements the [`Module`] /// trait. Also accepts various forms of kernel metadata. /// +/// The `params` field describe module parameters. Each entry has the form +/// +/// ```ignore +/// parameter_name: type { +/// default: default_value, +/// description: "Description", +/// } +/// ``` +/// +/// `type` may be one of +/// +/// - `i8` +/// - `u8` +/// - `i8` +/// - `u8` +/// - `i16` +/// - `u16` +/// - `i32` +/// - `u32` +/// - `i64` +/// - `u64` +/// - `isize` +/// - `usize` +/// /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h) /// /// [`Module`]: ../kernel/trait.Module.html
@@ -36,21 +60,19 @@/// description: "My very own kernel module!", /// license: "GPL", /// alias: ["alternate_module_name"], +/// params: { +/// my_parameter: i64 { +/// default: 1, +/// description: "This parameter has a default of 1", +/// }, +/// }, /// } /// /// struct MyModule; /// /// impl kernel::Module for MyModule { /// fn init() -> Result<Self> { -/// // If the parameter is writeable, then the kparam lock must be -/// // taken to read the parameter: -/// { -/// let lock = THIS_MODULE.kernel_param_lock(); -/// pr_info!("i32 param is: {}\n", writeable_i32.read(&lock)); -/// } -/// // If the parameter is read only, it can be read without locking -/// // the kernel parameters: -/// pr_info!("i32 param is: {}\n", my_i32.read()); +/// pr_info!("i32 param is: {}\n", module_parameters::my_parameter::read()); /// Ok(Self) /// } /// }
rust/macros/module.rs +203 -26
341 lines not on this page · raw message
samples/rust/rust_minimal.rs +10 -0
@@ -10,6 +10,12 @@ author: "Rust for Linux Contributors", description: "Rust minimal sample", license: "GPL", + params: { + test_parameter: i64 { + default: 1, + description:"This parameter has a default of 1" , + }, + }, }struct RustMinimal {
@@ -20,6 +26,10 @@ impl kernel::Module for RustMinimal {fn init (_module: &'staticThisModule ) ->Result <Self > {pr_info! ("Rust minimal sample (init)\n" );pr_info! ("Am I built-in? {}\n" , !cfg! (MODULE )); +pr_info! ( +"My parameter: {}\n" , + *module_parameters::test_parameter::read () + );let mut numbers =Vec ::new (); numbers.push (72 ,GFP_KERNEL )?;
scripts/Makefile.build +1 -1
@@ -263,7 +263,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := new_uninit +rust_allowed_features := new_uninit,const_mut_refs # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree
base-commit: 7c626ce4bae1ac14f60076d00eafe71af30450ba
Signature · 1 line
2.46.0
Trevor Gross
reviewerQuoted 17 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without
sysfssupport.rust/kernel/module_param.rs new file +4
-0@@ -0,0 +1,339 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Types for module parameters. +//!
rust/kernel/module_param.rs line 14
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+//! C header: [`include/linux/moduleparam.h`](../../../include/linux/moduleparam.h) + +use crate ::prelude::*; + +/// Types that can be used for module parameters. +/// +/// Note that displaying the type in `sysfs` will fail if +/// [`core::str::from_utf8`] (as implemented through the [`core::fmt::Display`] +/// trait) writes more than [`PAGE_SIZE`] bytes (including an additional null +/// terminator).
I'm a bit confused where str::from_utf8 comes into play - maybe just:
Note that displaying the type in sysfs will fail if the [Display] (core::fmt::Display) implementation would write more than [PAGE_SIZE] - 1 bytes.
rust/kernel/module_param.rs line 17
Quoted 2 lines
rust/kernel/module_param.rs new file +2
-0+/// [`PAGE_SIZE`]: `bindings::PAGE_SIZE` +pub trait ModuleParam : core::fmt::Display + core::marker::Sized {
I don't think Sized should need core::marker
rust/kernel/module_param.rs line 24
Quoted 7 lines
rust/kernel/module_param.rs new file +7
-0+/// The `ModuleParam` will be used by the kernel module through this type. +/// +/// This may differ from `Self` if, for example, `Self` needs to track +/// ownership without exposing it or allocate extra space for other possible +/// parameter values. This is required to support string parameters in the +/// future. +type Value : ?Sized ;
^ proof of the above :)
"This is required... in the future" could probably be moved to a non-doc comment or just dropped.
rust/kernel/module_param.rs line 114
Quoted 11 lines
rust/kernel/module_param.rs new file +11
-0+/// Write a string representation of the current parameter value to `buf`. +/// +/// # Safety +/// +/// Must not be called. +/// +/// # Note +/// +/// This should not be called as we declare all parameters as read only. +#[allow(clippy::extra_unused_type_parameters)] +unsafe extern "C" fn get_param<T>(
I think this could make sense being a safe function. I get that calling it would mean something is wrong - but that's a problem of broken invariants elsewhere and not just calling this, no?
rust/kernel/module_param.rs line 151
Quoted 11 lines
rust/kernel/module_param.rs new file +11
-0+/// Trait for parsing integers. +/// +/// Strings beginning with `0x`, `0o`, or `0b` are parsed as hex, octal, or +/// binary respectively. Strings beginning with `0` otherwise are parsed as +/// octal. Anything else is parsed as decimal. A leading `+` or `-` is also +/// permitted. Any string parsed by [`kstrtol()`] or [`kstrtoul()`] will be +/// successfully parsed. +/// +/// [`kstrtol()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtol +/// [`kstrtoul()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtoul +trait ParseInt :Sized {
Since this is standalone functionality, it might be better moved to a different module for reuse (and probably its own patch).
I'm not sure about the name either, would something like FromKStr with a method from_kstr make more sense? Also because the current trait will conflict if core::str::FromStr is also in scope.
The methods could use docs, and the trait could probably get a doctest and/or some unit tests.
rust/kernel/module_param.rs line 188
Quoted 11 lines
rust/kernel/module_param.rs new file +11
-0+fn from_str (src: &str ) ->Result <Self > { +match src.bytes ().next () { +None =>Err (EINVAL ), +Some (b'-' ) =>Self ::from_str_unsigned (&src[1 ..]) + .map_err (|_|EINVAL )? + .checked_neg () + .ok_or (EINVAL ), +Some (b'+' ) =>Self ::from_str_unsigned (&src[1 ..]).map_err (|_|EINVAL ), +Some (_) =>Self ::from_str_unsigned (src).map_err (|_|EINVAL ), + } + }
kstrtol returns -ERANGE on overflow, this might need to check the .kind() of parse errors to match this
rust/kernel/module_param.rs line 58
Quoted 2 lines
rust/kernel/module_param.rs new file +2
-0+macro_rules! impl_parse_int { + ($ty:ident) => {
Nit: $ty could be a :ty here (makes no difference)
rust/kernel/module_param.rs line 216
Quoted 1 line
rust/kernel/module_param.rs new file +1
-0+macro_rules! impl_module_param {
Nit: maybe impl_int_module_param since it doesn't handle other types
rust/kernel/module_param.rs line 246
Quoted 13 lines
rust/kernel/module_param.rs new file +13
-0+#[doc(hidden)] +#[macro_export] +/// Generate a static [`kernel_param_ops`](../../../include/linux/moduleparam.h) struct. +/// +/// # Examples +/// +/// ```ignore +/// make_param_ops!( +/// /// Documentation for new param ops. +/// PARAM_OPS_MYTYPE, // Name for the static. +/// MyType // A type which implements [`ModuleParam`]. +/// ); +/// ```
Nit: move attributes to after the docs
rust/kernel/module_param.rs line 254
Quoted 8 lines
rust/kernel/module_param.rs new file +8
-0+macro_rules! make_param_ops { + ($ops:ident, $ty:ty) => { + $crate::make_param_ops!( +#[doc= "" ] + $ops, + $ty + ); + };
I don't think you need this first pattern, since the meta in the below pattern is optional. But...
rust/kernel/module_param.rs line 256
Quoted 2 lines
rust/kernel/module_param.rs new file +2
-0+ ($(#[$meta:meta])* $ops:ident, $ty:ty) => { + $(#[$meta])*
...you could probably just drop the $meta and remove docs from the invocation by adding the following here
/// Rust implementation of [`kernel_param_ops`]
/// (../../../include/linux/moduleparam.h)
#[doc(concat!("for [`", stringify!($ty), "`].))]Since the docs are the same except the type
rust/kernel/module_param.rs line 265
Quoted 9 lines
rust/kernel/module_param.rs new file +9
-0+/// +/// Static [`kernel_param_ops`](../../../include/linux/moduleparam.h) +/// struct generated by [`make_param_ops`]. + pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops { + flags:0 , + set:Some (set_param ::<$ty>), + get:Some (get_param ::<$ty>), + free:Some (free ::<$ty>), + };
Could this be a const rather than a static?
rust/kernel/module_param.rs line 278
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+impl_module_param! (i8 ); +impl_module_param! (u8 ); +impl_module_param! (i16 ); +impl_module_param! (u16 ); +impl_module_param! (i32 ); +impl_module_param! (u32 ); +impl_module_param! (i64 ); +impl_module_param! (u64 ); +impl_module_param! (isize ); +impl_module_param! (usize );
Nit: these could probably go above impl_module_param to be next to their macro definition.
rust/macros/helpers.rs pub(crate) struct Generics { · line 110
Quoted 9 lines
rust/macros/helpers.rs +1
-0@@ -107,6 +107,14 @@ pub(crate) struct Generics { pub(crate) ty_generics: Vec<TokenTree>, } +pub (crate )fn expect_string_field (it: &mut token_stream::IntoIter , expected_name: &str ) ->String {
Just to make it obvious what it is looking for:
/// Expect `expected_name: "value",`
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 109
Quoted 7 lines
rust/macros/module.rs +2
-0+fn emit_params (&mut self, info: &ModuleInfo ) { +if let Some (params) = &info.params {
Switching to
let Some(params) = &info.params else {
return;
};would save an indentation level
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 115
Quoted 6 lines
rust/macros/module.rs +6
-0+for paramin params { +let ops =param_ops_path (¶m.ptype); + + self.emit_param ("parmtype" , ¶m.name, ¶m.ptype); + self.emit_param ("parm" , ¶m.name, ¶m.description); +
(Referring to below) could the template string body be indented another level, so it doesn't hang left of the parent write! macro?
Also - maybe let pfx = format!("__{name}_{param_name}") here then use {pfx}` in the template, since that sequence is repeated a lot.
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 119
Quoted 4 lines
rust/macros/module.rs +4
-0+write! ( + self.param_buffer, + " +static mut __ {name}_ {param_name}_value: {param_type} = {param_default};
Ah.. we need to migrate from static mut to UnsafeCell wrappers at some point. Since module! already uses static mut, this may need to happen separately - meaning I don't think we need to block on making any change here.
This would mean adding an UnsafeSyncCell / RacyCell (just a wrapper around UnsafeCell that always implements Sync), using UnsafeSyncCell<{param_type}> as the type here, and changing from static mut to just static.
(I can take a look at doing this change for existing static mut in the near future).
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 144
Quoted 7 lines
rust/macros/module.rs +7
-0+/// Newtype to make `bindings::kernel_param` `Sync`. +#[repr(transparent)] + struct __{name}_{param_name}_RacyKernelParam(::kernel::bindings::kernel_param); + +// SAFETY: C kernel handles serializing access to this type. We +// never access from Rust module. + unsafe impl Sync for __{name}_{param_name}_RacyKernelParam {{ }}
Could there just be a type for this in the kernel crate rather than creating one as part of the macro?
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 148
Quoted 3 lines
rust/macros/module.rs +3
-0+#[cfg(not( MODULE ))] + const __{name}_{param_name}_name: *const ::core::ffi::c_char = + b\"{name}.{param_name}\\0\" as *const _ as *const ::core::ffi::c_char;
This should work as c\"{name}.{param_name}\".as_ptr() now
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 152
Quoted 4 lines
rust/macros/module.rs +4
-0+ +#[cfg( MODULE )] + const __{name}_{param_name}_name: *const ::core::ffi::c_char = + b\"{param_name}\\0\" as *const _ as *const ::core::ffi::c_char;
Same as above.
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 158
Quoted 5 lines
rust/macros/module.rs +5
-0+ #[link_section = \"__param\"] +#[used] + static __{name}_{param_name}_struct: __{name}_{param_name}_RacyKernelParam = + __{name}_{param_name}_RacyKernelParam(::kernel::bindings::kernel_param {{ + name: __{name}_{param_name}_name,
You could eliminate the above __{name}_{param_name}_name consts by using:
name: if cfg!(MODULE) {
c\"{param_name}\\"
} else {
c\"{name}.{param_name}\\"
}.as_ptr(),rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 162
Quoted 4 lines
rust/macros/module.rs +4
-0+// SAFETY: `__this_module` is constructed by the kernel at load time +// and will not be freed until the module is unloaded. +#[cfg( MODULE )] + mod_: unsafe {{ &::kernel::bindings::__this_module as *const _ as *mut _ }},
Prefer .cast::<T>().cast_mut()
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 166
Quoted 4 lines
rust/macros/module.rs +4
-0+#[cfg(not( MODULE ))] + mod_: ::core::ptr::null_mut(), + ops: &{ops} as *const ::kernel::bindings::kernel_param_ops, + perm: 0, // Will not appear in sysfs
For my knowledge, what would be needed to make sysfs work?
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 175
Quoted 9 lines
rust/macros/module.rs +9
-0+ level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ +// SAFETY: As this is evaluated in const context, it is +// safe to take a reference to a mut static. + arg:unsafe {{ + ::core::ptr::addr_of_mut!(__ {name}_ {param_name}_value) + }}.cast ::<::core::ffi::c_void >(),
A note on this toward the end
rust/macros/module.rs pub(crate) fn module(ts: TokenStream) -> TokenStream {
Quoted 5 lines
rust/macros/module.rs +3
-0+ }}, + }}); + ",@@ -216,12 +387,14 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
Is a lot of below just some rewrapping and leading ::? It may be good to split off tweaks to the existing code
Quoted 73 lines
rust/macros/module.rs +15
-9// 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 {{ - kernel::ThisModule ::from_ptr (&kernel::bindings::__this_moduleas *const _ as *mut _ ) +static THIS_MODULE : ::kernel::ThisModule =unsafe {{ + ::kernel::ThisModule ::from_ptr ( + &::kernel::bindings::__this_moduleas *const _ as *mut _ + ) }};#[cfg(not( MODULE ))] -static THIS_MODULE : kernel::ThisModule =unsafe {{ - kernel::ThisModule ::from_ptr (core::ptr::null_mut ()) +static 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. @@ -276,7 +449,8 @@ mod __module_init {{#[doc(hidden)] #[link_section = \"{initcall_section}\"] #[used] - pub static __{name}_initcall: extern \"C\" fn() -> core::ffi::c_int = __{name}_init; + pub static __{name}_initcall: extern \"C\" fn() + -> ::core::ffi::c_int = __{name}_init; #[cfg(not(MODULE))] #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]@@ -291,7 +465,7 @@ mod __module_init {{#[cfg(not( MODULE ))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_init() -> core::ffi::c_int {{ + pub extern \"C\" fn __{name}_init() -> ::core::ffi::c_int {{ // SAFETY: This function is inaccessible to the outside due to the double // module wrapping it. It is called exactly once by the C side via its // placement above in the initcall section.@@ -314,8 +488,8 @@ mod __module_init {{/// # Safety /// /// This function must only be called once. -unsafe fn __init () -> core::ffi::c_int {{ - match <{type_} as kernel::Module>::init(&super::super::THIS_MODULE) {{ +unsafe fn __init () -> ::core::ffi::c_int {{ + match <{type_} as ::kernel::Module>::init(&super::super::THIS_MODULE) {{Ok (m) => {{// SAFETY: No data race, since `__MOD` can only be accessed by this // module and there only `__init` and `__exit` access it. These @@ -346,14 +520,17 @@ unsafe fn __exit() {{ __MOD =None ; }} }} - {modinfo} }} }} + mod module_parameters {{ + {params} + }}", type_ = info.type_, name = info.name, modinfo = modinfo.buffer, +params = modinfo.param_buffer, initcall_section = ".initcall6.init" ) .parse ()samples/rust/rust_minimal.rs +0
-0
samples/rust/rust_minimal.rs line 19
Quoted 10 lines
samples/rust/rust_minimal.rs +6
-0@@ -10,6 +10,12 @@ author: "Rust for Linux Contributors", description: "Rust minimal sample", license: "GPL", + params: { + test_parameter: i64 { + default: 1, + description:"This parameter has a default of 1" , + }, + }, }
I was going to suggest updating the sample then saw you did that already, thanks :)
scripts/Makefile.build $(obj)/%.lst: $(obj)/%.c FORCE · line 266
Quoted 10 lines
scripts/Makefile.build +1
-1@@ -263,7 +263,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := new_uninit +rust_allowed_features := new_uninit,const_mut_refs
We shouldn't enable const_mut_refs. It is indeed close to stabilization, but it is still kind of churny right now and we don't want to enable the sharp edges everywhere.
If the change from static mut to UnsafeCell that I mentioned above happens, addr_of_mut! turns into a .get().cast::<...>() takes the place of addr_of_mut! and doesn't require this feature (and also isn't unsafe).
If you prefer not to make that change, I think addr_of!(...).cast_mut() might be the best solution.
---
Other thought: would a wrapper type make more sense here? Something like this:
```
/* implementation */
struct ModParam<T>(UnsafeCell<T>);
// `Parameter` is the existing `ModParameter` (could be
// any name). It could be sealed.
impl<T: Parameter> ModParam<T> {
#[doc(hidden)] // used in the macro
fn new(value: T) -> Self { ... }
fn get(&self) -> T::Value { ... }
fn set(&self, v: T::Value) { ... }
}
```With usage:
```
module! {
// ...
// instantiated as:
// `static MY_PARAM: ModParam<i64> = ModParam::new(1);`
MY_PARAM: i64 {
default: 1,
description: "foo",
},
}
fn foo() {
pr_info!("My param is {}", MY_PARAM.get());
}
```Advantages I see:
- You bring your own name, rather than being scoped and needing to remember the module name
- You can check ModParam in the docs to see the API, rather than needing to refer to source for the exact signatures of read and write
- The interface gets a bit more like a mutex or atomic
- Trevor
Quoted 9 lines · Trevor Gross
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 119
Quoted 5 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
rust/macros/module.rs +4
-0+write! ( + self.param_buffer, + " +static mut __ {name}_ {param_name}_value: {param_type} = {param_default};Ah.. we need to migrate from
static muttoUnsafeCellwrappers at some point. Sincemodule!already usesstatic mut, this may need
IIRC Alice wanted to do something about that.
Quoted 26 lines
to happen separately - meaning I don't think we need to block on making any change here.
This would mean adding an
UnsafeSyncCell/RacyCell(just a wrapper aroundUnsafeCellthat always implementsSync), usingUnsafeSyncCell<{param_type}>as the type here, and changing fromstatic mutto juststatic.(I can take a look at doing this change for existing
static mutin the near future).scripts/Makefile.build $(obj)/%.lst: $(obj)/%.c FORCE · line 266
Quoted 10 lines
scripts/Makefile.build +1
-1@@ -263,7 +263,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := new_uninit +rust_allowed_features := new_uninit,const_mut_refsWe shouldn't enable
const_mut_refs. It is indeed close to stabilization, but it is still kind of churny right now and we don't want to enable the sharp edges everywhere.
Quoted 4 lines
If the change from
static muttoUnsafeCellthat I mentioned above happens,addr_of_mut!turns into a.get().cast::<...>()takes the place ofaddr_of_mut!and doesn't require this feature (and also isn't unsafe).
I think this is a good idea. There might only be a problem with not being Sync though... So probably need to use SyncUnsafeCell instead.
Quoted 2 lines
If you prefer not to make that change, I think
addr_of!(...).cast_mut()might be the best solution.
Won't that be resulting in the wrong provenance? I.e. the pointer won't be allowed to write to that location?
I just checked with miri, it doesn't complain (even with strict-provenance), so I guess it's fine? It feels rather wrong to me to allow writing through a pointer obtained via addr_of!.
Quoted 19 lines
---
Other thought: would a wrapper type make more sense here? Something like this:
``` /* implementation */ struct ModParam<T>(UnsafeCell<T>); // `Parameter` is the existing `ModParameter` (could be // any name). It could be sealed. impl<T: Parameter> ModParam<T> { #[doc(hidden)] // used in the macro fn new(value: T) -> Self { ... } fn get(&self) -> T::Value { ... } fn set(&self, v: T::Value) { ... } } ```
Quoted 7 lines
With usage:
```
module! { // ... // instantiated as: // `static MY_PARAM: ModParam<i64> = ModParam::new(1);`
We used to do this, but it lead to problems: normally the parameter has a lower case name, since that's the convention in the kernel. But then pattern matching prioritises the static instead of introducing it as a local parameter:
let MY_PARAM = ...;
would fail, since you can't match MY_PARAM.
This is also the reason why they live in their own module.
But you can still do the modification of creating ModParam and using that as the type of the static.
---
Cheers,
Benno
Quoted 20 lines
MY_PARAM: i64 { default: 1, description: "foo", }, }fn foo() { pr_info!("My param is {}", MY_PARAM.get()); }```
Advantages I see:
- You bring your own name, rather than being scoped and needing to remember the module name
- You can checkModParamin the docs to see the API, rather than needing to refer to source for the exact signatures ofreadandwrite
- The interface gets a bit more like a mutex or atomic- Trevor
Trevor Gross
reviewerQuoted 11 lines · Benno Lossin
Quoted 8 lines
We shouldn't enable
const_mut_refs. It is indeed close to stabilization, but it is still kind of churny right now and we don't want to enable the sharp edges everywhere.If the change from
static muttoUnsafeCellthat I mentioned above happens,addr_of_mut!turns into a.get().cast::<...>()takes the place ofaddr_of_mut!and doesn't require this feature (and also isn't unsafe).I think this is a good idea. There might only be a problem with not being
Syncthough... So probably need to useSyncUnsafeCellinstead.
Ah whoops, yeah that is what I meant.
Quoted 9 lines
Quoted 2 lines
If you prefer not to make that change, I think
addr_of!(...).cast_mut()might be the best solution.Won't that be resulting in the wrong provenance? I.e. the pointer won't be allowed to write to that location?
I just checked with miri, it doesn't complain (even with
strict-provenance), so I guess it's fine? It feels rather wrong to me to allow writing through a pointer obtained viaaddr_of!.
I think that static mut gets the interior mutability rules that UnsafeCell has, that *const and *mut become interchangeable. Quick demo for the UnsafeCell at [1]. We would probably have to ask opsem to clarify.
Coincidentally I had been talking to Ralf about this very pattern before seeing this, at [2].
Quoted 11 lines
Quoted 10 lines
Other thought: would a wrapper type make more sense here? Something like this:
```
/* implementation */
struct ModParam<T>(UnsafeCell<T>);
[...]module! { // ... // instantiated as: // `static MY_PARAM: ModParam<i64> = ModParam::new(1);`
Quoted 2 lines
We used to do this, but it lead to problems: normally the parameter has a lower case name, since that's the convention in the kernel. [...]
To me it seemed logical to keep the uppercase names here since it matches the convention for what they are (statics), and the macro could lowercase it for the bits exposed to the kernel. But I absolutely get the consistency argument here.
Quoted 9 lines
[...] But then
pattern matching prioritises the static instead of introducing it as a local parameter:let MY_PARAM = ...;would fail, since you can't match
MY_PARAM.This is also the reason why they live in their own module.
I'm not sure I follow the example here. It looks like it is shadowing a static's name as a local, why would you want that? Or if you meant the other way around let SomePat(...) = MY_PARAM, wouldn't it just be let SomePat(...) = MY_PARAM.get()? (Sorry if I missed some context here).
Quoted 2 lines
But you can still do the modification of creating
ModParamand using that as the type of the static.
Do you mean an expansion like this?
// module_parameters is kind of a long name
mod mod_params {
#[allow(non_upper_case_globals)]
static my_param: ModParam<i32> = ModParam::new(...);
}I don't mind that, even if the name is a bit weird by rust conventions.
(For what it's worth, I used this wrapper type pattern for a plugin project that does shared variables in a similar way. I have been quite happy with it.)
- Trevor
[1]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=43664620f50384b7a3d5bf74ce7c3e39
[2]: https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/More.20accidental.20stabilization
Quoted 21 lines · Trevor Gross
Quoted 11 lines · Benno Lossin
Quoted 8 lines
We shouldn't enable
const_mut_refs. It is indeed close to stabilization, but it is still kind of churny right now and we don't want to enable the sharp edges everywhere.If the change from
static muttoUnsafeCellthat I mentioned above happens,addr_of_mut!turns into a.get().cast::<...>()takes the place ofaddr_of_mut!and doesn't require this feature (and also isn't unsafe).I think this is a good idea. There might only be a problem with not being
Syncthough... So probably need to useSyncUnsafeCellinstead.Ah whoops, yeah that is what I meant.
Quoted 6 lines
Quoted 2 lines
If you prefer not to make that change, I think
addr_of!(...).cast_mut()might be the best solution.Won't that be resulting in the wrong provenance? I.e. the pointer won't be allowed to write to that location?
Quoted 8 lines
Quoted 3 lines
I just checked with miri, it doesn't complain (even with
strict-provenance), so I guess it's fine? It feels rather wrong to me to allow writing through a pointer obtained viaaddr_of!.I think that
static mutgets the interior mutability rules thatUnsafeCellhas, that *const and *mut become interchangeable. Quick demo for theUnsafeCellat [1]. We would probably have to ask opsem to clarify.
I see. I suggested to Andreas to change it to the current version, seems like I was wrong on this... I feel like the SyncUnsafeCell version is still better, since we can avoid a static mut.
Quoted 14 lines
Coincidentally I had been talking to Ralf about this very pattern before seeing this, at [2].
Quoted 11 lines
Quoted 10 lines
Other thought: would a wrapper type make more sense here? Something like this:
```
/* implementation */
struct ModParam<T>(UnsafeCell<T>);
[...]module! { // ... // instantiated as: // `static MY_PARAM: ModParam<i64> = ModParam::new(1);`
Quoted 7 lines
Quoted 2 lines
We used to do this, but it lead to problems: normally the parameter has a lower case name, since that's the convention in the kernel. [...]
To me it seemed logical to keep the uppercase names here since it matches the convention for what they are (statics), and the macro could lowercase it for the bits exposed to the kernel. But I absolutely get the consistency argument here.
That would also be an option, but it might be confusing for people, they enter a SCREAMING_CASE_SNAKE name, but when they start the kernel it doesn't work.
Quoted 8 lines
Quoted 8 lines
[...] But then
pattern matching prioritises the static instead of introducing it as a local parameter:let MY_PARAM = ...;would fail, since you can't match
MY_PARAM.
Quoted 7 lines
Quoted 1 line
This is also the reason why they live in their own module.
I'm not sure I follow the example here. It looks like it is shadowing a static's name as a local, why would you want that? Or if you meant the other way around
let SomePat(...) = MY_PARAM, wouldn't it just belet SomePat(...) = MY_PARAM.get()? (Sorry if I missed some context here).
Yeah I expressed this poorly, the problem before was that you would write:
module! {
/* ... */
params: {
foo: i64 {
default: 1,
description: "foo",
}
}
}
pub struct MyDriver {
foo: i64,
}
impl Module for MyDriver {
fn init(_: &'static ThisModule) -> Result<Self> {
let foo = foo.read();
// ^^^ cannot be named the same as a static
Ok(Self { foo })
}
}Quoted 10 lines
Quoted 2 lines
But you can still do the modification of creating
ModParamand using that as the type of the static.Do you mean an expansion like this?
// module_parameters is kind of a long name mod mod_params { #[allow(non_upper_case_globals)] static my_param: ModParam<i32> = ModParam::new(...); }
Yes that's what I meant, although my_param should be pub(crate).
Quoted 1 line
I don't mind that, even if the name is a bit weird by rust conventions.
Yeah, but I think since they are in their own module, it's fine.
One thing that we need to decide would be if we want
mod_params::my_param::read()
or
mod_params::my_param.read()
I slightly prefer the first one, which would mean that the expansion would have to be:
mod mod_params {
pub(crate) enum my_param {}
static my_param_value: ModParam<i32> = ModParam::new(...);
impl my_param {
pub(crate) fn read() {
my_param_value.read()
}
/* ... */
}
}Quoted 3 lines
(For what it's worth, I used this wrapper type pattern for a plugin project that does shared variables in a similar way. I have been quite happy with it.)
Good to know!
---
Cheers,
Benno
Hi Trevor,
Thanks a lot for the thorough review!
Quoted 31 lines · Trevor Gross
Quoted 17 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without
sysfssupport.rust/kernel/module_param.rs new file +4
-0@@ -0,0 +1,339 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Types for module parameters. +//! rust/kernel/module_param.rs line 14
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+//! C header: [`include/linux/moduleparam.h`](../../../include/linux/moduleparam.h) + +use crate ::prelude::*; + +/// Types that can be used for module parameters. +/// +/// Note that displaying the type in `sysfs` will fail if +/// [`core::str::from_utf8`] (as implemented through the [`core::fmt::Display`] +/// trait) writes more than [`PAGE_SIZE`] bytes (including an additional null +/// terminator). I'm a bit confused where
str::from_utf8comes into play - maybe just:
Quoted 3 lines
Note that displaying the type in
sysfswill fail if the [Display] (core::fmt::Display) implementation would write more than [PAGE_SIZE] - 1 bytes.
I think it is a hint for where to look if things go wrong for core types. But it makes sense to cut it to cut Display.
Quoted 4 lines
rust/kernel/module_param.rs line 17
Quoted 2 lines
rust/kernel/module_param.rs new file +2
-0+/// [`PAGE_SIZE`]: `bindings::PAGE_SIZE` +pub trait ModuleParam : core::fmt::Display + core::marker::Sized {I don't think
Sizedshould needcore::marker
Thanks.
Quoted 9 lines
rust/kernel/module_param.rs line 24
Quoted 8 lines
rust/kernel/module_param.rs new file +7
-0+/// The `ModuleParam` will be used by the kernel module through this type. +/// +/// This may differ from `Self` if, for example, `Self` needs to track +/// ownership without exposing it or allocate extra space for other possible +/// parameter values. This is required to support string parameters in the +/// future. +type Value : ?Sized ;
Quoted 4 lines
^ proof of the above :)
"This is required... in the future" could probably be moved to a non-doc comment or just dropped.
OK.
Quoted 16 lines
rust/kernel/module_param.rs line 114
Quoted 12 lines
rust/kernel/module_param.rs new file +11
-0+/// Write a string representation of the current parameter value to `buf`. +/// +/// # Safety +/// +/// Must not be called. +/// +/// # Note +/// +/// This should not be called as we declare all parameters as read only. +#[allow(clippy::extra_unused_type_parameters)] +unsafe extern "C" fn get_param<T>(I think this could make sense being a safe function. I get that calling it would mean something is wrong - but that's a problem of broken invariants elsewhere and not just calling this, no?
The "must not be called" requirement will be dropped when we support parameters writable through sysfs. Once we allow it to be called, it is going to have safety requirements and it will have to be unsafe. So I see no point it not making it unsafe now.
Quoted 16 lines
rust/kernel/module_param.rs line 151
Quoted 12 lines
rust/kernel/module_param.rs new file +11
-0+/// Trait for parsing integers. +/// +/// Strings beginning with `0x`, `0o`, or `0b` are parsed as hex, octal, or +/// binary respectively. Strings beginning with `0` otherwise are parsed as +/// octal. Anything else is parsed as decimal. A leading `+` or `-` is also +/// permitted. Any string parsed by [`kstrtol()`] or [`kstrtoul()`] will be +/// successfully parsed. +/// +/// [`kstrtol()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtol +/// [`kstrtoul()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtoul +trait ParseInt :Sized {Since this is standalone functionality, it might be better moved to a different module for reuse (and probably its own patch).
Quoted 3 lines
I'm not sure about the name either, would something like
FromKStrwith a methodfrom_kstrmake more sense? Also because the current trait will conflict ifcore::str::FromStris also in scope.
I see, that makes sense. I can rename it and move it to a separate patch and module.
Quoted 3 lines
The methods could use docs, and the trait could probably get a doctest and/or some unit tests.
I will add that.
Quoted 13 lines
rust/kernel/module_param.rs line 188
Quoted 12 lines
rust/kernel/module_param.rs new file +11
-0+fn from_str (src: &str ) ->Result <Self > { +match src.bytes ().next () { +None =>Err (EINVAL ), +Some (b'-' ) =>Self ::from_str_unsigned (&src[1 ..]) + .map_err (|_|EINVAL )? + .checked_neg () + .ok_or (EINVAL ), +Some (b'+' ) =>Self ::from_str_unsigned (&src[1 ..]).map_err (|_|EINVAL ), +Some (_) =>Self ::from_str_unsigned (src).map_err (|_|EINVAL ), + } + }
Quoted 2 lines
kstrtol returns
-ERANGEon overflow, this might need to check the.kind()of parse errors to match this
Good idea.
Quoted 5 lines
rust/kernel/module_param.rs line 58
Quoted 3 lines
rust/kernel/module_param.rs new file +2
-0+macro_rules! impl_parse_int { + ($ty:ident) => {Nit:
$tycould be a:tyhere (makes no difference)
👍
Quoted 4 lines
rust/kernel/module_param.rs line 216
Quoted 2 lines
rust/kernel/module_param.rs new file +1
-0+macro_rules! impl_module_param {Nit: maybe
impl_int_module_paramsince it doesn't handle other types
Yes.
Quoted 16 lines
Quoted 4 lines
rust/kernel/module_param.rs new file +3
-0+#[doc(hidden)] +#[macro_export] +/// Generate a static [`kernel_param_ops`](../../../include/linux/moduleparam.h) struct. rust/kernel/module_param.rs line 246
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+/// +/// # Examples +/// +/// ```ignore +/// make_param_ops!( +/// /// Documentation for new param ops. +/// PARAM_OPS_MYTYPE, // Name for the static. +/// MyType // A type which implements [`ModuleParam`]. +/// ); +/// ``` Nit: move attributes to after the docs
Will do. Is that a style thing we documented somewhere? Could we have clippy warn about this?
Quoted 16 lines
rust/kernel/module_param.rs line 254
Quoted 9 lines
rust/kernel/module_param.rs new file +8
-0+macro_rules! make_param_ops { + ($ops:ident, $ty:ty) => { + $crate::make_param_ops!( +#[doc= "" ] + $ops, + $ty + ); + };I don't think you need this first pattern, since the meta in the below pattern is optional. But...
rust/kernel/module_param.rs line 256
Quoted 2 lines
rust/kernel/module_param.rs new file +2
-0+ ($(#[$meta:meta])* $ops:ident, $ty:ty) => { + $(#[$meta])*
Quoted 8 lines
...you could probably just drop the
$metaand remove docs from the invocation by adding the following here/// Rust implementation of [`kernel_param_ops`] /// (../../../include/linux/moduleparam.h) #[doc(concat!("for [`", stringify!($ty), "`].))]Since the docs are the same except the type
I am not sure I think that is more simple. But either way is fine by me.
Quoted 11 lines
rust/kernel/module_param.rs line 265
Quoted 10 lines
rust/kernel/module_param.rs new file +9
-0+/// +/// Static [`kernel_param_ops`](../../../include/linux/moduleparam.h) +/// struct generated by [`make_param_ops`]. + pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops { + flags:0 , + set:Some (set_param ::<$ty>), + get:Some (get_param ::<$ty>), + free:Some (free ::<$ty>), + };
Quoted 1 line
Could this be a const rather than a static?
It cannot, because we need an address for it. As far as I understand const items are not guaranteed to have an address.
Quoted 14 lines
rust/kernel/module_param.rs line 278
Quoted 11 lines
rust/kernel/module_param.rs new file +10
-0+impl_module_param! (i8 ); +impl_module_param! (u8 ); +impl_module_param! (i16 ); +impl_module_param! (u16 ); +impl_module_param! (i32 ); +impl_module_param! (u32 ); +impl_module_param! (i64 ); +impl_module_param! (u64 ); +impl_module_param! (isize ); +impl_module_param! (usize );Nit: these could probably go above
impl_module_paramto be next to their macro definition.
Either that, or we move each of the three macro instances for each type together.
Quoted 9 lines
Quoted 9 lines
rust/macros/helpers.rs +0
-0@@ -107,6 +107,14 @@ pub(crate) struct Generics { pub(crate) ty_generics: Vec<TokenTree>, }
Quoted 5 lines
rust/macros/helpers.rs pub(crate) struct Generics { · line 110
Quoted 1 line
rust/macros/helpers.rs +1
-0+pub (crate )fn expect_string_field (it: &mut token_stream::IntoIter , expected_name: &str ) ->String {Just to make it obvious what it is looking for:
/// Expect `expected_name: "value",`
Right.
Quoted 8 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 109
Quoted 7 lines
rust/macros/module.rs +2
-0+fn emit_params (&mut self, info: &ModuleInfo ) { +if let Some (params) = &info.params {
Quoted 7 lines
Switching to
let Some(params) = &info.params else { return; };would save an indentation level
I don't mind the indentation level, but I think what you propose with early abort is easier to read. I was actually not aware of this syntax.
Quoted 9 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 115
Quoted 6 lines
rust/macros/module.rs +6
-0+for paramin params { +let ops =param_ops_path (¶m.ptype); + + self.emit_param ("parmtype" , ¶m.name, ¶m.ptype); + self.emit_param ("parm" , ¶m.name, ¶m.description); +(Referring to below) could the template string body be indented another level, so it doesn't hang left of the parent
write!macro?
Sure.
Quoted 3 lines
Also - maybe
let pfx = format!("__{name}_{param_name}") here then use{pfx}` in the template, since that sequence is repeated a lot.
Ok.
Quoted 11 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 119
Quoted 5 lines
rust/macros/module.rs +4
-0+write! ( + self.param_buffer, + " +static mut __ {name}_ {param_name}_value: {param_type} = {param_default};Ah.. we need to migrate from
static muttoUnsafeCellwrappers at some point. Sincemodule!already usesstatic mut, this may need to happen separately - meaning I don't think we need to block on making any change here.
Quoted 7 lines
This would mean adding an
UnsafeSyncCell/RacyCell(just a wrapper aroundUnsafeCellthat always implementsSync), usingUnsafeSyncCell<{param_type}>as the type here, and changing fromstatic mutto juststatic.(I can take a look at doing this change for existing
static mutin the near future).
It seems this discussion is happening on Zulip. Dropping a link to discussion there for people not aware [1].
Quoted 11 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 144
Quoted 8 lines
rust/macros/module.rs +7
-0+/// Newtype to make `bindings::kernel_param` `Sync`. +#[repr(transparent)] + struct __{name}_{param_name}_RacyKernelParam(::kernel::bindings::kernel_param); + +// SAFETY: C kernel handles serializing access to this type. We +// never access from Rust module. + unsafe impl Sync for __{name}_{param_name}_RacyKernelParam {{ }}Could there just be a type for this in the kernel crate rather than creating one as part of the macro?
We can, but I do not think we gain anything? If we move it to the kernel crate, we will have to mark it as pub and it will just clutter the name space.
Quoted 6 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 148
Quoted 4 lines
rust/macros/module.rs +3
-0+#[cfg(not( MODULE ))] + const __{name}_{param_name}_name: *const ::core::ffi::c_char = + b\"{name}.{param_name}\\0\" as *const _ as *const ::core::ffi::c_char;This should work as
c\"{name}.{param_name}\".as_ptr()now
Cool.
Quoted 14 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 152
Quoted 5 lines
rust/macros/module.rs +4
-0+ +#[cfg( MODULE )] + const __{name}_{param_name}_name: *const ::core::ffi::c_char = + b\"{param_name}\\0\" as *const _ as *const ::core::ffi::c_char;Same as above.
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 158
Quoted 5 lines
rust/macros/module.rs +5
-0+ #[link_section = \"__param\"] +#[used] + static __{name}_{param_name}_struct: __{name}_{param_name}_RacyKernelParam = + __{name}_{param_name}_RacyKernelParam(::kernel::bindings::kernel_param {{ + name: __{name}_{param_name}_name,
Quoted 7 lines
You could eliminate the above
__{name}_{param_name}_nameconsts by using:name: if cfg!(MODULE) { c\"{param_name}\\" } else { c\"{name}.{param_name}\\" }.as_ptr(),
Either way is fine for me.
Quoted 7 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 162
Quoted 5 lines
rust/macros/module.rs +4
-0+// SAFETY: `__this_module` is constructed by the kernel at load time +// and will not be freed until the module is unloaded. +#[cfg( MODULE )] + mod_: unsafe {{ &::kernel::bindings::__this_module as *const _ as *mut _ }},Prefer
.cast::<T>().cast_mut()
Changed to addr_of_mut!, but this is also subject to the discussion in [1], const_mut_refs being flaky, right?
Quoted 7 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 166
Quoted 5 lines
rust/macros/module.rs +4
-0+#[cfg(not( MODULE ))] + mod_: ::core::ptr::null_mut(), + ops: &{ops} as *const ::kernel::bindings::kernel_param_ops, + perm: 0, // Will not appear in sysfsFor my knowledge, what would be needed to make sysfs work?
We would set the flags field to allow read and/or write, and we would need to apply proper locking around the parameter storage.
Quoted 13 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 175
Quoted 10 lines
rust/macros/module.rs +9
-0+ level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ +// SAFETY: As this is evaluated in const context, it is +// safe to take a reference to a mut static. + arg:unsafe {{ + ::core::ptr::addr_of_mut!(__ {name}_ {param_name}_value) + }}.cast ::<::core::ffi::c_void >(),A note on this toward the end
Quoted 8 lines
rust/macros/module.rs pub(crate) fn module(ts: TokenStream) -> TokenStream {
Quoted 5 lines
rust/macros/module.rs +3
-0+ }}, + }}); + ",@@ -216,12 +387,14 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {Is a lot of below just some rewrapping and leading
::? It may be good to split off tweaks to the existing code
Yes, absolute type paths were requested in v1. I will split those that are not directly related to this change set.
Quoted 103 lines
Quoted 74 lines
rust/macros/module.rs +15
-9// 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 {{ - kernel::ThisModule ::from_ptr (&kernel::bindings::__this_moduleas *const _ as *mut _ ) +static THIS_MODULE : ::kernel::ThisModule =unsafe {{ + ::kernel::ThisModule ::from_ptr ( + &::kernel::bindings::__this_moduleas *const _ as *mut _ + ) }};#[cfg(not( MODULE ))] -static THIS_MODULE : kernel::ThisModule =unsafe {{ - kernel::ThisModule ::from_ptr (core::ptr::null_mut ()) +static 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. @@ -276,7 +449,8 @@ mod __module_init {{#[doc(hidden)] #[link_section = \"{initcall_section}\"] #[used] - pub static __{name}_initcall: extern \"C\" fn() -> core::ffi::c_int = __{name}_init; + pub static __{name}_initcall: extern \"C\" fn() + -> ::core::ffi::c_int = __{name}_init; #[cfg(not(MODULE))] #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]@@ -291,7 +465,7 @@ mod __module_init {{#[cfg(not( MODULE ))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_init() -> core::ffi::c_int {{ + pub extern \"C\" fn __{name}_init() -> ::core::ffi::c_int {{ // SAFETY: This function is inaccessible to the outside due to the double // module wrapping it. It is called exactly once by the C side via its // placement above in the initcall section.@@ -314,8 +488,8 @@ mod __module_init {{/// # Safety /// /// This function must only be called once. -unsafe fn __init () -> core::ffi::c_int {{ - match <{type_} as kernel::Module>::init(&super::super::THIS_MODULE) {{ +unsafe fn __init () -> ::core::ffi::c_int {{ + match <{type_} as ::kernel::Module>::init(&super::super::THIS_MODULE) {{Ok (m) => {{// SAFETY: No data race, since `__MOD` can only be accessed by this // module and there only `__init` and `__exit` access it. These @@ -346,14 +520,17 @@ unsafe fn __exit() {{ __MOD =None ; }} }} - {modinfo} }} }} + mod module_parameters {{ + {params} + }}", type_ = info.type_, name = info.name, modinfo = modinfo.buffer, +params = modinfo.param_buffer, initcall_section = ".initcall6.init" ) .parse ()samples/rust/rust_minimal.rs +0
-0samples/rust/rust_minimal.rs line 19
Quoted 10 lines
samples/rust/rust_minimal.rs +6
-0@@ -10,6 +10,12 @@ author: "Rust for Linux Contributors", description: "Rust minimal sample", license: "GPL", + params: { + test_parameter: i64 { + default: 1, + description:"This parameter has a default of 1" , + }, + }, }I was going to suggest updating the sample then saw you did that already, thanks :)
scripts/Makefile.build $(obj)/%.lst: $(obj)/%.c FORCE · line 266
Quoted 10 lines
scripts/Makefile.build +1
-1@@ -263,7 +263,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := new_uninit +rust_allowed_features := new_uninit,const_mut_refsWe shouldn't enable
const_mut_refs. It is indeed close to stabilization, but it is still kind of churny right now and we don't want to enable the sharp edges everywhere.
Quoted 7 lines
If the change from
static muttoUnsafeCellthat I mentioned above happens,addr_of_mut!turns into a.get().cast::<...>()takes the place ofaddr_of_mut!and doesn't require this feature (and also isn't unsafe).If you prefer not to make that change, I think
addr_of!(...).cast_mut()might be the best solution.
From the discussion at [1] it sounds to me like static UnsafeCell is the way forward. I can apply that for the static mut instances this patch introduces, and I can wait for module to be patched with that change before resending this. No rush.
Quoted 38 lines
---
Other thought: would a wrapper type make more sense here? Something like this:
``` /* implementation */ struct ModParam<T>(UnsafeCell<T>); // `Parameter` is the existing `ModParameter` (could be // any name). It could be sealed. impl<T: Parameter> ModParam<T> { #[doc(hidden)] // used in the macro fn new(value: T) -> Self { ... } fn get(&self) -> T::Value { ... } fn set(&self, v: T::Value) { ... } } ```With usage:
``` module! { // ... // instantiated as: // `static MY_PARAM: ModParam<i64> = ModParam::new(1);` MY_PARAM: i64 { default: 1, description: "foo", }, } fn foo() { pr_info!("My param is {}", MY_PARAM.get()); } ```
Quoted 3 lines
Advantages I see:
- You bring your own name, rather than being scoped and needing to remember the module name
The scoping is intentional. We did not want to pollute the name space, and pin_init had some issues when names were clashing. I think maybe this was discussed in v1.
Quoted 3 lines
- You can check
ModParamin the docs to see the API, rather than needing to refer to source for the exact signatures ofreadandwrite
Yes, that is a bit annoying. We could also implement read as a trait impl, so the trait would be documented in the kernel crate.
In the original code that this patch descends from, read was generated differently, depending on how the parameter would integrate with sysfs. We might be able to do that with generics withthe ModParam you suggest.
Quoted 1 line
- The interface gets a bit more like a mutex or atomic
We discussed passing self in v1 and dropped it in favor of the associated method accessor. It would make sense with the ModParam approach you suggest though.
Best regards,
Andreas
[1] https://rust-for-linux.zulipchat.com/#narrow/stream/x/topic/x/with/465040682
Trevor Gross
reviewerQuoted 6 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without
sysfssupport.
Also, I think the subject line needs an update ("rust: add module_params macro")
Quoted 10 lines · Trevor Gross
Quoted 6 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without
sysfssupport.Also, I think the subject line needs an update ("rust: add
module_paramsmacro")
Well, it is still what it does. Plus few support types. You think it is not descriptive enough?
BR Andreas
Trevor Gross
reviewerQuoted 11 lines · Andreas Hindborg
Quoted 8 lines · Trevor Gross
Quoted 6 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without
sysfssupport.
Quoted 5 lines
Quoted 2 lines
Also, I think the subject line needs an update ("rust: add
module_paramsmacro")Well, it is still what it does. Plus few support types. You think it is not descriptive enough?
Maybe it should just say 'Add parameter support to the module! macro'? The text module_params doesn't seem to appear in the patch, I was looking for something like module_params!.
- Trevor
Quoted 1 line
BR Andreas
Quoted 15 lines · Trevor Gross
Quoted 14 lines · Andreas Hindborg
Quoted 10 lines · Trevor Gross
Quoted 6 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without
sysfssupport.Also, I think the subject line needs an update ("rust: add
module_paramsmacro")
Quoted 6 lines
Quoted 2 lines
Well, it is still what it does. Plus few support types. You think it is not descriptive enough?
Maybe it should just say 'Add parameter support to the
module!macro'? The textmodule_paramsdoesn't seem to appear in the patch, I was looking for something likemodule_params!.
Right, I'll change it.
BR Andreas