Skip to contentSkip to conversation

rust: extend `module!` macro with integer parameter support

PATCH Superseded Andreas Hindborg 3 participants 15 messages May 6, 2025 – Jun 12, 2025

Subsystems (3)

v12 of 18 Superseded Latest is v18 →

lore
Share & tools
lore
author reviewer
#1 lore raw

PATCH v12 1/3 rust: str: add radix prefixed integer parsing functions

In reply to Andreas Hindborg

Add 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 | 172 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 171 insertions(+), 1 deletion(-)
rust/kernel/str.rs +171 -1
index 878111cb77bc..174e70397305 100644
@@ -573,7 +573,6 @@ macro_rules! c_str {
 }
 
 #[cfg(test)]
-#[expect(clippy::items_after_test_module)]
 mod tests {
     use super::*;
 
@@ -946,3 +945,174 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+/// Integer parsing functions for parsing signed and unsigned integers
+/// potentially prefixed with `0x`, `0o`, or `0b`.
+pub mod parse_int {
+    use crate::prelude::*;
+    use crate::str::BStr;
+    use core::ops::Deref;
+
+    // Make `FromStrRadix` a public type with a private name. This seals
+    // `ParseInt`, that is, prevents downstream users from implementing the
+    // trait.
+    mod private {
+        use crate::str::BStr;
+
+        /// Trait that allows parsing a [`&BStr`] to an integer with a radix.
+        ///
+        /// # Safety
+        ///
+        /// The member functions of this trait must be implemented according to
+        /// their documentation.
+        ///
+        /// [`&BStr`]: kernel::str::BStr
+        // This is required because the `from_str_radix` function on the primitive
+        // integer types is not part of any trait.
+        pub unsafe trait FromStrRadix: Sized {
+            /// The minimum value this integer type can assume.
+            const MIN: Self;
+
+            /// Parse `src` to [`Self`] using radix `radix`.
+            fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error>;
+
+            /// Return the absolute value of [`Self::MIN`].
+            fn abs_min() -> u64;
+
+            /// Perform bitwise 2's complement on `self`.
+            ///
+            /// Note: This function does not make sense for unsigned integers.
+            fn complement(self) -> Self;
+        }
+    }
+
+    /// Extract the radix from an integer literal optionally prefixed with
+    /// one of `0x`, `0X`, `0o`, `0O`, `0b`, `0B`, `0`.
+    fn strip_radix(src: &BStr) -> (u32, &BStr) {
+        match src.deref() {
+            [b'0', b'x' | b'X', rest @ ..] => (16, rest.as_ref()),
+            [b'0', b'o' | b'O', rest @ ..] => (8, rest.as_ref()),
+            [b'0', b'b' | b'B', rest @ ..] => (2, rest.as_ref()),
+            // NOTE: We are including the leading zero to be able to parse
+            // literal `0` here. If we removed it as a radix prefix, we would
+            // not be able to parse `0`.
+            [b'0', ..] => (8, src),
+            _ => (10, src),
+        }
+    }
+
+    /// Trait for parsing string representations of 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://docs.kernel.org/core-api/kernel-api.html#c.kstrtol
+    /// [`kstrtoul()`]: https://docs.kernel.org/core-api/kernel-api.html#c.kstrtoul
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::str::parse_int::ParseInt;
+    /// # use kernel::b_str;
+    ///
+    /// assert_eq!(Ok(0u8), u8::from_str(b_str!("0")));
+    ///
+    /// assert_eq!(Ok(0xa2u8), u8::from_str(b_str!("0xa2")));
+    /// assert_eq!(Ok(-0xa2i32), i32::from_str(b_str!("-0xa2")));
+    ///
+    /// assert_eq!(Ok(-0o57i8), i8::from_str(b_str!("-0o57")));
+    /// assert_eq!(Ok(0o57i8), i8::from_str(b_str!("057")));
+    ///
+    /// assert_eq!(Ok(0b1001i16), i16::from_str(b_str!("0b1001")));
+    /// assert_eq!(Ok(-0b1001i16), i16::from_str(b_str!("-0b1001")));
+    ///
+    /// assert_eq!(Ok(127i8), i8::from_str(b_str!("127")));
+    /// assert!(i8::from_str(b_str!("128")).is_err());
+    /// assert_eq!(Ok(-128i8), i8::from_str(b_str!("-128")));
+    /// assert!(i8::from_str(b_str!("-129")).is_err());
+    /// assert_eq!(Ok(255u8), u8::from_str(b_str!("255")));
+    /// assert!(u8::from_str(b_str!("256")).is_err());
+    /// ```
+    pub trait ParseInt: private::FromStrRadix + TryFrom<u64> {
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.deref() {
+                [b'-', rest @ ..] => {
+                    let (radix, digits) = strip_radix(rest.as_ref());
+                    // 2's complement values range from -2^(b-1) to 2^(b-1)-1.
+                    // So if we want to parse negative numbers as positive and
+                    // later multiply by -1, we have to parse into a larger
+                    // integer. We choose `u64` as sufficiently large.
+                    //
+                    // NOTE: 128 bit integers are not available on all
+                    // platforms, hence the choice of 64 bits.
+                    let val = u64::from_str_radix(
+                        core::str::from_utf8(digits).map_err(|_| EINVAL)?,
+                        radix,
+                    )
+                    .map_err(|_| EINVAL)?;
+
+                    if val > Self::abs_min() {
+                        return Err(EINVAL);
+                    }
+
+                    if val == Self::abs_min() {
+                        return Ok(Self::MIN);
+                    }
+
+                    // SAFETY: We checked that `val` will fit in `Self` above.
+                    let val: Self = unsafe { val.try_into().unwrap_unchecked() };
+
+                    Ok(val.complement())
+                }
+                _ => {
+                    let (radix, digits) = strip_radix(src);
+                    Self::from_str_radix(digits, radix).map_err(|_| EINVAL)
+                }
+            }
+        }
+    }
+
+    macro_rules! impl_parse_int {
+        ($ty:ty) => {
+            // SAFETY: We implement the trait according to the documentation.
+            unsafe impl private::FromStrRadix for $ty {
+                const MIN: Self = <$ty>::MIN;
+
+                fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error> {
+                    <$ty>::from_str_radix(core::str::from_utf8(src).map_err(|_| EINVAL)?, radix)
+                        .map_err(|_| EINVAL)
+                }
+
+                fn abs_min() -> u64 {
+                    #[allow(unused_comparisons)]
+                    if Self::MIN < 0 {
+                        1u64 << (Self::BITS - 1)
+                    } else {
+                        0
+                    }
+                }
+
+                fn complement(self) -> Self {
+                    (!self).wrapping_add((1 as $ty))
+                }
+            }
+
+            impl ParseInt for $ty {}
+        };
+    }
+
+    impl_parse_int!(i8);
+    impl_parse_int!(u8);
+    impl_parse_int!(i16);
+    impl_parse_int!(u16);
+    impl_parse_int!(i32);
+    impl_parse_int!(u32);
+    impl_parse_int!(i64);
+    impl_parse_int!(u64);
+    impl_parse_int!(isize);
+    impl_parse_int!(usize);
+}
Signature · 1 line
2.47.2
author reviewer
#14 lore raw

PATCH v12 3/3 modules: add rust modules files to MAINTAINERS

In reply to Andreas Hindborg

The 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
index 3cbf9ac0d83f..d283874843a0 100644
@@ -16395,6 +16395,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
author reviewer
#5 lore raw

PATCH v12 2/3 rust: add parameter support to the `module!` macro

In reply to Andreas Hindborg

Add support for module parameters to the module! macro. Implement read only support for integer types without sysfs support.

---
 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 204 +++++++++++++++++++++++++++++++++++++++++++
 rust/macros/helpers.rs       |  25 ++++++
 rust/macros/lib.rs           |  31 +++++++
 rust/macros/module.rs        | 195 ++++++++++++++++++++++++++++++++++++-----
 samples/rust/rust_minimal.rs |  10 +++
 6 files changed, 446 insertions(+), 20 deletions(-)
rust/kernel/lib.rs +1 -0
index de07aadd1ff5..9afb7eae9183 100644
@@ -61,6 +61,7 @@
 pub mod kunit;
 pub mod list;
 pub mod miscdevice;
+pub mod module_param;
 #[cfg(CONFIG_NET)]
 pub mod net;
 pub mod of;
rust/kernel/module_param.rs new file +204 -0

204 lines not on this page · raw message

rust/macros/helpers.rs +25 -0
index a3ee27e29a6f..16d300ad3d3b 100644
@@ -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())
@@ -86,3 +97,17 @@ pub(crate) fn function_name(input: TokenStream) -> Option<Ident> {
     }
     None
 }
+
+/// 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
index 9acaa68c974e..7a3a54fcf88e 100644
@@ -23,6 +23,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
@@ -39,6 +63,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);
@@ -47,6 +77,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 +175 -20

284 lines not on this page · raw message

samples/rust/rust_minimal.rs +10 -0
index 1fc7a1be6b6d..c04cc07b3249 100644
@@ -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: &'static ThisModule) -> 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.get()
+        );
 
         let mut numbers = KVec::new();
         numbers.push(72, GFP_KERNEL)?;
Signature · 1 line
2.47.2

Andreas Hindborg

author reviewer
#0 lore raw

v12 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 and updates BStr with a method to strip a string prefix.

Based on code by Adam Bratschi-Kaye lifted from the original rust branch [1].

---
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 (3):
rust: str: add radix prefixed integer parsing functions
rust: add parameter support to the module! macro
modules: add rust modules files to MAINTAINERS

 MAINTAINERS                  |   2 +
 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 204 +++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/str.rs           | 172 +++++++++++++++++++++++++++++++++++-
 rust/macros/helpers.rs       |  25 ++++++
 rust/macros/lib.rs           |  31 +++++++
 rust/macros/module.rs        | 195 ++++++++++++++++++++++++++++++++++++-----
 samples/rust/rust_minimal.rs |  10 +++
 8 files changed, 619 insertions(+), 21 deletions(-)

---
base-commit: b4432656b36e5cc1d50a1f2dc15357543add530e
change-id: 20241211-module-params-v3-ae7e5c8d8b5a

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
reviewer
#2 lore raw

Re: [PATCH v12 1/3] rust: str: add radix prefixed integer parsing functions

In reply to Andreas Hindborg
Quoted 13 lines · Andreas Hindborg
rust/kernel/str.rs +0 -1
index 878111cb77bc..174e70397305 100644
@@ -573,7 +573,6 @@ macro_rules! c_str {
 }
 
 #[cfg(test)]
-#[expect(clippy::items_after_test_module)]
 mod tests {
     use super::*;
 

rust/kernel/str.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 951

Quoted 7 lines
rust/kernel/str.rs +4 -0
@@ -946,3 +945,174 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+/// Integer parsing functions for parsing signed and unsigned integers
+/// potentially prefixed with `0x`, `0o`, or `0b`.
+pub mod parse_int {

Why not make this its own file? It's 172 lines long already.

Quoted 21 lines
rust/kernel/str.rs +21 -0
+    pub trait ParseInt: private::FromStrRadix + TryFrom<u64> {
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.deref() {
+                [b'-', rest @ ..] => {
+                    let (radix, digits) = strip_radix(rest.as_ref());
+                    // 2's complement values range from -2^(b-1) to 2^(b-1)-1.
+                    // So if we want to parse negative numbers as positive and
+                    // later multiply by -1, we have to parse into a larger
+                    // integer. We choose `u64` as sufficiently large.
+                    //
+                    // NOTE: 128 bit integers are not available on all
+                    // platforms, hence the choice of 64 bits.
+                    let val = u64::from_str_radix(
+                        core::str::from_utf8(digits).map_err(|_| EINVAL)?,
+                        radix,
+                    )
+                    .map_err(|_| EINVAL)?;
+
+                    if val > Self::abs_min() {
+                        return Err(EINVAL);

rust/kernel/str.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 1069

Quoted 10 lines
rust/kernel/str.rs +10 -0
+                    }
+
+                    if val == Self::abs_min() {
+                        return Ok(Self::MIN);
+                    }
+
+                    // SAFETY: We checked that `val` will fit in `Self` above.
+                    let val: Self = unsafe { val.try_into().unwrap_unchecked() };
+
+                    Ok(val.complement())

You're allowing to parse u32 with a leading -? I'd expect an error in that case. Maybe complement should be named negate and return a Result?

---
Cheers,
Benno

Quoted 8 lines
rust/kernel/str.rs +8 -0
+                }
+                _ => {
+                    let (radix, digits) = strip_radix(src);
+                    Self::from_str_radix(digits, radix).map_err(|_| EINVAL)
+                }
+            }
+        }
+    }
author reviewer
#3 lore raw

Re: [PATCH v12 1/3] rust: str: add radix prefixed integer parsing functions

Quoted 13 lines · Benno Lossin
Quoted 12 lines · Andreas Hindborg
rust/kernel/str.rs +0 -1
index 878111cb77bc..174e70397305 100644
@@ -573,7 +573,6 @@ macro_rules! c_str {
 }
 
 #[cfg(test)]
-#[expect(clippy::items_after_test_module)]
 mod tests {
     use super::*;
 
Quoted 10 lines

rust/kernel/str.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 951

Quoted 8 lines
rust/kernel/str.rs +4 -0
@@ -946,3 +945,174 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+/// Integer parsing functions for parsing signed and unsigned integers
+/// potentially prefixed with `0x`, `0o`, or `0b`.
+pub mod parse_int {

Why not make this its own file? It's 172 lines long already.

Sure. I'm really hoping to land this series for this cycle though, so if it's OK I would move the code next cycle.

Quoted 28 lines
Quoted 28 lines
rust/kernel/str.rs +27 -0
+    pub trait ParseInt: private::FromStrRadix + TryFrom<u64> {
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.deref() {
+                [b'-', rest @ ..] => {
+                    let (radix, digits) = strip_radix(rest.as_ref());
+                    // 2's complement values range from -2^(b-1) to 2^(b-1)-1.
+                    // So if we want to parse negative numbers as positive and
+                    // later multiply by -1, we have to parse into a larger
+                    // integer. We choose `u64` as sufficiently large.
+                    //
+                    // NOTE: 128 bit integers are not available on all
+                    // platforms, hence the choice of 64 bits.
+                    let val = u64::from_str_radix(
+                        core::str::from_utf8(digits).map_err(|_| EINVAL)?,
+                        radix,
+                    )
+                    .map_err(|_| EINVAL)?;
+
+                    if val > Self::abs_min() {
+                        return Err(EINVAL);
+                    }
+
+                    if val == Self::abs_min() {
+                        return Ok(Self::MIN);
+                    }
+
Quoted 8 lines

rust/kernel/str.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 1069

Quoted 4 lines
rust/kernel/str.rs +4 -0
+                    // SAFETY: We checked that `val` will fit in `Self` above.
+                    let val: Self = unsafe { val.try_into().unwrap_unchecked() };
+
+                    Ok(val.complement())

You're allowing to parse u32 with a leading -? I'd expect an error in that case. Maybe complement should be named negate and return a Result?

You would get Err(EINVAL) in that case, hitting this:

  if val > Self::abs_min() {
      return Err(EINVAL);
  }

Best regards,
Andreas Hindborg

reviewer
#6 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

In reply to Andreas Hindborg
Quoted 7 lines · Andreas Hindborg

Add support for module parameters to the module! macro. Implement read only support for integer types without sysfs support.

Quoted 7 lines
---
 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 204 +++++++++++++++++++++++++++++++++++++++++++
 rust/macros/helpers.rs       |  25 ++++++
 rust/macros/lib.rs           |  31 +++++++
 rust/macros/module.rs        | 195 ++++++++++++++++++++++++++++++++++++-----
 samples/rust/rust_minimal.rs |  10 +++

I know this is already the 12th version, but I think this patch should be split into the module_param module introduction, proc-macro modifications and the sample changes.

[...]

rust/kernel/module_param.rs line 57

Quoted 11 lines
rust/kernel/module_param.rs new file +11 -0
+/// Set the module parameter from a string.
+///
+/// Used to set the parameter value at kernel initialization, when loading
+/// the module or when set through `sysfs`.
+///
+/// See `struct kernel_param_ops.set`.
+///
+/// # Safety
+///
+/// - If `val` is non-null then it must point to a valid null-terminated string.
+///   The `arg` field of `param` must be an instance of `T`.

This sentence is conveying the same (or at least similar) requirement as the bullet point below.

rust/kernel/module_param.rs line 66

Quoted 9 lines
rust/kernel/module_param.rs new file +9 -0
+/// - `param.arg` must be a pointer to valid `*mut T` as set up by the
+///   [`module!`] macro.
+///
+/// # Invariants
+///
+/// Currently, we only support read-only parameters that are not readable
+/// from `sysfs`. Thus, this function is only called at kernel
+/// initialization time, or at module load time, and we have exclusive
+/// access to the parameter for the duration of the function.

Why is this an Invariants section?

Quoted 10 lines
rust/kernel/module_param.rs new file +10 -0
+///
+/// [`module!`]: macros::module
+unsafe extern "C" fn set_param<T>(
+    val: *const kernel::ffi::c_char,
+    param: *const crate::bindings::kernel_param,
+) -> core::ffi::c_int
+where
+    T: ModuleParam,
+{
+    // NOTE: If we start supporting arguments without values, val _is_ allowed

rust/kernel/module_param.rs line 86

Quoted 10 lines
rust/kernel/module_param.rs new file +10 -0
+    // to be null here.
+    if val.is_null() {
+        // TODO: Use pr_warn_once available.
+        crate::pr_warn!("Null pointer passed to `module_param::set_param`");
+        return EINVAL.to_errno();
+    }
+
+    // SAFETY: By function safety requirement, val is non-null and
+    // null-terminated. By C API contract, `val` is live and valid for reads
+    // for the duration of this function.

We shouldn't mention "C API contract" here and move the liveness requirement to the safety requirements of the function. Or change the safety requirements for this function to only be called from some specific C API.

rust/kernel/module_param.rs line 93

Quoted 7 lines
rust/kernel/module_param.rs new file +7 -0
+    let arg = unsafe { CStr::from_char_ptr(val) };
+
+    crate::error::from_result(|| {
+        let new_value = T::try_from_param_arg(arg)?;
+
+        // SAFETY: `param` is guaranteed to be valid by C API contract
+        // and `arg` is guaranteed to point to an instance of `T`.

Ditto.

rust/kernel/module_param.rs line 98

Quoted 5 lines
rust/kernel/module_param.rs new file +5 -0
+        let old_value = unsafe { (*param).__bindgen_anon_1.arg as *mut T };
+
+        // SAFETY: `old_value` is valid for writes, as we have exclusive
+        // access. `old_value` is pointing to an initialized static, and
+        // so it is properly initialized.

Why do we have exclusive access? Should be in the safety requirements.

Quoted 4 lines
rust/kernel/module_param.rs new file +4 -0
+        unsafe { *old_value = new_value };
+        Ok(0)
+    })
+}

[...]

Quoted 6 lines
rust/kernel/module_param.rs new file +6 -0
+#[doc(hidden)]
+#[macro_export]
+/// Generate a static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) struct.
+///
+/// # Examples
+///

rust/kernel/module_param.rs line 182

Quoted 10 lines
rust/kernel/module_param.rs new file +10 -0
+/// ```ignore
+/// make_param_ops!(
+///     /// Documentation for new param ops.
+///     PARAM_OPS_MYTYPE, // Name for the static.
+///     MyType // A type which implements [`ModuleParam`].
+/// );
+/// ```
+macro_rules! make_param_ops {
+    ($ops:ident, $ty:ty) => {
+        ///

Spurious newline?

rust/kernel/module_param.rs line 184

Quoted 2 lines
rust/kernel/module_param.rs new file +2 -0
+        /// Static [`kernel_param_ops`](srctree/include/linux/moduleparam.h)
+        /// struct generated by `make_param_ops`

Is it useful for this fact to be in the docs? I'd remove it.

Quoted 25 lines
rust/kernel/module_param.rs new file +20 -0
+        #[doc = concat!("for [`", stringify!($ty), "`].")]
+        pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops {
+            flags: 0,
+            set: Some(set_param::<$ty>),
+            get: None,
+            free: None,
+        };
+    };
+}
+
+make_param_ops!(PARAM_OPS_I8, i8);
+make_param_ops!(PARAM_OPS_U8, u8);
+make_param_ops!(PARAM_OPS_I16, i16);
+make_param_ops!(PARAM_OPS_U16, u16);
+make_param_ops!(PARAM_OPS_I32, i32);
+make_param_ops!(PARAM_OPS_U32, u32);
+make_param_ops!(PARAM_OPS_I64, i64);
+make_param_ops!(PARAM_OPS_U64, u64);
+make_param_ops!(PARAM_OPS_ISIZE, isize);
+make_param_ops!(PARAM_OPS_USIZE, usize);
rust/macros/helpers.rs +0 -0
index a3ee27e29a6f..16d300ad3d3b 100644

rust/macros/helpers.rs pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { · line 16

Quoted 7 lines
rust/macros/helpers.rs +4 -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() == '-' => {

Should we also allow a leading +?

Quoted 16 lines
rust/macros/helpers.rs +9 -0
+            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())
@@ -86,3 +97,17 @@ pub(crate) fn function_name(input: TokenStream) -> Option<Ident> {
     }
     None
 }
+
+/// Parse a token stream of the form `expected_name: "value",` and return the

rust/macros/helpers.rs pub(crate) fn function_name(input: TokenStream) -> Option<Ident> { · line 111

Quoted 10 lines
rust/macros/helpers.rs +10 -0
+/// 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), ',');

This won't allow omitting the trailing comma.

Quoted 2 lines
rust/macros/helpers.rs +2 -0
+    string
+}

[...]

Quoted 24 lines
rust/macros/helpers.rs +7 -7
@@ -186,33 +336,35 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
     let info = ModuleInfo::parse(&mut it);
 
     let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
-    if let Some(author) = info.author {
-        modinfo.emit("author", &author);
+    if let Some(author) = &info.author {
+        modinfo.emit("author", author);
     }
-    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 {

rust/macros/helpers.rs pub(crate) fn module(ts: TokenStream) -> TokenStream { · line 358

Quoted 10 lines
rust/macros/helpers.rs +3 -3
         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);

I don't like that you have to change all of these. Can't you just take a &[Parameter] argument in emit_params instead of the whole ModuleInfo struct?

---
Cheers,
Benno

Quoted 2 lines
rust/macros/helpers.rs +0 -0
         }
     }
reviewer
#4 lore raw

Re: [PATCH v12 1/3] rust: str: add radix prefixed integer parsing functions

In reply to Andreas Hindborg
Quoted 38 lines · Andreas Hindborg
Quoted 28 lines · Benno Lossin
Quoted 27 lines · Andreas Hindborg
rust/kernel/str.rs +27 -0
+    pub trait ParseInt: private::FromStrRadix + TryFrom<u64> {
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.deref() {
+                [b'-', rest @ ..] => {
+                    let (radix, digits) = strip_radix(rest.as_ref());
+                    // 2's complement values range from -2^(b-1) to 2^(b-1)-1.
+                    // So if we want to parse negative numbers as positive and
+                    // later multiply by -1, we have to parse into a larger
+                    // integer. We choose `u64` as sufficiently large.
+                    //
+                    // NOTE: 128 bit integers are not available on all
+                    // platforms, hence the choice of 64 bits.
+                    let val = u64::from_str_radix(
+                        core::str::from_utf8(digits).map_err(|_| EINVAL)?,
+                        radix,
+                    )
+                    .map_err(|_| EINVAL)?;
+
+                    if val > Self::abs_min() {
+                        return Err(EINVAL);
+                    }
+
+                    if val == Self::abs_min() {
+                        return Ok(Self::MIN);
+                    }
+
Quoted 8 lines

rust/kernel/str.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 1069

Quoted 4 lines
rust/kernel/str.rs +4 -0
+                    // SAFETY: We checked that `val` will fit in `Self` above.
+                    let val: Self = unsafe { val.try_into().unwrap_unchecked() };
+
+                    Ok(val.complement())

You're allowing to parse u32 with a leading -? I'd expect an error in that case. Maybe complement should be named negate and return a Result?

Quoted 5 lines

You would get Err(EINVAL) in that case, hitting this:

  if val > Self::abs_min() {
      return Err(EINVAL);
  }

Ah, I think I asked this in a previous version already... Thanks.

---
Cheers,
Benno

author reviewer
#7 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

In reply to Benno Lossin
Quoted 16 lines · Benno Lossin
Quoted 7 lines · Andreas Hindborg

Add support for module parameters to the module! macro. Implement read only support for integer types without sysfs support.

Quoted 7 lines
---
 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 204 +++++++++++++++++++++++++++++++++++++++++++
 rust/macros/helpers.rs       |  25 ++++++
 rust/macros/lib.rs           |  31 +++++++
 rust/macros/module.rs        | 195 ++++++++++++++++++++++++++++++++++++-----
 samples/rust/rust_minimal.rs |  10 +++
Quoted 4 lines

I know this is already the 12th version, but I think this patch should be split into the module_param module introduction, proc-macro modifications and the sample changes.

OK.

Quoted 16 lines

[...]

rust/kernel/module_param.rs line 57

Quoted 11 lines
rust/kernel/module_param.rs new file +11 -0
+/// Set the module parameter from a string.
+///
+/// Used to set the parameter value at kernel initialization, when loading
+/// the module or when set through `sysfs`.
+///
+/// See `struct kernel_param_ops.set`.
+///
+/// # Safety
+///
+/// - If `val` is non-null then it must point to a valid null-terminated string.
+///   The `arg` field of `param` must be an instance of `T`.

This sentence is conveying the same (or at least similar) requirement as the bullet point below.

Yes, you are right. At any rate the wording is wrong, a pointer cannot "be an instance", it can point to one.

Quoted 12 lines

rust/kernel/module_param.rs line 66

Quoted 10 lines
rust/kernel/module_param.rs new file +9 -0
+/// - `param.arg` must be a pointer to valid `*mut T` as set up by the
+///   [`module!`] macro.
+///
+/// # Invariants
+///
+/// Currently, we only support read-only parameters that are not readable
+/// from `sysfs`. Thus, this function is only called at kernel
+/// initialization time, or at module load time, and we have exclusive
+/// access to the parameter for the duration of the function.

Why is this an Invariants section?

Looks like a mistake, I'll change it to "# Note".

Quoted 18 lines
Quoted 18 lines
rust/kernel/module_param.rs new file +17 -0
+///
+/// [`module!`]: macros::module
+unsafe extern "C" fn set_param<T>(
+    val: *const kernel::ffi::c_char,
+    param: *const crate::bindings::kernel_param,
+) -> core::ffi::c_int
+where
+    T: ModuleParam,
+{
+    // NOTE: If we start supporting arguments without values, val _is_ allowed
+    // to be null here.
+    if val.is_null() {
+        // TODO: Use pr_warn_once available.
+        crate::pr_warn!("Null pointer passed to `module_param::set_param`");
+        return EINVAL.to_errno();
+    }
+
Quoted 8 lines

rust/kernel/module_param.rs line 86

Quoted 3 lines
rust/kernel/module_param.rs new file +3 -0
+    // SAFETY: By function safety requirement, val is non-null and
+    // null-terminated. By C API contract, `val` is live and valid for reads
+    // for the duration of this function.

We shouldn't mention "C API contract" here and move the liveness requirement to the safety requirements of the function. Or change the safety requirements for this function to only be called from some specific C API.

OK.

Quoted 10 lines

rust/kernel/module_param.rs line 93

Quoted 8 lines
rust/kernel/module_param.rs new file +7 -0
+    let arg = unsafe { CStr::from_char_ptr(val) };
+
+    crate::error::from_result(|| {
+        let new_value = T::try_from_param_arg(arg)?;
+
+        // SAFETY: `param` is guaranteed to be valid by C API contract
+        // and `arg` is guaranteed to point to an instance of `T`.

Ditto.

OK.

Quoted 8 lines

rust/kernel/module_param.rs line 98

Quoted 6 lines
rust/kernel/module_param.rs new file +5 -0
+        let old_value = unsafe { (*param).__bindgen_anon_1.arg as *mut T };
+
+        // SAFETY: `old_value` is valid for writes, as we have exclusive
+        // access. `old_value` is pointing to an initialized static, and
+        // so it is properly initialized.

Why do we have exclusive access? Should be in the safety requirements.

Will add this.

Quoted 18 lines
Quoted 5 lines
rust/kernel/module_param.rs new file +4 -0
+        unsafe { *old_value = new_value };
+        Ok(0)
+    })
+}

[...]

Quoted 10 lines
rust/kernel/module_param.rs new file +10 -0
+#[doc(hidden)]
+#[macro_export]
+/// Generate a static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) struct.
+///
+/// # Examples
+///
+/// ```ignore
+/// make_param_ops!(
+///     /// Documentation for new param ops.
+///     PARAM_OPS_MYTYPE, // Name for the static.
Quoted 8 lines

rust/kernel/module_param.rs line 182

Quoted 6 lines
rust/kernel/module_param.rs new file +6 -0
+///     MyType // A type which implements [`ModuleParam`].
+/// );
+/// ```
+macro_rules! make_param_ops {
+    ($ops:ident, $ty:ty) => {
+        ///

Spurious newline?

Will remove.

Quoted 5 lines

rust/kernel/module_param.rs line 184

Quoted 3 lines
rust/kernel/module_param.rs new file +2 -0
+        /// Static [`kernel_param_ops`](srctree/include/linux/moduleparam.h)
+        /// struct generated by `make_param_ops`

Is it useful for this fact to be in the docs? I'd remove it.

OK.

Quoted 29 lines
Quoted 29 lines
rust/kernel/module_param.rs new file +20 -0
+        #[doc = concat!("for [`", stringify!($ty), "`].")]
+        pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops {
+            flags: 0,
+            set: Some(set_param::<$ty>),
+            get: None,
+            free: None,
+        };
+    };
+}
+
+make_param_ops!(PARAM_OPS_I8, i8);
+make_param_ops!(PARAM_OPS_U8, u8);
+make_param_ops!(PARAM_OPS_I16, i16);
+make_param_ops!(PARAM_OPS_U16, u16);
+make_param_ops!(PARAM_OPS_I32, i32);
+make_param_ops!(PARAM_OPS_U32, u32);
+make_param_ops!(PARAM_OPS_I64, i64);
+make_param_ops!(PARAM_OPS_U64, u64);
+make_param_ops!(PARAM_OPS_ISIZE, isize);
+make_param_ops!(PARAM_OPS_USIZE, usize);
rust/macros/helpers.rs +0 -0
index a3ee27e29a6f..16d300ad3d3b 100644
@@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> {
     }
 }
 
Quoted 6 lines

rust/macros/helpers.rs pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { · line 16

Quoted 4 lines
rust/macros/helpers.rs +4 -0
+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() == '-' => {

Should we also allow a leading +?

I would argue no, because rust literals cannot start with +.

Quoted 21 lines
Quoted 21 lines
rust/macros/helpers.rs +13 -0
+            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())
@@ -86,3 +97,17 @@ pub(crate) fn function_name(input: TokenStream) -> Option<Ident> {
     }
     None
 }
+
+/// Parse a token stream of the form `expected_name: "value",` and return the
+/// string in the position of "value".
+///
+/// # Panics
+///
Quoted 8 lines

rust/macros/helpers.rs pub(crate) fn function_name(input: TokenStream) -> Option<Ident> { · line 111

Quoted 6 lines
rust/macros/helpers.rs +6 -0
+/// - 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), ',');

This won't allow omitting the trailing comma.

This is in line with the rest of the module macro.

Quoted 34 lines
Quoted 3 lines
rust/macros/helpers.rs +2 -0
+    string
+}

[...]

Quoted 28 lines
rust/macros/helpers.rs +8 -8
@@ -186,33 +336,35 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
     let info = ModuleInfo::parse(&mut it);
 
     let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
-    if let Some(author) = info.author {
-        modinfo.emit("author", &author);
+    if let Some(author) = &info.author {
+        modinfo.emit("author", author);
     }
-    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);
         }
Quoted 8 lines

rust/macros/helpers.rs pub(crate) fn module(ts: TokenStream) -> TokenStream { · line 358

Quoted 6 lines
rust/macros/helpers.rs +2 -2
     }
-    if let Some(firmware) = info.firmware {
+    if let Some(firmware) = &info.firmware {
         for fw in firmware {
-            modinfo.emit("firmware", &fw);
+            modinfo.emit("firmware", fw);

I don't like that you have to change all of these.

Why not? If I was to write this code in the first place, I would have used a reference rather than pass by value.

Quoted 3 lines

Can't you just take a
&[Parameter] argument in emit_params instead of the whole ModuleInfo struct?

I don't think that is a nice solution. I would have to pass the name field as well, increasing the number of parameters to the function.

Best regards,
Andreas Hindborg

author reviewer
#8 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

Quoted 143 lines · Andreas Hindborg
Quoted 16 lines · Benno Lossin
Quoted 7 lines · Andreas Hindborg

Add support for module parameters to the module! macro. Implement read only support for integer types without sysfs support.

Quoted 7 lines
---
 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 204 +++++++++++++++++++++++++++++++++++++++++++
 rust/macros/helpers.rs       |  25 ++++++
 rust/macros/lib.rs           |  31 +++++++
 rust/macros/module.rs        | 195 ++++++++++++++++++++++++++++++++++++-----
 samples/rust/rust_minimal.rs |  10 +++
Quoted 4 lines

I know this is already the 12th version, but I think this patch should be split into the module_param module introduction, proc-macro modifications and the sample changes.

OK.

Quoted 16 lines

[...]

rust/kernel/module_param.rs line 57

Quoted 11 lines
rust/kernel/module_param.rs new file +11 -0
+/// Set the module parameter from a string.
+///
+/// Used to set the parameter value at kernel initialization, when loading
+/// the module or when set through `sysfs`.
+///
+/// See `struct kernel_param_ops.set`.
+///
+/// # Safety
+///
+/// - If `val` is non-null then it must point to a valid null-terminated string.
+///   The `arg` field of `param` must be an instance of `T`.

This sentence is conveying the same (or at least similar) requirement as the bullet point below.

Yes, you are right. At any rate the wording is wrong, a pointer cannot "be an instance", it can point to one.

Quoted 12 lines

rust/kernel/module_param.rs line 66

Quoted 10 lines
rust/kernel/module_param.rs new file +9 -0
+/// - `param.arg` must be a pointer to valid `*mut T` as set up by the
+///   [`module!`] macro.
+///
+/// # Invariants
+///
+/// Currently, we only support read-only parameters that are not readable
+/// from `sysfs`. Thus, this function is only called at kernel
+/// initialization time, or at module load time, and we have exclusive
+/// access to the parameter for the duration of the function.

Why is this an Invariants section?

Looks like a mistake, I'll change it to "# Note".

Quoted 18 lines
Quoted 18 lines
rust/kernel/module_param.rs new file +17 -0
+///
+/// [`module!`]: macros::module
+unsafe extern "C" fn set_param<T>(
+    val: *const kernel::ffi::c_char,
+    param: *const crate::bindings::kernel_param,
+) -> core::ffi::c_int
+where
+    T: ModuleParam,
+{
+    // NOTE: If we start supporting arguments without values, val _is_ allowed
+    // to be null here.
+    if val.is_null() {
+        // TODO: Use pr_warn_once available.
+        crate::pr_warn!("Null pointer passed to `module_param::set_param`");
+        return EINVAL.to_errno();
+    }
+
Quoted 8 lines

rust/kernel/module_param.rs line 86

Quoted 3 lines
rust/kernel/module_param.rs new file +3 -0
+    // SAFETY: By function safety requirement, val is non-null and
+    // null-terminated. By C API contract, `val` is live and valid for reads
+    // for the duration of this function.

We shouldn't mention "C API contract" here and move the liveness requirement to the safety requirements of the function. Or change the safety requirements for this function to only be called from some specific C API.

OK.

Quoted 10 lines

rust/kernel/module_param.rs line 93

Quoted 8 lines
rust/kernel/module_param.rs new file +7 -0
+    let arg = unsafe { CStr::from_char_ptr(val) };
+
+    crate::error::from_result(|| {
+        let new_value = T::try_from_param_arg(arg)?;
+
+        // SAFETY: `param` is guaranteed to be valid by C API contract
+        // and `arg` is guaranteed to point to an instance of `T`.

Ditto.

OK.

Quoted 8 lines

rust/kernel/module_param.rs line 98

Quoted 6 lines
rust/kernel/module_param.rs new file +5 -0
+        let old_value = unsafe { (*param).__bindgen_anon_1.arg as *mut T };
+
+        // SAFETY: `old_value` is valid for writes, as we have exclusive
+        // access. `old_value` is pointing to an initialized static, and
+        // so it is properly initialized.

Why do we have exclusive access? Should be in the safety requirements.

Will add this.

Quoted 18 lines
Quoted 5 lines
rust/kernel/module_param.rs new file +4 -0
+        unsafe { *old_value = new_value };
+        Ok(0)
+    })
+}

[...]

Quoted 10 lines
rust/kernel/module_param.rs new file +10 -0
+#[doc(hidden)]
+#[macro_export]
+/// Generate a static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) struct.
+///
+/// # Examples
+///
+/// ```ignore
+/// make_param_ops!(
+///     /// Documentation for new param ops.
+///     PARAM_OPS_MYTYPE, // Name for the static.
Quoted 8 lines

rust/kernel/module_param.rs line 182

Quoted 6 lines
rust/kernel/module_param.rs new file +6 -0
+///     MyType // A type which implements [`ModuleParam`].
+/// );
+/// ```
+macro_rules! make_param_ops {
+    ($ops:ident, $ty:ty) => {
+        ///

Spurious newline?

Will remove.

Quoted 1 line
Quoted 7 lines
Quoted 4 lines

rust/kernel/module_param.rs line 184

Quoted 2 lines
rust/kernel/module_param.rs new file +2 -0
+        /// Static [`kernel_param_ops`](srctree/include/linux/moduleparam.h)
+        /// struct generated by `make_param_ops`

Is it useful for this fact to be in the docs? I'd remove it.

OK.

Clippy thinks it is useful:

    error: missing documentation for a static
      --> /home/aeh/src/linux-rust/module-params/rust/kernel/module_param.rs:182:9
        |
    182 |         pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops {
        |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...
    191 | make_param_ops!(PARAM_OPS_I8, i8);
        | --------------------------------- in this macro invocation
        |

So either we need to #[allow(missing_docs)] or just add the line back. What do you prefer?

Best regards,
Andreas Hindborg

#9 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

Quoted 2 lines · Andreas Hindborg

So either we need to #[allow(missing_docs)] or just add the line back. What do you prefer?

Do you mean if you remove the concat! too, right?

It would need to be expect, but I think even an expect(missing_docs) is not really useful vs. having some docs.

But another question is: if the docs are not useful, should an item be hidden to begin with?

(By the way, that one is rustc, not Clippy)

Cheers,
Miguel

#13 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

In reply to Benno Lossin
Quoted 5 lines · Benno Lossin

rust/kernel/module_param.rs line 72

Quoted 5 lines
rust/kernel/module_param.rs new file +4 -0
+unsafe extern "C" fn set_param<T>(
+    val: *const kernel::ffi::c_char,
+    param: *const crate::bindings::kernel_param,
+) -> core::ffi::c_int

New instance of core::ffi:: (and both these c_* should be unqualified).

Cheers,
Miguel

author reviewer
#10 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

In reply to Miguel Ojeda
Quoted 5 lines · Miguel Ojeda
Quoted 2 lines · Andreas Hindborg

So either we need to #[allow(missing_docs)] or just add the line back. What do you prefer?

Do you mean if you remove the concat! too, right?

Yes, all of it.

Quoted 6 lines

It would need to be expect, but I think even an expect(missing_docs) is not really useful vs. having some docs.

But another question is: if the docs are not useful, should an item be hidden to begin with?

That is probably the best solution, yes.

Quoted 1 line

(By the way, that one is rustc, not Clippy)

Right.

Best regards,
Andreas Hindborg

reviewer
#11 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

In reply to Andreas Hindborg
Quoted 10 lines · Andreas Hindborg
Quoted 9 lines · Benno Lossin
Quoted 8 lines · Andreas Hindborg
rust/macros/helpers.rs +0 -0
index a3ee27e29a6f..16d300ad3d3b 100644
@@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> {
     }
 }
 
Quoted 8 lines
Quoted 6 lines

rust/macros/helpers.rs pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { · line 16

Quoted 4 lines
rust/macros/helpers.rs +4 -0
+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() == '-' => {

Should we also allow a leading +?

I would argue no, because rust literals cannot start with +.

Makes sense.

Quoted 29 lines
Quoted 20 lines
Quoted 20 lines
rust/macros/helpers.rs +13 -0
+            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())
@@ -86,3 +97,17 @@ pub(crate) fn function_name(input: TokenStream) -> Option<Ident> {
     }
     None
 }
+
+/// Parse a token stream of the form `expected_name: "value",` and return the
+/// string in the position of "value".
+///
+/// # Panics
+///
Quoted 8 lines

rust/macros/helpers.rs pub(crate) fn function_name(input: TokenStream) -> Option<Ident> { · line 111

Quoted 6 lines
rust/macros/helpers.rs +6 -0
+/// - 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), ',');

This won't allow omitting the trailing comma.

Quoted 1 line

This is in line with the rest of the module macro.

Then we should change that:

    https://github.com/Rust-for-Linux/linux/issues/1172
Quoted 42 lines
Quoted 33 lines
Quoted 2 lines
rust/macros/helpers.rs +2 -0
+    string
+}

[...]

Quoted 28 lines
rust/macros/helpers.rs +8 -8
@@ -186,33 +336,35 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
     let info = ModuleInfo::parse(&mut it);
 
     let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
-    if let Some(author) = info.author {
-        modinfo.emit("author", &author);
+    if let Some(author) = &info.author {
+        modinfo.emit("author", author);
     }
-    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);
         }
Quoted 8 lines

rust/macros/helpers.rs pub(crate) fn module(ts: TokenStream) -> TokenStream { · line 358

Quoted 6 lines
rust/macros/helpers.rs +2 -2
     }
-    if let Some(firmware) = info.firmware {
+    if let Some(firmware) = &info.firmware {
         for fw in firmware {
-            modinfo.emit("firmware", &fw);
+            modinfo.emit("firmware", fw);

I don't like that you have to change all of these.

Quoted 2 lines

Why not? If I was to write this code in the first place, I would have used a reference rather than pass by value.

That's fine, but do it in a separate commit then.

Quoted 6 lines
Quoted 3 lines

Can't you just take a
&[Parameter] argument in emit_params instead of the whole ModuleInfo struct?

I don't think that is a nice solution. I would have to pass the name field as well, increasing the number of parameters to the function.

Ah right makes sense.

---
Cheers,
Benno

author reviewer
#12 lore raw

Re: [PATCH v12 2/3] rust: add parameter support to the `module!` macro

Quoted 99 lines · Benno Lossin
Quoted 10 lines · Andreas Hindborg
Quoted 9 lines · Benno Lossin
Quoted 8 lines · Andreas Hindborg
rust/macros/helpers.rs +0 -0
index a3ee27e29a6f..16d300ad3d3b 100644
@@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> {
     }
 }
 
Quoted 8 lines
Quoted 6 lines

rust/macros/helpers.rs pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { · line 16

Quoted 4 lines
rust/macros/helpers.rs +4 -0
+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() == '-' => {

Should we also allow a leading +?

I would argue no, because rust literals cannot start with +.

Makes sense.

Quoted 29 lines
Quoted 20 lines
Quoted 20 lines
rust/macros/helpers.rs +13 -0
+            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())
@@ -86,3 +97,17 @@ pub(crate) fn function_name(input: TokenStream) -> Option<Ident> {
     }
     None
 }
+
+/// Parse a token stream of the form `expected_name: "value",` and return the
+/// string in the position of "value".
+///
+/// # Panics
+///
Quoted 8 lines

rust/macros/helpers.rs pub(crate) fn function_name(input: TokenStream) -> Option<Ident> { · line 111

Quoted 6 lines
rust/macros/helpers.rs +6 -0
+/// - 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), ',');

This won't allow omitting the trailing comma.

Quoted 1 line

This is in line with the rest of the module macro.

Then we should change that:

    https://github.com/Rust-for-Linux/linux/issues/1172
Quoted 42 lines
Quoted 41 lines
Quoted 2 lines
rust/macros/helpers.rs +2 -0
+    string
+}

[...]

Quoted 24 lines
rust/macros/helpers.rs +7 -7
@@ -186,33 +336,35 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
     let info = ModuleInfo::parse(&mut it);
 
     let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
-    if let Some(author) = info.author {
-        modinfo.emit("author", &author);
+    if let Some(author) = &info.author {
+        modinfo.emit("author", author);
     }
-    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 {

rust/macros/helpers.rs pub(crate) fn module(ts: TokenStream) -> TokenStream { · line 358

Quoted 10 lines
rust/macros/helpers.rs +3 -3
         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);

I don't like that you have to change all of these.

Quoted 4 lines
Quoted 2 lines

Why not? If I was to write this code in the first place, I would have used a reference rather than pass by value.

That's fine, but do it in a separate commit then.

OK, I can do that 👍

Best regards,
Andreas Hindborg