public inbox for linux-modules@vger.kernel.org
 help / color / mirror / Atom feed
From: Matthew Wood <thepacketgeek@gmail.com>
To: Miguel Ojeda <ojeda@kernel.org>,
	Luis Chamberlain <mcgrof@kernel.org>,
	Petr Pavlu <petr.pavlu@suse.com>,
	Daniel Gomez <da.gomez@kernel.org>,
	Sami Tolvanen <samitolvanen@google.com>
Cc: "Aaron Tomlin" <atomlin@atomlin.com>,
	"Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"David Gow" <davidgow@google.com>,
	"José Expósito" <jose.exposito89@gmail.com>,
	linux-modules@vger.kernel.org, rust-for-linux@vger.kernel.org,
	linux-kernel@vger.kernel.org
Subject: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Date: Thu, 26 Feb 2026 15:47:28 -0800	[thread overview]
Message-ID: <20260226234736.428341-3-thepacketgeek@gmail.com> (raw)
In-Reply-To: <20260226234736.428341-1-thepacketgeek@gmail.com>

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


  parent reply	other threads:[~2026-02-26 23:47 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-02-26 23:47 [PATCH 0/8] rust: module parameter extensions Matthew Wood
2026-02-26 23:47 ` [PATCH 1/8] rust: module_param: add StringParam type for C string parameters Matthew Wood
2026-02-28  1:32   ` Miguel Ojeda
2026-03-05 12:47   ` Petr Pavlu
2026-02-26 23:47 ` Matthew Wood [this message]
2026-03-04  8:13   ` [PATCH 2/8] rust: module_param: wire StringParam into the module! macro Petr Pavlu
2026-03-09  2:24     ` Matthew Wood
2026-03-06 19:27   ` Sami Tolvanen
2026-03-09  2:27     ` Matthew Wood
2026-02-26 23:47 ` [PATCH 3/8] samples: rust_minimal: demonstrate string module parameter Matthew Wood
2026-02-26 23:47 ` [PATCH 4/8] rust: module_param: add ObsKernelParam type Matthew Wood
2026-02-26 23:47 ` [PATCH 5/8] rust: module_param: add from_setup_arg() to ModuleParam trait Matthew Wood
2026-02-26 23:47 ` [PATCH 6/8] rust: macros: add early_param support to module! macro Matthew Wood
2026-03-06 17:22   ` Petr Pavlu
2026-02-26 23:47 ` [PATCH 7/8] samples: rust_minimal: demonstrate early_param usage Matthew Wood
2026-02-26 23:47 ` [PATCH 8/8] rust: macros: add configurable initcall levels to module! macro Matthew Wood
2026-02-27 13:27 ` [PATCH 0/8] rust: module parameter extensions Matthew Wood

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260226234736.428341-3-thepacketgeek@gmail.com \
    --to=thepacketgeek@gmail.com \
    --cc=a.hindborg@kernel.org \
    --cc=aliceryhl@google.com \
    --cc=atomlin@atomlin.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=da.gomez@kernel.org \
    --cc=dakr@kernel.org \
    --cc=davidgow@google.com \
    --cc=gary@garyguo.net \
    --cc=jose.exposito89@gmail.com \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-modules@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=mcgrof@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=petr.pavlu@suse.com \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=samitolvanen@google.com \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox