rust: extend `module!` macro with integer parameter support
Subsystems (5)
Andreas Hindborg
reviewerv18 cover rust: extend `module!` macro with integer parameter support
Extend the module! macro with support module parameters. Also add some string to integer parsing functions.
Based on the original module parameter support by Miguel [1], later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].
---
Changes in v18:
- Rebase on Rust atomic patches (tip/master).
- Link to v17: https://lore.kernel.org/r/[email protected]
Changes in v17:
- Fix drop impl of SetOnce so that it works with UnsafeCell<MaybeUninit<_>>.
- Slightly reword safety framework in SetOnce.
- Rebase on atomic series v6.
- Link to v16: https://lore.kernel.org/r/[email protected]
Changes in v16:
- Normalize imports in set_once.rs.
- Use UnsafeCell<MaybeUninit<T>> rather than Opaque<T> for SetOnce.
- Use regular load in drop of SetOnce.
- Update attribution paragraph in cover letter with details from Miguel.
- Remove stray TODO in set_once.rs
- Link to v15: https://lore.kernel.org/r/[email protected]
Changes in v15:
- Rebase on v6.16-rc5.
- Dedent code in module macro for better formatting.
- Rename OnceLock to SetOnce.
- Use "being initialized" rather than "being mutably accessed" when
describing initialization state of OnceLock.
- Use Relaxed ordering when transitioning to exclusive access in
OnceLock.
- Add drop implementation for OnceLock.
- Re-export OnceLock from kernel::sync module.
- Improve indentation of in macro code. Prefix cfg to ::core::cfg in
macro code.
- Use core::ptr::from_ref rather than as casts.
- Hide KernelParam instances behind const _: () blocks.
- Rename ModuleParamAccess::get to ModuleParamAccess::value.
- Rename RacyKernelParam to KernelParam.
- Remove ModuleParam::Value.
- Move copy implementation of OnceLock.
- Update safety comments and invariants of OnceLock.
- Link to v14: https://lore.kernel.org/r/[email protected]
Note: This series now depends on the atomics series [1].
[1] https://lore.kernel.org/all/[email protected]
Changes in v14:
- Remove unnecessary crate:: prefix from module_param::set_param.
- Make FromStrRadix safe again by moving unsafe blocks to macro implementation (thanks Benno).
- Use core::ptr::write in set_param and drop safety requirement regarding initialization.
- Add a TODO to use SyncUnsafeCell for ModuleParamAccess when available.
- Add a NOTE regarding Copy bound on ModuleParam.
- Remove 'static lifetime qualifier from ModuleParam::try_from_param_arg argument.
- Fix a typo in the safety requirements for set_param.
- Remove unused #[macro_export] attribute.
- Remove obsolete documentation for ModuleParam::try_from_param_arg.
- Make RacyKernelParam tuple field private.
- Introduce OnceLock and use that to synchronize population of parameter values.
- Link to v13: https://lore.kernel.org/r/[email protected]
Changes in v13:
- remove absolute path for ffi types.
- Split patch 2 into 4 separate patches.
- Overhaul safety framework for set_param.
- Remove generated docs for kernel_param_ops.
- Move parse_int to separate file.
- Rebase on v6.16-rc1
- Link to v12: https://lore.kernel.org/r/[email protected]
Changes in v12:
- Assign through pointer rather than using core::ptr::replace.
- Prevent a potential use-after-free during module teardown.
- Link to v11: https://lore.kernel.org/r/[email protected]
Changes in v11:
- Apply a few nits from Miguel.
- Link to v10: https://lore.kernel.org/r/[email protected]
Changes in v10:
- Apply fixups from Miguel:
- Add integer type suffixes to assert! in tests.
- Fix links to docs.kernel.org.
- Applyy markdown and intra-doc links where possible.
- Change to /// for mod docs.
- Slightly reword a comment.
- Pluralize "Examples" section name.
- Hide uses in example.
- Removed #[expect] for the rusttest target.
- Link to v9: https://lore.kernel.org/r/[email protected]
Changes in v9:
- Remove UB when parsing the minimum integer values.
- Make FromStr trait unsafe, since wrong implementations can cause UB.
- Drop patches that were applied to rust-next.
- Link to v8: https://lore.kernel.org/r/[email protected]
Changes in v8:
- Change print statement in sample to better communicate parameter name.
- Use imperative mode in commit messages.
- Remove prefix path from EINVAL.
- Change try_from_param_arg to accept &BStr rather than &[u8].
- Parse integers without 128 bit integer types.
- Seal trait FromStrRadix.
- Strengthen safety requirement of set_param.
- Remove comment about Display and PAGE_SIZE.
- Add note describing why ModuleParamAccess is pub.
- Typo and grammar fixes for documentation.
- Update MAINTAINERS with rust module files.
- Link to v7: https://lore.kernel.org/r/[email protected]
Changes in v7:
- Remove dependency on pr_warn_once patches, replace with TODO.
- Rework ParseInt::from_str to avoid allocating.
- Add a comment explaining how we parse "0".
- Change trait bound on Index impl for BStr to match std library approach.
- Link to v6: https://lore.kernel.org/r/[email protected]
Changes in v6:
- Fix a bug that prevented parsing of negative default values for
parameters in the module! macro.
- Fix a bug that prevented parsing zero in strip_radix. Also add a
test case for this.
- Add AsRef<BStr> for [u8] and BStr.
- Use impl AsRef<BStr> as type of prefix in BStr::strip_prefix.
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Fix a typo in a safety comment in set_param.
- Use a match statement in parse_int::strip_radix.
- Add an implementation of Index for BStr.
- Fix a logic inversion bug where parameters would not be parsed.
- Use kernel::ffi::c_char in set_param rather than the one in core.
- Use kernel::c_str! rather than c"..." literal in module macro.
- Rebase on v6.14-rc1.
- Link to v4: https://lore.kernel.org/r/[email protected]
Changes in v4:
- Add module maintainers to Cc list (sorry)
- Add a few missing [doc_links]
- Add panic section to expect_string_field
- Fix a typo in safety requirement of module_params::free
- Change assert! to pr_warn_once! in module_params::set_param
- Remove module_params::get_param and install null pointer instead
- Remove use of the unstable feature sync_unsafe_cell
- Link to v3: https://lore.kernel.org/r/[email protected]
Changes in v3:
- use SyncUnsafeCell rather than static mut and simplify parameter access
- remove Display bound from ModuleParam
- automatically generate documentation for PARAM_OPS_.*
- remove as *const _ as *mut_ phrasing
- inline parameter name in struct instantiation in emit_params
- move RacyKernelParam out of macro template
- use C string literals rather than byte string literals with explicit null
- template out __{name}_{param_name} in emit_param
- indent template in emit_params
- use let-else expression in emit_params to get rid of an indentation level
- document expect_string_field
- move invication of impl_int_module_param to be closer to macro def
- move attributes after docs in make_param_ops
- rename impl_module_param to impl_int_module_param`
- use ty instead of ident in impl_parse_int
- use BStr instead of &str for string manipulation
- move string parsing functions to seperate patch and add examples, fix bugs
- degrade comment about future support from doc comment to regular comment
- remove std lib path from Sized marker
- update documentation for trait ModuleParam
- Link to v2: https://lore.kernel.org/all/[email protected]/
Changes in v2:
- 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.
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/
---
Andreas Hindborg (7):
rust: sync: add SetOnce
rust: str: add radix prefixed integer parsing functions
rust: introduce module_param module
rust: module: use a reference in macros::module::module
rust: module: update the module macro with module parameter support
rust: samples: add a module parameter to the rust_minimal sample
modules: add rust modules files to MAINTAINERS
MAINTAINERS | 2 + rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 181 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++++ rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 ++++++++++++++++++++++++++++ rust/macros/helpers.rs | 25 ++++++ rust/macros/lib.rs | 31 +++++++ rust/macros/module.rs | 194 +++++++++++++++++++++++++++++++++++++++---- samples/rust/rust_minimal.rs | 10 +++ 11 files changed, 703 insertions(+), 18 deletions(-)
---
base-commit: 103265a1a936cfe910c9ac0f0ab153f7dac818ba
change-id: 20241211-module-params-v3-ae7e5c8d8b5a
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
reviewerPATCH v18 1/7 rust: sync: add `SetOnce`
Introduce the SetOnce type, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.
--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+)
rust/kernel/sync.rs +2 -0
@@ -20,6 +20,7 @@pub mod poll;pub mod rcu;mod refcount; +mod set_once;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use completion::Completion ;
@@ -29,6 +30,7 @@pub use lock::spinlock::{new_spinlock,SpinLock ,SpinLockGuard };pub use locked_by::LockedBy ;pub use refcount::Refcount ; +pub use set_once::SetOnce ;/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`. #[repr(transparent)]
rust/kernel/sync/set_once.rs new file +125 -0
125 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v18 2/7 rust: str: add radix prefixed integer parsing functions
In reply to Andreas HindborgAdd the trait ParseInt for parsing string representations of integers where the string representations are optionally prefixed by a radix specifier. Implement the trait for the primitive integer types.
--- rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+)
rust/kernel/str.rs +2 -0
@@ -8,6 +8,8 @@use crate ::prelude::*; +pub mod parse_int; +/// Byte string without UTF-8 validity guarantee. #[repr(transparent)] pub struct BStr ([u8 ]);
rust/kernel/str/parse_int.rs new file +148 -0
148 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v18 3/7 rust: introduce module_param module
In reply to Andreas HindborgAdd types and traits for interfacing the C moduleparam API.
--- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 181 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -98,6 +98,7 @@pub mod list;pub mod miscdevice;pub mod mm; +pub mod module_param;#[cfg( CONFIG_NET )] pub mod net;pub mod of;
rust/kernel/module_param.rs new file +181 -0
181 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v18 4/7 rust: module: use a reference in macros::module::module
In reply to Andreas HindborgWhen we add parameter support to the module macro, we want to be able to pass a reference to ModuleInfo to a helper function. That is not possible when we move out of the local modinfo. So change the function to access the local via reference rather than value.
--- rust/macros/module.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
rust/macros/module.rs +8 -8
@@ -176,23 +176,23 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {// Rust does not allow hyphens in identifiers, use underscore instead. let ident = info.name.replace ('-' ,"_" );let mut modinfo =ModInfoBuilder ::new (ident.as_ref ()); -if let Some (authors) = info.authors { +if let Some (authors) = &info.authors {for authorin authors { - modinfo.emit ("author" , &author); + modinfo.emit ("author" , author); } } -if let Some (description) = info.description { - modinfo.emit ("description" , &description); +if let Some (description) = &info.description { + modinfo.emit ("description" , description); } modinfo.emit ("license" , &info.license); -if let Some (aliases) = info.alias { +if let Some (aliases) = &info.alias {for aliasin aliases { - modinfo.emit ("alias" , &alias); + modinfo.emit ("alias" , alias); } } -if let Some (firmware) = info.firmware { +if let Some (firmware) = &info.firmware {for fwin firmware { - modinfo.emit ("firmware" , &fw); + modinfo.emit ("firmware" , fw); } }
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v18 5/7 rust: module: update the module macro with module parameter support
In reply to Andreas HindborgAllow module parameters to be declared in the rust module! macro.
--- rust/macros/helpers.rs | 25 +++++++ rust/macros/lib.rs | 31 +++++++++ rust/macros/module.rs | 178 ++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 224 insertions(+), 10 deletions(-)
rust/macros/helpers.rs +25 -0
@@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { } } +pub (crate )fn try_sign (it: &mut token_stream::IntoIter ) ->Option <char > { +let peek = it.clone ().next (); +match peek { +Some (TokenTree ::Punct (punct))if punct.as_char () =='-' => { +let _ = it.next (); +Some (punct.as_char ()) + } + _ =>None , + } +} +pub (crate )fn try_literal (it: &mut token_stream::IntoIter ) ->Option <String > {if let Some (TokenTree ::Literal (literal)) = it.next () {Some (literal.to_string ())
@@ -103,3 +114,17 @@ pub(crate) fn file() -> String { proc_macro::Span ::call_site ().file () } } + +/// Parse a token stream of the form `expected_name: "value",` and return the +/// string in the position of "value". +/// +/// # Panics +/// +/// - On parse error. +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 +}
rust/macros/lib.rs +31 -0
@@ -28,6 +28,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
@@ -44,6 +68,12 @@/// 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(i32);
@@ -52,6 +82,7 @@/// fn init(_module: &'static ThisModule) -> Result<Self> { /// let foo: i32 = 42; /// pr_info!("I contain: {}\n", foo); +/// pr_info!("i32 param is: {}\n", module_parameters::my_parameter.read()); /// Ok(Self(foo)) /// } /// }
rust/macros/module.rs +168 -10
252 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v18 6/7 rust: samples: add a module parameter to the rust_minimal sample
In reply to Andreas HindborgShowcase the rust module parameter support by adding a module parameter to the rust_minimal sample.
--- samples/rust/rust_minimal.rs | 10 ++++++++++ 1 file changed, 10 insertions(+)
samples/rust/rust_minimal.rs +10 -0
@@ -10,6 +10,12 @@ authors: ["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! ( +"test_parameter: {}\n" , + *module_parameters::test_parameter.value () + );let mut numbers =KVec ::new (); numbers.push (72 ,GFP_KERNEL )?;
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v18 7/7 modules: add rust modules files to MAINTAINERS
In reply to Andreas HindborgThe module subsystem people agreed to maintain rust support for modules [1]. Thus, add entries for relevant files to modules entry in MAINTAINERS.
--- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+)
MAINTAINERS +2 -0
@@ -17136,6 +17136,8 @@ F: include/linux/module*.h F: kernel/module/ F: lib/test_kmod.c F: lib/tests/module/ +F: rust/kernel/module_param.rs +F: rust/macros/module.rs F: scripts/module* F: tools/testing/selftests/kmod/ F: tools/testing/selftests/module/
Signature · 1 line
2.47.2
Quoted 7 lines · Andreas Hindborg
Extend the
module!macro with support module parameters. Also add some string to integer parsing functions.Based on the original module parameter support by Miguel [1], later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].
Quoted 5 lines
I tested this series with rust_minimal module. They LGTM,
The patches did not apply cleanly to v6.18-rc3, at least not when using b4. However, when applying them to the base commit and then rebasing onto v6.18-rc3, I didn't see any conflicts.
I've created a temporary branch with this rebase here:
https://git.kernel.org/pub/scm/linux/kernel/git/modules/linux.git/log/?h=rebase/[email protected]
Can you take a look when you can? I'll merge this shortly after checking with Uwe, as there are some minor conflicts with his tree.
+ Uwe
These are the conflicts I see when merging the patch series from Michal [1] (Introduce import_ns support for Rust). I believe these are trivial things that we will get notified from linux-next merging. But let me know what you think as you have requested in that thread.
[1] Link: https://lore.kernel.org/all/[email protected]/
...
Applying: rust: macros: Add support for 'imports_ns' to module! Patch failed at 0008 rust: macros: Add support for 'imports_ns' to module!
error: patch failed: rust/macros/module.rs:98
error: rust/macros/module.rs: patch does not apply
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
git am --show-current-patch=diff
--- rust/macros/module.rs | 8 ++++++++ 1 file changed, 8 insertions(+) --- rust/macros/module.rs | 8 ++++++++ 1 file changed, 8 insertions(+)
rust/macros/module.rs +8 -0
@@ -98,6 +98,7 @@ struct ModuleInfo { description: Option<String>, alias: Option<Vec<String>>, firmware: Option<Vec<String>>, + imports_ns: Option<Vec<String>>, }impl ModuleInfo {
@@ -112,6 +113,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "license", "alias", "firmware", + "imports_ns", ];const REQUIRED_KEYS : &[&str ] = &["type" ,"name" ,"license" ];let mut seen_keys =Vec ::new ();
@@ -137,6 +139,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "license" => info.license = expect_string_ascii(it), "alias" => info.alias = Some(expect_string_array(it)), "firmware" => info.firmware = Some(expect_string_array(it)), + "imports_ns" => info.imports_ns = Some(expect_string_array(it)), _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."), }
@@ -195,6 +198,11 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { modinfo.emit ("firmware" , &fw); } } +if let Some (imports) = info.imports_ns { +for nsin imports { + modinfo.emit ("import_ns" , &ns); + } + }// Built-in modules also export the `file` modinfo string. let file =
Hello Daniel,
[Adding Stephen and linux-next to Cc]
Quoted 14 lines · Daniel Gomez
Quoted 7 lines · Andreas Hindborg
Extend the
module!macro with support module parameters. Also add some string to integer parsing functions.Based on the original module parameter support by Miguel [1], later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].
Quoted 5 lines
Quoted 7 lines
I tested this series with
rust_minimalmodule. They LGTM,Tested-by Daniel Gomez <[email protected]>The patches did not apply cleanly to v6.18-rc3, at least not when using b4. However, when applying them to the base commit and then rebasing onto v6.18-rc3, I didn't see any conflicts.
I don't know how you use b4, but
git checkout v6.18-rc3 b4 am -3 [email protected] git am -3 ./v18_20250924_a_hindborg_rust_extend_module_macro_with_integer_parameter_support.mbx
works fine on my end. Using -3 should have the same effect as applying the series on top of the original base and rebase it.
git fetch https://git.kernel.org/pub/scm/linux/kernel/git/modules/linux.git rebase/[email protected] git range-diff FETCH_HEAD...HEAD
confirms that.
Quoted 7 lines
I've created a temporary branch with this rebase here:
https://git.kernel.org/pub/scm/linux/kernel/git/modules/linux.git/log/?h=rebase/[email protected]
Can you take a look when you can? I'll merge this shortly after checking with Uwe, as there are some minor conflicts with his tree.
Quoted 8 lines
+ Uwe
These are the conflicts I see when merging the patch series from Michal [1] (Introduce
import_nssupport for Rust). I believe these are trivial things that we will get notified from linux-next merging. But let me know what you think as you have requested in that thread.
Yeah, I expect that Stephen will highlight the conflicts, but I prefer to not be surprised by that and consider linux-next more a fallback security net that I don't want to use. I like it to be the other way round and tell Stephen about conflicts to expect :-)
Quoted 11 lines
...
Applying: rust: macros: Add support for 'imports_ns' to module! Patch failed at 0008 rust: macros: Add support for 'imports_ns' to module!
error: patch failed:rust/macros/module.rs:98
error:rust/macros/module.rs: patch does not apply
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Quoted 1 line
git am --show-current-patch=diff
That command shows the patch to apply, but not the conflict, let alone your resolution.
Quoted 12 lines
--- rust/macros/module.rs | 8 ++++++++ 1 file changed, 8 insertions(+) --- rust/macros/module.rs | 8 ++++++++ 1 file changed, 8 insertions(+)rust/macros/module.rs +0
-0
rust/macros/module.rs struct ModuleInfo { · line 102
Quoted 5 lines
rust/macros/module.rs +1
-0@@ -98,6 +98,7 @@ struct ModuleInfo { description: Option<String>, alias: Option<Vec<String>>, firmware: Option<Vec<String>>, + imports_ns: Option<Vec<String>>, }
So here the addition of params is missing.
Quoted 1 line
[...]
When I merge your branch mentioned above with my pwm/for-next and resolve the merge conflicts, the resolution looks as follows. The only non-trivial thing is that
if let Some(imports) = info.imports_ns {now needs a & for info.
Best regards
Uwe
rust/macros/module.rs +0 -0
@@@ -205,50 -98,7 +205,51 @@@ struct ModuleInfo description: Option<String>, alias: Option<Vec<String>>, firmware: Option<Vec<String>>, + imports_ns: Option<Vec<String>>, + params: Option<Vec<Parameter>>, +} + +#[derive(Debug)] +struct Parameter { + name: String, + ptype: String, + default: String, + description: String, +} + +fn expect_params(it: &mut token_stream::IntoIter) -> Vec<Parameter> { + let params = expect_group(it); +assert_eq! (params.delimiter (),Delimiter ::Brace ); + let mut it = params.stream().into_iter(); + let mut parsed = Vec::new(); + +loop { + let param_name = match it.next() { + Some(TokenTree::Ident(ident)) => ident.to_string(), + Some(_) => panic!("Expected Ident or end"), + None => break, + }; + +assert_eq! (expect_punct (&mut it),':' ); + let param_type = expect_ident(&mut it); + let group = expect_group(&mut it); + assert_eq!(group.delimiter(), Delimiter::Brace); +assert_eq! (expect_punct (&mut it),',' ); + + let mut param_it = group.stream().into_iter(); + let param_default = expect_param_default(&mut param_it); + let param_description = expect_string_field(&mut param_it, "description"); +expect_end (&mut param_it); + + parsed.push(Parameter { + name: param_name, + ptype: param_type, + default: param_default, + description: param_description, + }) + } + + parsed } impl ModuleInfo { "license", "alias", "firmware", + "imports_ns", + "params", ];const REQUIRED_KEYS : &[&str ] = &["type" ,"name" ,"license" ];let mut seen_keys =Vec ::new (); "license" => info.license = expect_string_ascii(it), "alias" => info.alias = Some(expect_string_array(it)), "firmware" => info.firmware = Some(expect_string_array(it)), + "imports_ns" => info.imports_ns = Some(expect_string_array(it)), + "params" => info.params = Some(expect_params(it)), _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."), }// Rust does not allow hyphens in identifiers, use underscore instead. let ident = info.name.replace('-', "_");let mut modinfo =ModInfoBuilder ::new (ident.as_ref ()); - if let Some(authors) = info.authors { + if let Some(authors) = &info.authors { for author in authors { - modinfo.emit("author", &author); + modinfo.emit("author", author); } } - if let Some(description) = info.description { - modinfo.emit("description", &description); + if let Some(description) = &info.description { + modinfo.emit("description", description); } modinfo.emit("license", &info.license); - if let Some(aliases) = info.alias { + if let Some(aliases) = &info.alias { for alias in aliases { - modinfo.emit("alias", &alias); + modinfo.emit("alias", alias); } } - if let Some(firmware) = info.firmware { + if let Some(firmware) = &info.firmware { for fw in firmware { - modinfo.emit("firmware", &fw); + modinfo.emit("firmware", fw); } } - if let Some(imports) = info.imports_ns { ++ if let Some(imports) = &info.imports_ns { + for ns in imports { + modinfo.emit("import_ns", &ns); + } + } // Built-in modules also export the `file` modinfo string. let file =
Daniel Gomez
maintainerQuoted 27 lines · Uwe Kleine-König
Hello Daniel,
[Adding Stephen and linux-next to Cc]
Quoted 14 lines · Daniel Gomez
Quoted 7 lines · Andreas Hindborg
Extend the
module!macro with support module parameters. Also add some string to integer parsing functions.Based on the original module parameter support by Miguel [1], later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].
Quoted 5 lines
Quoted 7 lines
I tested this series with
rust_minimalmodule. They LGTM,Tested-by Daniel Gomez <[email protected]>The patches did not apply cleanly to v6.18-rc3, at least not when using b4. However, when applying them to the base commit and then rebasing onto v6.18-rc3, I didn't see any conflicts.
Quoted 8 lines
I don't know how you use b4, but
git checkout v6.18-rc3 b4 am -3 [email protected] git am -3 ./v18_20250924_a_hindborg_rust_extend_module_macro_with_integer_parameter_support.mbxworks fine on my end. Using
-3should have the same effect as applying the series on top of the original base and rebase it.
Right, that's what I did but manually. I didn't know about that argument :).
Quoted 20 lines
git fetch https://git.kernel.org/pub/scm/linux/kernel/git/modules/linux.git rebase/[email protected] git range-diff FETCH_HEAD...HEADconfirms that.
Quoted 14 lines
I've created a temporary branch with this rebase here:
https://git.kernel.org/pub/scm/linux/kernel/git/modules/linux.git/log/?h=rebase/[email protected]
Can you take a look when you can? I'll merge this shortly after checking with Uwe, as there are some minor conflicts with his tree.
+ Uwe
These are the conflicts I see when merging the patch series from Michal [1] (Introduce
import_nssupport for Rust). I believe these are trivial things that we will get notified from linux-next merging. But let me know what you think as you have requested in that thread.
Quoted 6 lines
Quoted 1 line
Yeah, I expect that Stephen will highlight the conflicts, but I prefer to not be surprised by that and consider linux-next more a fallback security net that I don't want to use. I like it to be the other way round and tell Stephen about conflicts to expect :-)
Please Stephen, check the proposed changes below. I plan to merge this series in modules' tree and it will conflict with Uwe's tree on rust/macros/module.rs file.
Quoted 39 lines
Quoted 12 lines
...
Applying: rust: macros: Add support for 'imports_ns' to module! Patch failed at 0008 rust: macros: Add support for 'imports_ns' to module!
error: patch failed:rust/macros/module.rs:98
error:rust/macros/module.rs: patch does not apply
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"Quoted 1 line
git am --show-current-patch=diff
That command shows the patch to apply, but not the conflict, let alone your resolution.
Quoted 12 lines
--- rust/macros/module.rs | 8 ++++++++ 1 file changed, 8 insertions(+) --- rust/macros/module.rs | 8 ++++++++ 1 file changed, 8 insertions(+)rust/macros/module.rs +0
-0rust/macros/module.rs struct ModuleInfo { · line 102
Quoted 5 lines
rust/macros/module.rs +1
-0@@ -98,6 +98,7 @@ struct ModuleInfo { description: Option<String>, alias: Option<Vec<String>>, firmware: Option<Vec<String>>, + imports_ns: Option<Vec<String>>, }So here the addition of
paramsis missing.Quoted 1 line
[...]
Quoted 7 lines
When I merge your branch mentioned above with my pwm/for-next and resolve the merge conflicts, the resolution looks as follows. The only non-trivial thing is that
if let Some(imports) = info.imports_ns {now needs a & for
info.
Correct.
In case it's necessary, I've merged your changes into the modules's -next branch and attach the diff for you and Stephen. Not sure which order trees are taken/merged, though.
Quoted 108 lines
Best regards
Uwerust/macros/module.rs +3
-0@@@ -205,50 -98,7 +205,51 @@@ struct ModuleInfo description: Option<String>, alias: Option<Vec<String>>, firmware: Option<Vec<String>>, + imports_ns: Option<Vec<String>>, + params: Option<Vec<Parameter>>, +} + +#[derive(Debug)] +struct Parameter { + name: String, + ptype: String, + default: String, + description: String, +} + +fn expect_params(it: &mut token_stream::IntoIter) -> Vec<Parameter> { + let params = expect_group(it); +assert_eq! (params.delimiter (),Delimiter ::Brace ); + let mut it = params.stream().into_iter(); + let mut parsed = Vec::new(); + +loop { + let param_name = match it.next() { + Some(TokenTree::Ident(ident)) => ident.to_string(), + Some(_) => panic!("Expected Ident or end"), + None => break, + }; + +assert_eq! (expect_punct (&mut it),':' ); + let param_type = expect_ident(&mut it); + let group = expect_group(&mut it); + assert_eq!(group.delimiter(), Delimiter::Brace); +assert_eq! (expect_punct (&mut it),',' ); + + let mut param_it = group.stream().into_iter(); + let param_default = expect_param_default(&mut param_it); + let param_description = expect_string_field(&mut param_it, "description"); +expect_end (&mut param_it); + + parsed.push(Parameter { + name: param_name, + ptype: param_type, + default: param_default, + description: param_description, + }) + } + + parsed } impl ModuleInfo {@@@ -263,7 -113,7 +264,8 @@@ "license", "alias", "firmware", + "imports_ns", + "params", ];const REQUIRED_KEYS : &[&str ] = &["type" ,"name" ,"license" ];let mut seen_keys =Vec ::new ();@@@ -289,7 -139,7 +291,8 @@@ "license" => info.license = expect_string_ascii(it), "alias" => info.alias = Some(expect_string_array(it)), "firmware" => info.firmware = Some(expect_string_array(it)), + "imports_ns" => info.imports_ns = Some(expect_string_array(it)), + "params" => info.params = Some(expect_params(it)), _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."), }@@@ -329,25 -179,30 +332,30 @@@ pub(crate) fn module(ts: TokenStream) -// Rust does not allow hyphens in identifiers, use underscore instead. let ident = info.name.replace ('-' ,"_" );let mut modinfo =ModInfoBuilder ::new (ident.as_ref ()); - if let Some(authors) = info.authors { + if let Some(authors) = &info.authors { for author in authors { - modinfo.emit("author", &author); + modinfo.emit("author", author); } } - if let Some(description) = info.description { - modinfo.emit("description", &description); + if let Some(description) = &info.description { + modinfo.emit("description", description); } modinfo.emit("license", &info.license); - if let Some(aliases) = info.alias { + if let Some(aliases) = &info.alias { for alias in aliases { - modinfo.emit("alias", &alias); + modinfo.emit("alias", alias); } } - if let Some(firmware) = info.firmware { + if let Some(firmware) = &info.firmware { for fw in firmware { - modinfo.emit("firmware", &fw); + modinfo.emit("firmware", fw); }
rust/macros/module.rs
Quoted 10 lines
rust/macros/module.rs +5
-0} -if let Some (imports) = info.imports_ns { ++ if let Some(imports) = &info.imports_ns { +for nsin imports { + modinfo.emit ("import_ns" , &ns); + } + }// Built-in modules also export the `file` modinfo string. let file =
The resolution looks good to me.
As I applied Michal's patch on top of Andreas changes, it looks like this on my side:
rust/macros/module.rs +8 -0
@@ -206,6 +206,7 @@ struct ModuleInfo { alias: Option<Vec<String>>, firmware: Option<Vec<String>>, params: Option<Vec<Parameter>>, + imports_ns: Option<Vec<String>>, }#[derive( Debug )]
@@ -264,6 +265,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "alias", "firmware", "params", + "imports_ns", ];const REQUIRED_KEYS : &[&str ] = &["type" ,"name" ,"license" ];let mut seen_keys =Vec ::new ();
@@ -290,6 +292,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "alias" => info.alias = Some(expect_string_array(it)), "firmware" => info.firmware = Some(expect_string_array(it)), "params" => info.params = Some(expect_params(it)), + "imports_ns" => info.imports_ns = Some(expect_string_array(it)), _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."), }
@@ -348,6 +351,11 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { modinfo.emit ("firmware" , fw); } } +if let Some (imports) = &info.imports_ns { +for nsin imports { + modinfo.emit ("import_ns" , &ns); + } + }// Built-in modules also export the `file` modinfo string. let file =
Quoted 8 lines · Andreas Hindborg
Extend the
module!macro with support module parameters. Also add some string to integer parsing functions.Based on the original module parameter support by Miguel [1], later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].
[...]
Applied, thanks!
[1/7] rust: sync: add SetOnce
commit: 821fe7bf16c57d690f4f92997f4e51abb93e0347
[2/7] rust: str: add radix prefixed integer parsing functions
commit: 51d9ee90ea9060be240830eb28f5f117ad00318c
[3/7] rust: introduce module_param module
commit: 0b08fc292842a13aa496413b48c1efb83573b8c6
[4/7] rust: module: use a reference in macros::module::module
commit: 3809d7a89fe550bf4065c04adff6dac610daddad
[5/7] rust: module: update the module macro with module parameter support
commit: 0b24f9740f26ac7ad91ac0f4de27717c14de91bd
[6/7] rust: samples: add a module parameter to the rust_minimal sample
commit: e119c2fe8c78632188f6cdeae620951a7032855a
[7/7] modules: add rust modules files to MAINTAINERS
commit: ee3b8134b2bae848e03e56c090ceca4ae76cee06Best regards,
Signature · 1 line
Daniel Gomez <[email protected]>