Skip to contentSkip to conversation

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

PATCH Superseded Andreas Hindborg 4 participants 18 messages Feb 11, 2025 – Feb 18, 2025

Subsystems (3)

v6 of 18 Superseded Latest is v18 →

lore
Share & tools
lore

Andreas Hindborg

author reviewer
#0 lore raw

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

This series extends the module! macro with support module parameters. It also adds some string to integer parsing functions and updates BStr with a method to strip a string prefix.

This series stated out as code by Adam Bratschi-Kaye lifted from the original rust branch [1].

After a bit of discussion on v3 about whether or not module parameters is a good idea, it seems that module parameters in Rust has a place in the kernel for now. This series is a dependency for rnull, the Rust null block driver [2].

---
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 (6):
rust: str: implement PartialEq for BStr
rust: str: implement Index for BStr
rust: str: implement AsRef<BStr> for [u8] and BStr
rust: str: implement strip_prefix for BStr
rust: str: add radix prefixed integer parsing functions
rust: add parameter support to the module! macro

 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 225 +++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/str.rs           | 156 ++++++++++++++++++++++++++++++
 rust/macros/helpers.rs       |  25 +++++
 rust/macros/lib.rs           |  31 ++++++
 rust/macros/module.rs        | 191 ++++++++++++++++++++++++++++++++----
 samples/rust/rust_minimal.rs |  10 ++
 7 files changed, 621 insertions(+), 18 deletions(-)

---
base-commit: 379487e17ca406b47392e7ab6cf35d1c3bacb371
change-id: 20241211-module-params-v3-ae7e5c8d8b5a
prerequisite-change-id: 20241107-pr_once_macros-6438e6f5b923:v4
prerequisite-patch-id: 57743fff5d9c649ff7c1aed7e374d08ae67dda91
prerequisite-patch-id: fe607e3e1f666e7250bf099e581d53c83fea5f7d
prerequisite-patch-id: eb030eccf23466b0e22e7c699f252c40bd5f21bf

Best regards,

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

PATCH v6 1/6 rust: str: implement `PartialEq` for `BStr`

Implement PartialEq for BStr by comparing underlying byte slices.

---
 rust/kernel/str.rs | 6 ++++++
 1 file changed, 6 insertions(+)
rust/kernel/str.rs +6 -0
index 28e2201604d67..002dcddf7c768 100644
@@ -108,6 +108,12 @@ fn deref(&self) -> &Self::Target {
     }
 }
 
+impl PartialEq for BStr {
+    fn eq(&self, other: &Self) -> bool {
+        self.deref().eq(other.deref())
+    }
+}
+
 /// Creates a new [`BStr`] from a string literal.
 ///
 /// `b_str!` converts the supplied string literal to byte string, so non-ASCII
Signature · 1 line
2.47.0
author reviewer
#2 lore raw

PATCH v6 2/6 rust: str: implement `Index` for `BStr`

In reply to Andreas Hindborg

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +11 -0
index 002dcddf7c768..1eb945bed77d6 100644
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,
+{
+    type Output = Self;
+
+    fn index(&self, index: Idx) -> &Self::Output {
+        BStr::from_bytes(&self.0[index])
+    }
+}
+
 /// Creates a new [`BStr`] from a string literal.
 ///
 /// `b_str!` converts the supplied string literal to byte string, so non-ASCII
Signature · 1 line
2.47.0
reviewer
#3 lore raw

Re: [PATCH v6 2/6] rust: str: implement `Index` for `BStr`

Quoted 15 lines · On Tue, 11 Feb 2025 16:57:36 +0100 Andreas Hindborg <[email protected]>…

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +0 -0
index 002dcddf7c768..1eb945bed77d6 100644

rust/kernel/str.rs fn eq(&self, other: &Self) -> bool { · line 119

Quoted 6 lines
rust/kernel/str.rs +3 -0
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,

I think I'd prefer

	[T]: Index<Idx>,

here.

Quoted 12 lines
rust/kernel/str.rs +8 -0
+{
+    type Output = Self;
+
+    fn index(&self, index: Idx) -> &Self::Output {
+        BStr::from_bytes(&self.0[index])
+    }
+}
+
 /// Creates a new [`BStr`] from a string literal.
 ///
 /// `b_str!` converts the supplied string literal to byte string, so non-ASCII
author reviewer
#4 lore raw

Re: [PATCH v6 2/6] rust: str: implement `Index` for `BStr`

Quoted 21 lines · Gary Guo
Quoted 18 lines · On Tue, 11 Feb 2025 16:57:36 +0100 Andreas Hindborg <[email protected]>…

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +0 -0
index 002dcddf7c768..1eb945bed77d6 100644
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
Quoted 7 lines

rust/kernel/str.rs fn eq(&self, other: &Self) -> bool { · line 119

Quoted 3 lines
rust/kernel/str.rs +3 -0
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,

I think I'd prefer

	[T]: Index<Idx>,

Is that equivalent?

Best regards,
Andreas Hindborg

reviewer
#5 lore raw

Re: [PATCH v6 2/6] rust: str: implement `Index` for `BStr`

Quoted 29 lines · On Tue, 11 Feb 2025 21:24:44 +0100 Andreas Hindborg <[email protected]>…
Quoted 27 lines · Gary Guo
Quoted 15 lines · On Tue, 11 Feb 2025 16:57:36 +0100 Andreas Hindborg <[email protected]>…

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +0 -0
index 002dcddf7c768..1eb945bed77d6 100644

rust/kernel/str.rs fn eq(&self, other: &Self) -> bool { · line 119

Quoted 6 lines
rust/kernel/str.rs +3 -0
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,  

I think I'd prefer

Quoted 3 lines
Quoted 1 line
	[T]: Index<Idx>,  

Is that equivalent?

Sorry, I meant [u8]: Index<Idx>. This makes more semantic sense that "what ever can index a byte slice, it can also index BStr". This is also how our CStr and the array primitive type implements its Index operation.

They should be equivalent as libcore does

	impl<T, I> Index<I> for [T] where I: SliceIndex<[T]> { ... }

Best,
Gary

Quoted 6 lines

Best regards,
Andreas Hindborg

author reviewer
#6 lore raw

Re: [PATCH v6 2/6] rust: str: implement `Index` for `BStr`

Quoted 36 lines · Gary Guo
Quoted 29 lines · On Tue, 11 Feb 2025 21:24:44 +0100 Andreas Hindborg <[email protected]>…
Quoted 27 lines · Gary Guo
Quoted 15 lines · On Tue, 11 Feb 2025 16:57:36 +0100 Andreas Hindborg <[email protected]>…

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +0 -0
index 002dcddf7c768..1eb945bed77d6 100644

rust/kernel/str.rs fn eq(&self, other: &Self) -> bool { · line 119

Quoted 6 lines
rust/kernel/str.rs +3 -0
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,

I think I'd prefer

Quoted 3 lines
Quoted 1 line
	[T]: Index<Idx>,

Is that equivalent?

Quoted 9 lines

Sorry, I meant [u8]: Index<Idx>. This makes more semantic sense that "what ever can index a byte slice, it can also index BStr". This is also how our CStr and the array primitive type implements its Index operation.

They should be equivalent as libcore does

	impl<T, I> Index<I> for [T] where I: SliceIndex<[T]> { ... }

What I originally wrote is Idx must be usable as an index for [u8], yielding [u8] when indexing.

The new one you suggest, I parse as [u8] should be indexable by Idx. This is less info. The compiler will also complain about the missing info:

error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/module-params/rust/kernel/str.rs:141:26

    |
141 |         BStr::from_bytes(&self.0[index])
    |         ---------------- ^^^^^^^^^^^^^^ expected `&[u8]`, found `&<[u8] as Index<Idx>>::Output`
    |         |
    |         arguments to this function are incorrect
    |

= note: expected reference &[u8]
found reference &<[u8] as Index<Idx>>::Output
= help: consider constraining the associated type <[u8] as Index<Idx>>::Output to [u8]

If I constrain the output it's all fine again:

    [u8]: Index<Idx, Output = [u8]>,

But as I said, I don't think it matters which direction we put this?

Best regards,
Andreas Hindborg

#7 lore raw

Re: [PATCH v6 2/6] rust: str: implement `Index` for `BStr`

Quoted 66 lines · Andreas Hindborg
Quoted 36 lines · Gary Guo
Quoted 29 lines · On Tue, 11 Feb 2025 21:24:44 +0100 Andreas Hindborg <[email protected]>…
Quoted 27 lines · Gary Guo
Quoted 15 lines · On Tue, 11 Feb 2025 16:57:36 +0100 Andreas Hindborg <[email protected]>…

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +0 -0
index 002dcddf7c768..1eb945bed77d6 100644

rust/kernel/str.rs fn eq(&self, other: &Self) -> bool { · line 119

Quoted 6 lines
rust/kernel/str.rs +3 -0
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,

I think I'd prefer

Quoted 3 lines
Quoted 1 line
	[T]: Index<Idx>,

Is that equivalent?

Quoted 9 lines

Sorry, I meant [u8]: Index<Idx>. This makes more semantic sense that "what ever can index a byte slice, it can also index BStr". This is also how our CStr and the array primitive type implements its Index operation.

They should be equivalent as libcore does

	impl<T, I> Index<I> for [T] where I: SliceIndex<[T]> { ... }

What I originally wrote is Idx must be usable as an index for [u8], yielding [u8] when indexing.

The new one you suggest, I parse as [u8] should be indexable by Idx. This is less info. The compiler will also complain about the missing info:

error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/module-params/rust/kernel/str.rs:141:26

    |
141 |         BStr::from_bytes(&self.0[index])
    |         ---------------- ^^^^^^^^^^^^^^ expected `&[u8]`, found `&<[u8] as Index<Idx>>::Output`
    |         |
    |         arguments to this function are incorrect
    |

= note: expected reference &[u8]
found reference &<[u8] as Index<Idx>>::Output
= help: consider constraining the associated type <[u8] as Index<Idx>>::Output to [u8]

Quoted 6 lines

If I constrain the output it's all fine again:

    [u8]: Index<Idx, Output = [u8]>,

But as I said, I don't think it matters which direction we put this?

I think it's better to depend on Index compared to SliceIndex.

---
Cheers,
Benno

author reviewer
#8 lore raw

Re: [PATCH v6 2/6] rust: str: implement `Index` for `BStr`

Quoted 67 lines · Benno Lossin
Quoted 66 lines · Andreas Hindborg
Quoted 36 lines · Gary Guo
Quoted 29 lines · On Tue, 11 Feb 2025 21:24:44 +0100 Andreas Hindborg <[email protected]>…
Quoted 27 lines · Gary Guo
Quoted 15 lines · On Tue, 11 Feb 2025 16:57:36 +0100 Andreas Hindborg <[email protected]>…

The Index implementation on BStr was lost when we switched BStr from a type alias of [u8] to a newtype. This patch adds back Index by implementing Index for BStr when Index would be implemented for [u8].

---
 rust/kernel/str.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/str.rs +0 -0
index 002dcddf7c768..1eb945bed77d6 100644

rust/kernel/str.rs fn eq(&self, other: &Self) -> bool { · line 119

Quoted 6 lines
rust/kernel/str.rs +3 -0
@@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool {
     }
 }
 
+impl<Idx> Index<Idx> for BStr
+where
+    Idx: core::slice::SliceIndex<[u8], Output = [u8]>,

I think I'd prefer

Quoted 3 lines
Quoted 1 line
	[T]: Index<Idx>,

Is that equivalent?

Quoted 9 lines

Sorry, I meant [u8]: Index<Idx>. This makes more semantic sense that "what ever can index a byte slice, it can also index BStr". This is also how our CStr and the array primitive type implements its Index operation.

They should be equivalent as libcore does

	impl<T, I> Index<I> for [T] where I: SliceIndex<[T]> { ... }

What I originally wrote is Idx must be usable as an index for [u8], yielding [u8] when indexing.

The new one you suggest, I parse as [u8] should be indexable by Idx. This is less info. The compiler will also complain about the missing info:

error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/module-params/rust/kernel/str.rs:141:26

    |
141 |         BStr::from_bytes(&self.0[index])
    |         ---------------- ^^^^^^^^^^^^^^ expected `&[u8]`, found `&<[u8] as Index<Idx>>::Output`
    |         |
    |         arguments to this function are incorrect
    |

= note: expected reference &[u8]
found reference &<[u8] as Index<Idx>>::Output
= help: consider constraining the associated type <[u8] as Index<Idx>>::Output to [u8]

Quoted 8 lines
Quoted 6 lines

If I constrain the output it's all fine again:

    [u8]: Index<Idx, Output = [u8]>,

But as I said, I don't think it matters which direction we put this?

I think it's better to depend on Index compared to SliceIndex.

I am curious for what reason?

Best regards,
Andreas Hindborg

author reviewer
#9 lore raw

PATCH v6 3/6 rust: str: implement `AsRef<BStr>` for `[u8]` and `BStr`

In reply to Andreas Hindborg

Implement AsRef<BStr> for [u8] and BStr so these can be used interchangeably for operations on BStr.

---
 rust/kernel/str.rs | 12 ++++++++++++
 1 file changed, 12 insertions(+)
rust/kernel/str.rs +12 -0
index 1eb945bed77d6..389341455b962 100644
@@ -125,6 +125,18 @@ fn index(&self, index: Idx) -> &Self::Output {
     }
 }
 
+impl AsRef<BStr> for [u8] {
+    fn as_ref(&self) -> &BStr {
+        BStr::from_bytes(self)
+    }
+}
+
+impl AsRef<BStr> for BStr {
+    fn as_ref(&self) -> &BStr {
+        self
+    }
+}
+
 /// Creates a new [`BStr`] from a string literal.
 ///
 /// `b_str!` converts the supplied string literal to byte string, so non-ASCII
Signature · 1 line
2.47.0
author reviewer
#10 lore raw

PATCH v6 4/6 rust: str: implement `strip_prefix` for `BStr`

In reply to Andreas Hindborg

Implement strip_prefix for BStr by deferring to slice::strip_prefix on the underlying &[u8].

---

It is also possible to get this method by implementing core::slice::SlicePattern for BStr. SlicePattern is unstable, so this seems more reasonable.

---
 rust/kernel/str.rs | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
rust/kernel/str.rs +16 -0
index 389341455b962..c102adac32757 100644
@@ -31,6 +31,22 @@ pub const fn from_bytes(bytes: &[u8]) -> &Self {
         // SAFETY: `BStr` is transparent to `[u8]`.
         unsafe { &*(bytes as *const [u8] as *const BStr) }
     }
+
+    /// Strip a prefix from `self`. Delegates to [`slice::strip_prefix`].
+    ///
+    /// # Example
+    /// ```
+    /// use kernel::b_str;
+    /// assert_eq!(Some(b_str!("bar")), b_str!("foobar").strip_prefix(b_str!("foo")));
+    /// assert_eq!(None, b_str!("foobar").strip_prefix(b_str!("bar")));
+    /// assert_eq!(Some(b_str!("foobar")), b_str!("foobar").strip_prefix(b_str!("")));
+    /// assert_eq!(Some(b_str!("")), b_str!("foobar").strip_prefix(b_str!("foobar")));
+    /// ```
+    pub fn strip_prefix(&self, pattern: impl AsRef<Self>) -> Option<&BStr> {
+        self.deref()
+            .strip_prefix(pattern.as_ref().deref())
+            .map(Self::from_bytes)
+    }
 }
 
 impl fmt::Display for BStr {
Signature · 1 line
2.47.0
author reviewer
#11 lore raw

PATCH v6 5/6 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 | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
rust/kernel/str.rs +111 -0
index c102adac32757..192cd0ff5974f 100644
@@ -945,3 +945,114 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+pub mod parse_int {
+    //! Integer parsing functions for parsing signed and unsigned integers
+    //! potentially prefixed with `0x`, `0o`, or `0b`.
+
+    use crate::alloc::flags;
+    use crate::prelude::*;
+    use crate::str::BStr;
+    use core::ops::Deref;
+
+    /// Trait that allows parsing a [`&BStr`] to an integer with a radix.
+    ///
+    /// [`&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 trait FromStrRadix: Sized {
+        /// Parse `src` to `Self` using radix `radix`.
+        fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error>;
+    }
+
+    /// 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', ..] => (16, &src[2..]),
+            [b'0', b'o' | b'O', ..] => (8, &src[2..]),
+            [b'0', b'b' | b'B', ..] => (2, &src[2..]),
+            [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://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtol
+    /// [`kstrtoul()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtoul
+    ///
+    /// # Example
+    /// ```
+    /// use kernel::str::parse_int::ParseInt;
+    /// use kernel::b_str;
+    ///
+    /// assert_eq!(Ok(0), 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(127), i8::from_str(b_str!("127")));
+    /// assert!(i8::from_str(b_str!("128")).is_err());
+    /// assert_eq!(Ok(-128), i8::from_str(b_str!("-128")));
+    /// assert!(i8::from_str(b_str!("-129")).is_err());
+    /// assert_eq!(Ok(255), u8::from_str(b_str!("255")));
+    /// assert!(u8::from_str(b_str!("256")).is_err());
+    /// ```
+    pub trait ParseInt: FromStrRadix {
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.iter().next() {
+                None => Err(EINVAL),
+                Some(sign @ b'-') | Some(sign @ b'+') => {
+                    let (radix, digits) = strip_radix(BStr::from_bytes(&src[1..]));
+                    let mut n_digits: KVec<u8> =
+                        KVec::with_capacity(digits.len() + 1, flags::GFP_KERNEL)?;
+                    n_digits.push(*sign, flags::GFP_KERNEL)?;
+                    n_digits.extend_from_slice(digits, flags::GFP_KERNEL)?;
+                    Self::from_str_radix(BStr::from_bytes(&n_digits), radix).map_err(|_| EINVAL)
+                }
+                Some(_) => {
+                    let (radix, digits) = strip_radix(src);
+                    Self::from_str_radix(digits, radix).map_err(|_| EINVAL)
+                }
+            }
+        }
+    }
+
+    macro_rules! impl_parse_int {
+        ($ty:ty) => {
+            impl FromStrRadix for $ty {
+                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)
+                }
+            }
+
+            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.0
reviewer
#12 lore raw

Re: [PATCH v6 5/6] rust: str: add radix prefixed integer parsing functions

Quoted 32 lines · On Tue, 11 Feb 2025 16:57:39 +0100 Andreas Hindborg <[email protected]>…

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 | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
rust/kernel/str.rs +15 -0
index c102adac32757..192cd0ff5974f 100644
@@ -945,3 +945,114 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+pub mod parse_int {
+    //! Integer parsing functions for parsing signed and unsigned integers
+    //! potentially prefixed with `0x`, `0o`, or `0b`.
+
+    use crate::alloc::flags;
+    use crate::prelude::*;
+    use crate::str::BStr;
+    use core::ops::Deref;
+
+    /// Trait that allows parsing a [`&BStr`] to an integer with a radix.
+    ///
+    /// [`&BStr`]: kernel::str::BStr
+    // This is required because the `from_str_radix` function on the primitive
+    // integer types is not part of any trait.

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+    pub trait FromStrRadix: Sized {
+        /// Parse `src` to `Self` using radix `radix`.
+        fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error>;
+    }
+
+    /// 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', ..] => (16, &src[2..]),

This can be written as

	[b'0', b'x' | b'X', rest @ ..] => (16, rest),

to avoid manual indexing. Same for o and b below.

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

Quoted 3 lines
rust/kernel/str.rs +3 -0
+            [b'0', b'o' | b'O', ..] => (8, &src[2..]),
+            [b'0', b'b' | b'B', ..] => (2, &src[2..]),
+            [b'0', ..] => (8, src),

Perhaps add a comment saying that this isn't using src[1..] so 0 can be parsed.

Quoted 39 lines
rust/kernel/str.rs +39 -0
+            _ => (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://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtol
+    /// [`kstrtoul()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtoul
+    ///
+    /// # Example
+    /// ```
+    /// use kernel::str::parse_int::ParseInt;
+    /// use kernel::b_str;
+    ///
+    /// assert_eq!(Ok(0), 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(127), i8::from_str(b_str!("127")));
+    /// assert!(i8::from_str(b_str!("128")).is_err());
+    /// assert_eq!(Ok(-128), i8::from_str(b_str!("-128")));
+    /// assert!(i8::from_str(b_str!("-129")).is_err());
+    /// assert_eq!(Ok(255), u8::from_str(b_str!("255")));
+    /// assert!(u8::from_str(b_str!("256")).is_err());
+    /// ```
+    pub trait ParseInt: FromStrRadix {

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.iter().next() {
+                None => Err(EINVAL),
+                Some(sign @ b'-') | Some(sign @ b'+') => {
+                    let (radix, digits) = strip_radix(BStr::from_bytes(&src[1..]));
+                    let mut n_digits: KVec<u8> =
+                        KVec::with_capacity(digits.len() + 1, flags::GFP_KERNEL)?;
+                    n_digits.push(*sign, flags::GFP_KERNEL)?;
+                    n_digits.extend_from_slice(digits, flags::GFP_KERNEL)?;

I think my comment from a previous series saying that this shouldn't need allocation is not addressed.

Quoted 35 lines
rust/kernel/str.rs +34 -0
+                    Self::from_str_radix(BStr::from_bytes(&n_digits), radix).map_err(|_| EINVAL)
+                }
+                Some(_) => {
+                    let (radix, digits) = strip_radix(src);
+                    Self::from_str_radix(digits, radix).map_err(|_| EINVAL)
+                }
+            }
+        }
+    }
+
+    macro_rules! impl_parse_int {
+        ($ty:ty) => {
+            impl FromStrRadix for $ty {
+                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)
+                }
+            }
+
+            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);
+}
author reviewer
#13 lore raw

Re: [PATCH v6 5/6] rust: str: add radix prefixed integer parsing functions

Quoted 48 lines · Gary Guo
Quoted 32 lines · On Tue, 11 Feb 2025 16:57:39 +0100 Andreas Hindborg <[email protected]>…

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 | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
rust/kernel/str.rs +15 -0
index c102adac32757..192cd0ff5974f 100644
@@ -945,3 +945,114 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+pub mod parse_int {
+    //! Integer parsing functions for parsing signed and unsigned integers
+    //! potentially prefixed with `0x`, `0o`, or `0b`.
+
+    use crate::alloc::flags;
+    use crate::prelude::*;
+    use crate::str::BStr;
+    use core::ops::Deref;
+
+    /// Trait that allows parsing a [`&BStr`] to an integer with a radix.
+    ///
+    /// [`&BStr`]: kernel::str::BStr
+    // This is required because the `from_str_radix` function on the primitive
+    // integer types is not part of any trait.

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+    pub trait FromStrRadix: Sized {
+        /// Parse `src` to `Self` using radix `radix`.
+        fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error>;
+    }
+
+    /// 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', ..] => (16, &src[2..]),

This can be written as

Quoted 3 lines
	[b'0', b'x' | b'X', rest @ ..] => (16, rest),

to avoid manual indexing. Same for o and b below.

error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/module-params/rust/kernel/str.rs:972:52

    |
972 |             [b'0', b'x' | b'X', rest @ ..] => (16, rest),
    |                                                    ^^^^ expected `&BStr`, found `&[u8]`
    |

= note: expected reference &BStr
found reference &[u8]

But I guess I could use the new AsRef impl. Or is it more idiomatic to implement From<&[u8]> for &BStr and go with rest.into()?

Quoted 7 lines

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

Quoted 4 lines
rust/kernel/str.rs +3 -0
+            [b'0', b'o' | b'O', ..] => (8, &src[2..]),
+            [b'0', b'b' | b'B', ..] => (2, &src[2..]),
+            [b'0', ..] => (8, src),

Perhaps add a comment saying that this isn't using src[1..] so 0 can be parsed.

Good idea.

Quoted 51 lines
Quoted 40 lines
rust/kernel/str.rs +39 -0
+            _ => (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://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtol
+    /// [`kstrtoul()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtoul
+    ///
+    /// # Example
+    /// ```
+    /// use kernel::str::parse_int::ParseInt;
+    /// use kernel::b_str;
+    ///
+    /// assert_eq!(Ok(0), 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(127), i8::from_str(b_str!("127")));
+    /// assert!(i8::from_str(b_str!("128")).is_err());
+    /// assert_eq!(Ok(-128), i8::from_str(b_str!("-128")));
+    /// assert!(i8::from_str(b_str!("-129")).is_err());
+    /// assert_eq!(Ok(255), u8::from_str(b_str!("255")));
+    /// assert!(u8::from_str(b_str!("256")).is_err());
+    /// ```
+    pub trait ParseInt: FromStrRadix {

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.iter().next() {
+                None => Err(EINVAL),
+                Some(sign @ b'-') | Some(sign @ b'+') => {
+                    let (radix, digits) = strip_radix(BStr::from_bytes(&src[1..]));
+                    let mut n_digits: KVec<u8> =
+                        KVec::with_capacity(digits.len() + 1, flags::GFP_KERNEL)?;
+                    n_digits.push(*sign, flags::GFP_KERNEL)?;
+                    n_digits.extend_from_slice(digits, flags::GFP_KERNEL)?;
Quoted 2 lines

I think my comment from a previous series saying that this shouldn't need allocation is not addressed.

Thanks for noticing. This is the discussion from v4:

Quoted 5 lines
Quoted 4 lines

I don't think we should allocate for parsing. This can trivially be a non-allocating. Just check that the next byte is an ASCII digit (reject if so, in case people give multiple signs), and then from_str_radix and return as is or use checked_neg.

Quoted 8 lines

The issue with that approach is that 2s complement signed integer types of width b can assume values from -2^(b-1) to (2^(b-1))-1. We would reject the value -2^(b-1) when trying to parse as 2^(b-1).

We could parse into an unsigned type, but it gets kind of clunky.

Another option is to stop relying on from_str_radix from core and roll our own that takes sign as a separate function argument.

What is your take on that?

Best regards,
Andreas Hindborg

reviewer
#14 lore raw

Re: [PATCH v6 5/6] rust: str: add radix prefixed integer parsing functions

Quoted 60 lines · On Tue, 11 Feb 2025 21:13:10 +0100 Andreas Hindborg <[email protected]>…
Quoted 48 lines · Gary Guo
Quoted 32 lines · On Tue, 11 Feb 2025 16:57:39 +0100 Andreas Hindborg <[email protected]>…

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 | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
rust/kernel/str.rs +15 -0
index c102adac32757..192cd0ff5974f 100644
@@ -945,3 +945,114 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+pub mod parse_int {
+    //! Integer parsing functions for parsing signed and unsigned integers
+    //! potentially prefixed with `0x`, `0o`, or `0b`.
+
+    use crate::alloc::flags;
+    use crate::prelude::*;
+    use crate::str::BStr;
+    use core::ops::Deref;
+
+    /// Trait that allows parsing a [`&BStr`] to an integer with a radix.
+    ///
+    /// [`&BStr`]: kernel::str::BStr
+    // This is required because the `from_str_radix` function on the primitive
+    // integer types is not part of any trait.

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+    pub trait FromStrRadix: Sized {
+        /// Parse `src` to `Self` using radix `radix`.
+        fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error>;
+    }
+
+    /// 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', ..] => (16, &src[2..]),  

This can be written as

Quoted 3 lines
	[b'0', b'x' | b'X', rest @ ..] => (16, rest),

to avoid manual indexing. Same for o and b below.

error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/module-params/rust/kernel/str.rs:972:52

    |
972 |             [b'0', b'x' | b'X', rest @ ..] => (16, rest),
    |                                                    ^^^^ expected `&BStr`, found `&[u8]`
    |
Quoted 5 lines

= note: expected reference &BStr
found reference &[u8]

But I guess I could use the new AsRef impl. Or is it more idiomatic to implement From<&[u8]> for &BStr and go with rest.into()?

Ah, alright, I missed that this function is operating on BStr instead of slice. Keeping the current form is fine then.

Quoted 28 lines
Quoted 8 lines

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

Quoted 5 lines
rust/kernel/str.rs +3 -0
+            [b'0', b'o' | b'O', ..] => (8, &src[2..]),
+            [b'0', b'b' | b'B', ..] => (2, &src[2..]),
+            [b'0', ..] => (8, src),  

Perhaps add a comment saying that this isn't using src[1..] so 0 can be parsed.

Good idea.

Quoted 17 lines
Quoted 16 lines
rust/kernel/str.rs +14 -0
+            _ => (10, src),
+        }
+    }
 
+    pub trait ParseInt: FromStrRadix {
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.iter().next() {
+                None => Err(EINVAL),
+                Some(sign @ b'-') | Some(sign @ b'+') => {
+                    let (radix, digits) = strip_radix(BStr::from_bytes(&src[1..]));
+                    let mut n_digits: KVec<u8> =
+                        KVec::with_capacity(digits.len() + 1, flags::GFP_KERNEL)?;
+                    n_digits.push(*sign, flags::GFP_KERNEL)?;
+                    n_digits.extend_from_slice(digits, flags::GFP_KERNEL)?;  
Quoted 15 lines
Quoted 2 lines

I think my comment from a previous series saying that this shouldn't need allocation is not addressed.

Thanks for noticing. This is the discussion from v4:

Quoted 10 lines
Quoted 4 lines

I don't think we should allocate for parsing. This can trivially be a non-allocating. Just check that the next byte is an ASCII digit (reject if so, in case people give multiple signs), and then from_str_radix and return as is or use checked_neg.

The issue with that approach is that 2s complement signed integer types of width b can assume values from -2^(b-1) to (2^(b-1))-1. We would reject the value -2^(b-1) when trying to parse as 2^(b-1).

We could parse into an unsigned type, but it gets kind of clunky.

I would say either that or just call into kstrto* family.

Best,
Gary

Quoted 11 lines
Quoted 3 lines

Another option is to stop relying on from_str_radix from core and roll our own that takes sign as a separate function argument.

What is your take on that?

Best regards,
Andreas Hindborg

author reviewer
#15 lore raw

Re: [PATCH v6 5/6] rust: str: add radix prefixed integer parsing functions

Quoted 110 lines · Gary Guo
Quoted 60 lines · On Tue, 11 Feb 2025 21:13:10 +0100 Andreas Hindborg <[email protected]>…
Quoted 48 lines · Gary Guo
Quoted 32 lines · On Tue, 11 Feb 2025 16:57:39 +0100 Andreas Hindborg <[email protected]>…

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 | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
rust/kernel/str.rs +15 -0
index c102adac32757..192cd0ff5974f 100644
@@ -945,3 +945,114 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 macro_rules! fmt {
     ($($f:tt)*) => ( core::format_args!($($f)*) )
 }
+
+pub mod parse_int {
+    //! Integer parsing functions for parsing signed and unsigned integers
+    //! potentially prefixed with `0x`, `0o`, or `0b`.
+
+    use crate::alloc::flags;
+    use crate::prelude::*;
+    use crate::str::BStr;
+    use core::ops::Deref;
+
+    /// Trait that allows parsing a [`&BStr`] to an integer with a radix.
+    ///
+    /// [`&BStr`]: kernel::str::BStr
+    // This is required because the `from_str_radix` function on the primitive
+    // integer types is not part of any trait.

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+    pub trait FromStrRadix: Sized {
+        /// Parse `src` to `Self` using radix `radix`.
+        fn from_str_radix(src: &BStr, radix: u32) -> Result<Self, crate::error::Error>;
+    }
+
+    /// 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', ..] => (16, &src[2..]),

This can be written as

Quoted 3 lines
	[b'0', b'x' | b'X', rest @ ..] => (16, rest),

to avoid manual indexing. Same for o and b below.

error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/module-params/rust/kernel/str.rs:972:52

    |
972 |             [b'0', b'x' | b'X', rest @ ..] => (16, rest),
    |                                                    ^^^^ expected `&BStr`, found `&[u8]`
    |
Quoted 5 lines

= note: expected reference &BStr
found reference &[u8]

But I guess I could use the new AsRef impl. Or is it more idiomatic to implement From<&[u8]> for &BStr and go with rest.into()?

Ah, alright, I missed that this function is operating on BStr instead of slice. Keeping the current form is fine then.

Quoted 38 lines
Quoted 8 lines

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

Quoted 5 lines
rust/kernel/str.rs +3 -0
+            [b'0', b'o' | b'O', ..] => (8, &src[2..]),
+            [b'0', b'b' | b'B', ..] => (2, &src[2..]),
+            [b'0', ..] => (8, src),

Perhaps add a comment saying that this isn't using src[1..] so 0 can be parsed.

Good idea.

Quoted 17 lines
Quoted 6 lines
rust/kernel/str.rs +4 -0
+            _ => (10, src),
+        }
+    }
 
+    pub trait ParseInt: FromStrRadix {

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

Quoted 10 lines
rust/kernel/str.rs +10 -0
+        /// Parse a string according to the description in [`Self`].
+        fn from_str(src: &BStr) -> Result<Self> {
+            match src.iter().next() {
+                None => Err(EINVAL),
+                Some(sign @ b'-') | Some(sign @ b'+') => {
+                    let (radix, digits) = strip_radix(BStr::from_bytes(&src[1..]));
+                    let mut n_digits: KVec<u8> =
+                        KVec::with_capacity(digits.len() + 1, flags::GFP_KERNEL)?;
+                    n_digits.push(*sign, flags::GFP_KERNEL)?;
+                    n_digits.extend_from_slice(digits, flags::GFP_KERNEL)?;
Quoted 2 lines

I think my comment from a previous series saying that this shouldn't need allocation is not addressed.

Thanks for noticing. This is the discussion from v4:

Quoted 5 lines
Quoted 4 lines

I don't think we should allocate for parsing. This can trivially be a non-allocating. Just check that the next byte is an ASCII digit (reject if so, in case people give multiple signs), and then from_str_radix and return as is or use checked_neg.

Quoted 7 lines
Quoted 5 lines
Quoted 5 lines

The issue with that approach is that 2s complement signed integer types of width b can assume values from -2^(b-1) to (2^(b-1))-1. We would reject the value -2^(b-1) when trying to parse as 2^(b-1).

We could parse into an unsigned type, but it gets kind of clunky.

I would say either that or just call into kstrto* family.

Right. I'll rather parse into i128 than call into that.

Best regards,
Andreas Hindborg

author reviewer
#16 lore raw

PATCH v6 6/6 rust: add parameter support to the `module!` macro

In reply to Andreas Hindborg

This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without sysfs support.

---
 rust/kernel/lib.rs           |   1 +
 rust/kernel/module_param.rs  | 225 +++++++++++++++++++++++++++++++++++++++++++
 rust/macros/helpers.rs       |  25 +++++
 rust/macros/lib.rs           |  31 ++++++
 rust/macros/module.rs        | 191 ++++++++++++++++++++++++++++++++----
 samples/rust/rust_minimal.rs |  10 ++
 6 files changed, 465 insertions(+), 18 deletions(-)
rust/kernel/lib.rs +1 -0
index ee48cf68c3111..3d3b0d346b248 100644
@@ -57,6 +57,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 +225 -0

225 lines not on this page · raw message

rust/macros/helpers.rs +25 -0
index 563dcd2b7ace5..ffc9f0cccddc8 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())
@@ -107,6 +118,20 @@ pub(crate) struct Generics {
     pub(crate) ty_generics: Vec<TokenTree>,
 }
 
+/// 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
+}
+
 /// Parses the given `TokenStream` into `Generics` and the rest.
 ///
 /// The generics are not present in the rest, but a where clause might remain.
rust/macros/lib.rs +31 -0
index d61bc6a56425e..2778292f8cee1 100644
@@ -24,6 +24,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
@@ -40,6 +64,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);
@@ -48,6 +78,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 +173 -18

277 lines not on this page · raw message

samples/rust/rust_minimal.rs +10 -0
index 4aaf117bf8e3c..d999a77c6eb9a 100644
@@ -10,6 +10,12 @@
     author: "Rust for Linux Contributors",
     description: "Rust minimal sample",
     license: "GPL",
+    params: {
+        test_parameter: i64 {
+            default: 1,
+            description: "This parameter has a default of 1",
+        },
+    },
 }
 
 struct RustMinimal {
@@ -20,6 +26,10 @@ impl kernel::Module for RustMinimal {
     fn init(_module: &'static ThisModule) -> Result<Self> {
         pr_info!("Rust minimal sample (init)\n");
         pr_info!("Am I built-in? {}\n", !cfg!(MODULE));
+        pr_info!(
+            "My parameter: {}\n",
+            *module_parameters::test_parameter.get()
+        );
 
         let mut numbers = KVec::new();
         numbers.push(72, GFP_KERNEL)?;
Signature · 1 line
2.47.0
maintainer Acked-by on v6 6/6
#17 lore raw

Re: [PATCH v6 6/6] rust: add parameter support to the `module!` macro

Quoted 5 lines · Andreas Hindborg

This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without sysfs support.

For what it's worth, this looks reasonable to me from the modules perspective.

Signature · 2 lines
Thanks,
Petr