[PATCH 2/8] rust: module_param: wire StringParam into the module! macro

Matthew Wood posted 8 patches 1 month, 1 week ago
[PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Posted by Matthew Wood 1 month, 1 week ago
Add support for `string` as a parameter type in the module! macro.

On the runtime side, add:
  - set_string_param(): an extern "C" callback matching the
    kernel_param_ops::set signature that stores the raw C string
    pointer directly into the SetOnce<StringParam> container, avoiding
    an unnecessary copy-and-parse round-trip.
  - PARAM_OPS_STRING: a static kernel_param_ops that uses
    set_string_param as its setter.
  - ModuleParam impl for StringParam with try_from_param_arg()
    returning -EINVAL, since string parameters are populated
    exclusively through the kernel's set callback.

On the macro side:
  - Change the Parameter::ptype field from Ident to syn::Type to
    support path-qualified types.
  - Recognize the `string` shorthand and resolve it to the fully
    qualified ::kernel::module_param::StringParam type during code
    generation.
  - Wrap string default values with StringParam::from_c_str(c_str!(...))
    to produce a compile-time CStr-backed default.
  - Route `string` to PARAM_OPS_STRING in param_ops_path().

Signed-off-by: Matthew Wood <thepacketgeek@gmail.com>
---
 rust/kernel/module_param.rs | 48 +++++++++++++++++++++++++++++++++++++
 rust/macros/module.rs       | 42 +++++++++++++++++++++++++-------
 2 files changed, 81 insertions(+), 9 deletions(-)

diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs
index 80fe8643c0ab..67ff6f2ea9c2 100644
--- a/rust/kernel/module_param.rs
+++ b/rust/kernel/module_param.rs
@@ -86,6 +86,36 @@ pub trait ModuleParam: Sized + Copy {
     })
 }
 
+/// Set a string module parameter from a string.
+///
+/// Similar to [`set_param`] but for [`StringParam`].
+///
+/// # Safety
+///
+/// Same requirements as [`set_param`].
+unsafe extern "C" fn set_string_param(
+    val: *const c_char,
+    param: *const bindings::kernel_param,
+) -> c_int {
+    if val.is_null() {
+        crate::pr_warn!("Null pointer passed to `module_param::set_string_param`");
+        return EINVAL.to_errno();
+    }
+
+    crate::error::from_result(|| {
+        // SAFETY: val points to a valid C string from the kernel.
+        let cstr_param = unsafe { StringParam::from_ptr(val) };
+
+        // SAFETY: By function safety requirements, param.arg points to our SetOnce<StringParam>.
+        let container = unsafe { &*((*param).__bindgen_anon_1.arg.cast::<SetOnce<StringParam>>()) };
+
+        container
+            .populate(cstr_param)
+            .then_some(0)
+            .ok_or(kernel::error::code::EEXIST)
+    })
+}
+
 macro_rules! impl_int_module_param {
     ($ty:ident) => {
         impl ModuleParam for $ty {
@@ -175,6 +205,15 @@ pub fn as_bytes(&self) -> Option<&[u8]> {
 unsafe impl Send for StringParam {}
 unsafe impl Sync for StringParam {}
 
+impl ModuleParam for StringParam {
+    fn try_from_param_arg(_arg: &BStr) -> Result<Self> {
+        // For StringParam, we don't parse here - the kernel's set callback
+        // directly stores the pointer. This method should not be called
+        // when using PARAM_OPS_STRING.
+        Err(EINVAL)
+    }
+}
+
 /// A wrapper for kernel parameters.
 ///
 /// This type is instantiated by the [`module!`] macro when module parameters are
@@ -249,3 +288,12 @@ macro_rules! make_param_ops {
 make_param_ops!(PARAM_OPS_U64, u64);
 make_param_ops!(PARAM_OPS_ISIZE, isize);
 make_param_ops!(PARAM_OPS_USIZE, usize);
+
+/// Parameter ops for string parameters.
+#[doc(hidden)]
+pub static PARAM_OPS_STRING: bindings::kernel_param_ops = bindings::kernel_param_ops {
+    flags: 0,
+    set: Some(set_string_param),
+    get: None,
+    free: None,
+};
diff --git a/rust/macros/module.rs b/rust/macros/module.rs
index e16298e520c7..0d76743741fb 100644
--- a/rust/macros/module.rs
+++ b/rust/macros/module.rs
@@ -8,7 +8,8 @@
 };
 use quote::{
     format_ident,
-    quote, //
+    quote,
+    ToTokens, //
 };
 use syn::{
     braced,
@@ -120,13 +121,15 @@ fn emit_params(&mut self, info: &ModuleInfo) {
 
         for param in params {
             let param_name_str = param.name.to_string();
-            let param_type_str = param.ptype.to_string();
+            let param_type_str = param.ptype.to_token_stream().to_string();
+            // Clean up the type string for modinfo (remove spaces around ::)
+            let param_type_clean = param_type_str.replace(" ", "");
 
             let ops = param_ops_path(&param_type_str);
 
             // Note: The spelling of these fields is dictated by the user space
             // tool `modinfo`.
-            self.emit_param("parmtype", &param_name_str, &param_type_str);
+            self.emit_param("parmtype", &param_name_str, &param_type_clean);
             self.emit_param("parm", &param_name_str, &param.description.value());
 
             let static_name = format_ident!("__{}_{}_struct", self.module, param.name);
@@ -137,14 +140,32 @@ fn emit_params(&mut self, info: &ModuleInfo) {
                     .expect("name contains NUL-terminator");
 
             let param_name = &param.name;
-            let param_type = &param.ptype;
             let param_default = &param.default;
 
+            // `string` is a shorthand for `StringParam` in the macro — resolve to
+            // the real type for code generation.
+            let is_str_param = param_type_str == "string";
+            let actual_type: Type = if is_str_param {
+                parse_quote!(::kernel::module_param::StringParam)
+            } else {
+                param.ptype.clone()
+            };
+
+            // For `string` params the default is always a string literal which
+            // gets wrapped with StringParam::from_c_str(kernel::c_str!(...)).
+            let default_expr = if is_str_param {
+                quote! {
+                    ::kernel::module_param::StringParam::from_c_str(::kernel::c_str!(#param_default))
+                }
+            } else {
+                quote!(#param_default)
+            };
+
             self.param_ts.extend(quote! {
                 #[allow(non_upper_case_globals)]
                 pub(crate) static #param_name:
-                    ::kernel::module_param::ModuleParamAccess<#param_type> =
-                        ::kernel::module_param::ModuleParamAccess::new(#param_default);
+                    ::kernel::module_param::ModuleParamAccess<#actual_type> =
+                        ::kernel::module_param::ModuleParamAccess::new(#default_expr);
 
                 const _: () = {
                     #[allow(non_upper_case_globals)]
@@ -186,7 +207,9 @@ fn emit_params(&mut self, info: &ModuleInfo) {
 }
 
 fn param_ops_path(param_type: &str) -> Path {
-    match param_type {
+    let type_name = param_type.rsplit("::").next().unwrap_or(param_type).trim();
+
+    match type_name {
         "i8" => parse_quote!(::kernel::module_param::PARAM_OPS_I8),
         "u8" => parse_quote!(::kernel::module_param::PARAM_OPS_U8),
         "i16" => parse_quote!(::kernel::module_param::PARAM_OPS_I16),
@@ -197,6 +220,7 @@ fn param_ops_path(param_type: &str) -> Path {
         "u64" => parse_quote!(::kernel::module_param::PARAM_OPS_U64),
         "isize" => parse_quote!(::kernel::module_param::PARAM_OPS_ISIZE),
         "usize" => parse_quote!(::kernel::module_param::PARAM_OPS_USIZE),
+        "string" => parse_quote!(::kernel::module_param::PARAM_OPS_STRING),
         t => panic!("Unsupported parameter type {}", t),
     }
 }
@@ -340,7 +364,7 @@ macro_rules! parse_ordered_fields {
 
 struct Parameter {
     name: Ident,
-    ptype: Ident,
+    ptype: Type,
     default: Expr,
     description: LitStr,
 }
@@ -349,7 +373,7 @@ impl Parse for Parameter {
     fn parse(input: ParseStream<'_>) -> Result<Self> {
         let name = input.parse()?;
         input.parse::<Token![:]>()?;
-        let ptype = input.parse()?;
+        let ptype: Type = input.parse()?;
 
         let fields;
         braced!(fields in input);
-- 
2.52.0

Re: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Posted by Sami Tolvanen 1 month ago
On Thu, Feb 26, 2026 at 03:47:28PM -0800, Matthew Wood wrote:
> +/// Set a string module parameter from a string.
> +///
> +/// Similar to [`set_param`] but for [`StringParam`].
> +///
> +/// # Safety
> +///
> +/// Same requirements as [`set_param`].
> +unsafe extern "C" fn set_string_param(
> +    val: *const c_char,
> +    param: *const bindings::kernel_param,
> +) -> c_int {
> +    if val.is_null() {
> +        crate::pr_warn!("Null pointer passed to `module_param::set_string_param`");
> +        return EINVAL.to_errno();
> +    }
> +
> +    crate::error::from_result(|| {
> +        // SAFETY: val points to a valid C string from the kernel.
> +        let cstr_param = unsafe { StringParam::from_ptr(val) };
> +
> +        // SAFETY: By function safety requirements, param.arg points to our SetOnce<StringParam>.
> +        let container = unsafe { &*((*param).__bindgen_anon_1.arg.cast::<SetOnce<StringParam>>()) };

I do realize this matches set_param, and there's a good chance I
missed something when reading the macros, but doesn't arg actually
point to ModuleParamAccess<T> here? Since the struct is not repr(C),
isn't the compiler technically speaking allowed to reorder the
fields, which means SetOnce<T> might not actually be at offset 0?

> +
> +        container
> +            .populate(cstr_param)
> +            .then_some(0)
> +            .ok_or(kernel::error::code::EEXIST)

Does this mean the behavior for Rust modules differs from C modules if
the user specifies multiple instances of the same parameter? I believe
we just use the last value of the parameter instead of failing in C.

Sami
Re: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Posted by Matthew Wood 4 weeks, 1 day ago
On Fri, Mar 6, 2026 at 11:28 AM Sami Tolvanen <samitolvanen@google.com> wrote:
>
> On Thu, Feb 26, 2026 at 03:47:28PM -0800, Matthew Wood wrote:
> > +/// Set a string module parameter from a string.
> > +///
> > +/// Similar to [`set_param`] but for [`StringParam`].
> > +///
> > +/// # Safety
> > +///
> > +/// Same requirements as [`set_param`].
> > +unsafe extern "C" fn set_string_param(
> > +    val: *const c_char,
> > +    param: *const bindings::kernel_param,
> > +) -> c_int {
> > +    if val.is_null() {
> > +        crate::pr_warn!("Null pointer passed to `module_param::set_string_param`");
> > +        return EINVAL.to_errno();
> > +    }
> > +
> > +    crate::error::from_result(|| {
> > +        // SAFETY: val points to a valid C string from the kernel.
> > +        let cstr_param = unsafe { StringParam::from_ptr(val) };
> > +
> > +        // SAFETY: By function safety requirements, param.arg points to our SetOnce<StringParam>.
> > +        let container = unsafe { &*((*param).__bindgen_anon_1.arg.cast::<SetOnce<StringParam>>()) };
>
> I do realize this matches set_param, and there's a good chance I
> missed something when reading the macros, but doesn't arg actually
> point to ModuleParamAccess<T> here? Since the struct is not repr(C),
> isn't the compiler technically speaking allowed to reorder the
> fields, which means SetOnce<T> might not actually be at offset 0?
>

Hi Sami,

I appreciate the review! This does seem to be an oversight, I'll try
to figure out the
correct implementation. I agree, `repr(C)` is likely needed here.

> > +
> > +        container
> > +            .populate(cstr_param)
> > +            .then_some(0)
> > +            .ok_or(kernel::error::code::EEXIST)
>
> Does this mean the behavior for Rust modules differs from C modules if
> the user specifies multiple instances of the same parameter? I believe
> we just use the last value of the parameter instead of failing in C.
>
> Sami

Yes, I'll fix that, the implementations should match.

Regards,
Mat
Re: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Posted by Petr Pavlu 1 month ago
On 2/27/26 12:47 AM, Matthew Wood wrote:
> Add support for `string` as a parameter type in the module! macro.
> 
> On the runtime side, add:
>   - set_string_param(): an extern "C" callback matching the
>     kernel_param_ops::set signature that stores the raw C string
>     pointer directly into the SetOnce<StringParam> container, avoiding
>     an unnecessary copy-and-parse round-trip.
>   - PARAM_OPS_STRING: a static kernel_param_ops that uses
>     set_string_param as its setter.
>   - ModuleParam impl for StringParam with try_from_param_arg()
>     returning -EINVAL, since string parameters are populated
>     exclusively through the kernel's set callback.
> 
> On the macro side:
>   - Change the Parameter::ptype field from Ident to syn::Type to
>     support path-qualified types.

Why is it necessary to change the type of Parameter::ptype? My
understanding is that this token can currently be "i8", "u8", ...,
"isize", "usize". Additionally, the value "string" should now be
accepted. When should one use a path-qualified type in this context?

>   - Recognize the `string` shorthand and resolve it to the fully
>     qualified ::kernel::module_param::StringParam type during code
>     generation.
>   - Wrap string default values with StringParam::from_c_str(c_str!(...))
>     to produce a compile-time CStr-backed default.
>   - Route `string` to PARAM_OPS_STRING in param_ops_path().
> 
> Signed-off-by: Matthew Wood <thepacketgeek@gmail.com>
> ---
>  rust/kernel/module_param.rs | 48 +++++++++++++++++++++++++++++++++++++
>  rust/macros/module.rs       | 42 +++++++++++++++++++++++++-------
>  2 files changed, 81 insertions(+), 9 deletions(-)
> 
> diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs
> index 80fe8643c0ab..67ff6f2ea9c2 100644
> --- a/rust/kernel/module_param.rs
> +++ b/rust/kernel/module_param.rs
> @@ -86,6 +86,36 @@ pub trait ModuleParam: Sized + Copy {
>      })
>  }
>  
> +/// Set a string module parameter from a string.
> +///
> +/// Similar to [`set_param`] but for [`StringParam`].
> +///
> +/// # Safety
> +///
> +/// Same requirements as [`set_param`].
> +unsafe extern "C" fn set_string_param(
> +    val: *const c_char,
> +    param: *const bindings::kernel_param,
> +) -> c_int {

The safety comment is somewhat inaccurate because set_param() says that
the input value needs to be valid only for the duration of the call,
whereas set_string_param() and StringParam require it to be valid for
the module's lifetime.

-- 
Thanks,
Petr
Re: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Posted by Matthew Wood 4 weeks, 1 day ago
On Wed, Mar 4, 2026 at 12:13 AM Petr Pavlu <petr.pavlu@suse.com> wrote:
>
> On 2/27/26 12:47 AM, Matthew Wood wrote:
> > Add support for `string` as a parameter type in the module! macro.
> >
> > On the runtime side, add:
> >   - set_string_param(): an extern "C" callback matching the
> >     kernel_param_ops::set signature that stores the raw C string
> >     pointer directly into the SetOnce<StringParam> container, avoiding
> >     an unnecessary copy-and-parse round-trip.
> >   - PARAM_OPS_STRING: a static kernel_param_ops that uses
> >     set_string_param as its setter.
> >   - ModuleParam impl for StringParam with try_from_param_arg()
> >     returning -EINVAL, since string parameters are populated
> >     exclusively through the kernel's set callback.
> >
> > On the macro side:
> >   - Change the Parameter::ptype field from Ident to syn::Type to
> >     support path-qualified types.
>
> Why is it necessary to change the type of Parameter::ptype? My
> understanding is that this token can currently be "i8", "u8", ...,
> "isize", "usize". Additionally, the value "string" should now be
> accepted. When should one use a path-qualified type in this context?
>

Hi Petr,

Thanks for the review! Yes, I believe your point is correct and I will look
at this again. I think I left that after wanting to be able to use the
StringParam
type, but realized that matching on `string` is more ergonomic.

> > +/// Set a string module parameter from a string.
> > +///
> > +/// Similar to [`set_param`] but for [`StringParam`].
> > +///
> > +/// # Safety
> > +///
> > +/// Same requirements as [`set_param`].
> > +unsafe extern "C" fn set_string_param(
> > +    val: *const c_char,
> > +    param: *const bindings::kernel_param,
> > +) -> c_int {
>
> The safety comment is somewhat inaccurate because set_param() says that
> the input value needs to be valid only for the duration of the call,
> whereas set_string_param() and StringParam require it to be valid for
> the module's lifetime.
>

Yes, thank you. After reading these safety comments back I agree they need
to be fixed. Miguel had a similar point as well. I'll update these in v2.

Thank you!
- Mat