rust: module parameter extensions
Subsystems (2)
cover rust: module parameter extensions
This series extends the Rust module! macro with three capabilities that are available to C modules but currently missing from the Rust
abstractions: string parameters, early boot command-line parameters, and configurable initcall levels.
The existing Rust module parameter infrastructure supports integer types (i8..u64, isize, usize) but has no way to accept string values. Additionally, built-in Rust modules cannot register parameters for early boot command-line parsing (__setup / early_param), and all Rust modules are hard-coded to initcall level 6 (device_initcall) with no way to control initialization ordering.
String parameter support (patches 1-3):
Introduce StringParam, a Copy wrapper around *const c_char whose memory is managed by the kernel parameter subsystem. Wire it into the module! macro as the string parameter type with a dedicated kernel_param_ops (PARAM_OPS_STRING) that stores the pointer directly into a SetOnce<StringParam> container. The rust_minimal sample is updated to demonstrate usage.
An earlier implementation of string parameter support was proposed in:
https://github.com/Rust-for-Linux/linux/pull/110/
This series takes a different approach for StringParam by storing the raw C string pointer directly rather than copying the string data, since the kernel guarantees the backing memory remains valid for the module's lifetime. This avoids allocation in the parameter setter and keeps StringParam as a simple Copy type consistent with the existing integer parameter design.
Early boot parameter support (patches 4-7):
Add ObsKernelParam (mirroring the C obs_kernel_param), extend the ModuleParam trait with from_setup_arg() for constructing parameter values from raw __setup callback arguments, and integrate an optional early_param field into the module! macro. When specified, the macro emits a __setup entry in the .init.setup ELF section, gated behind #[cfg(not(MODULE))] since this mechanism is only meaningful for built-in modules.
Configurable initcall levels (patch 8):
Add an optional initcall field to the module! macro that accepts any of the eight standard levels (pure through late). The default remains level 6 (device) so existing modules are unaffected.
Matthew Wood (8):
rust: module_param: add StringParam type for C string parameters
rust: module_param: wire StringParam into the module! macro
samples: rust_minimal: demonstrate string module parameter
rust: module_param: add ObsKernelParam type
rust: module_param: add from_setup_arg() to ModuleParam trait
rust: macros: add early_param support to module! macro
samples: rust_minimal: demonstrate early_param usage
rust: macros: add configurable initcall levels to module! macro
rust/kernel/module_param.rs | 160 +++++++++++++++++++++++++++++++ rust/macros/lib.rs | 9 ++ rust/macros/module.rs | 179 +++++++++++++++++++++++++++++++++-- samples/rust/rust_minimal.rs | 33 ++++++- 4 files changed, 368 insertions(+), 13 deletions(-)
Signature · 1 line
2.52.0
PATCH 1/8 rust: module_param: add StringParam type for C string parameters
Introduce StringParam, a Copy wrapper around *const c_char that represents a string module parameter whose memory is managed by the kernel parameter subsystem.
StringParam provides:
- from_ptr(): construct from a raw C string pointer
- from_c_str(): construct from a static CStr (for compile-time default values)
- null(): construct an unset/empty parameter
- as_cstr() / as_bytes(): safe accessors that return None when the pointer is null
The type is marked Send + Sync because the underlying pointer is effectively 'static for the module's lifetime — the kernel guarantees the string memory remains valid while the module is loaded.
This is a prerequisite for wiring string parameters into the module! macro in subsequent patches.
--- rust/kernel/module_param.rs | 69 +++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)
rust/kernel/module_param.rs +69 -0
@@ -6,6 +6,7 @@use crate ::prelude::*;use crate ::str::BStr ; +use crate ::str::CStr ;use bindings;use kernel::sync::SetOnce ;
@@ -106,6 +107,74 @@ fn try_from_param_arg(arg: &BStr) -> Result<Self> {impl_int_module_param! (isize );impl_int_module_param! (usize ); +/// A module parameter that holds a C string pointer. +/// +/// This type is `Copy` by storing only a raw pointer. The underlying string +/// memory is managed by the kernel's parameter subsystem. +/// +/// # Safety +/// +/// The pointer is only valid while the module is loaded. The kernel ensures +/// the string memory remains valid for the module's lifetime. +#[derive( Copy , Clone )] +#[repr(transparent)] +pub struct StringParam { + ptr: *const c_char , +} + +impl StringParam { +/// Creates a new `StringParam` from a raw pointer. +/// +/// # Safety +/// +/// The pointer must be valid and point to a null-terminated string, +/// or be null for an empty/unset parameter. +pub const unsafe fn from_ptr (ptr: *const c_char ) ->Self { +Self { ptr } + } + +/// Creates a `StringParam` from a static `CStr` reference. +/// +/// Useful for compile-time default values in module parameter declarations. +pub const fn from_c_str (s: &'staticCStr ) ->Self { +Self { + ptr:crate ::str::as_char_ptr_in_const_context (s), + } + } + +/// Creates a null/empty `StringParam`. +pub const fn null () ->Self { +Self { + ptr: core::ptr::null (), + } + } + +/// Returns `true` if the parameter is null/unset. +pub fn is_null (&self) ->bool { + self.ptr.is_null () + } + +/// Returns the string as a `CStr` reference, if set. +pub fn as_cstr (&self) ->Option <&CStr > { +if self.ptr.is_null () { +None + }else { +// SAFETY: pointer validity is checked above +Some (unsafe {CStr ::from_char_ptr (self.ptr) }) + } + } + +/// Returns the string as bytes, if set. +pub fn as_bytes (&self) ->Option <&[u8 ]> { + self.as_cstr ().map (|s| s.to_bytes ()) + } +} + +// SAFETY: The pointer is managed by the kernel and is effectively 'static +// for the module's lifetime. +unsafe impl Send for StringParam {} +unsafe impl Sync for StringParam {} +/// A wrapper for kernel parameters. /// /// This type is instantiated by the [`module!`] macro when module parameters are
Signature · 1 line
2.52.0
Re: [PATCH 1/8] rust: module_param: add StringParam type for C string parameters
Quoted 2 lines · Matthew Wood
+/// This type is
Copyby storing only a raw pointer. The underlying string
Please use intra-doc links where possible/reasonable.
rust/kernel/module_param.rs fn try_from_param_arg(arg: &BStr) -> Result<Self> { · line 121
Quoted 7 lines
rust/kernel/module_param.rs +7
-0+/// # Safety +/// +/// The pointer is only valid while the module is loaded. The kernel ensures +/// the string memory remains valid for the module's lifetime. +#[derive( Copy , Clone )] +#[repr(transparent)] +pub struct StringParam {
A # Safety section for a type? What do you mean here?
I think you may want to establish an invariant instead.
rust/kernel/module_param.rs fn try_from_param_arg(arg: &BStr) -> Result<Self> { · line 163
Quoted 2 lines
rust/kernel/module_param.rs +2
-0+// SAFETY: pointer validity is checked above +Some (unsafe {CStr ::from_char_ptr (self.ptr) })
I assume you mean that the non-null implies the validity, but validity is not really "checked" above. That is why you probably want to have a proper invariant in the type, so that you can invoke it here etc.
Quoted 1 line
+unsafe impl Sync for StringParam {}
This is missing a // SAFETY: comment -- please double-check CLIPPY=1 passes clean.
Cheers,
Miguel
Petr Pavlu
maintainerRe: [PATCH 1/8] rust: module_param: add StringParam type for C string parameters
In reply to Matthew WoodQuoted 12 lines · Matthew Wood
Introduce StringParam, a Copy wrapper around *const
c_charthat represents a string module parameter whose memory is managed by the kernel parameter subsystem.StringParam provides:
-from_ptr(): construct from a raw C string pointer
-from_c_str(): construct from a static CStr (for compile-time default values)
-null(): construct an unset/empty parameter
-as_cstr()/as_bytes(): safe accessors that return None when the pointer is null
Quoted 3 lines
The type is marked Send + Sync because the underlying pointer is effectively 'static for the module's lifetime — the kernel guarantees the string memory remains valid while the module is loaded.
It is correct that module::args is currently valid for the module's lifetime. However, I wonder if this is still needed and we're not unnecessarily wasting memory. Since commit e180a6b7759a ("param: fix charp parameters set via sysfs"), even charp parameters are kmalloc'ed, unless they end up pointing into static_command_line when the specific parameters are built into vmlinux and set during boot.
Similarly, if Rust modules eventually need to support parameters set via sysfs, it will also be necessary to make copies.
Signature · 2 lines
Cheers, Petr
PATCH 2/8 rust: module_param: wire StringParam into the module! macro
In reply to Matthew WoodAdd 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().
--- rust/kernel/module_param.rs | 48 +++++++++++++++++++++++++++++++++++++ rust/macros/module.rs | 42 +++++++++++++++++++++++++------- 2 files changed, 81 insertions(+), 9 deletions(-)
rust/kernel/module_param.rs +48 -0
@@ -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 , +};
rust/macros/module.rs +33 -9
94 lines not on this page · raw message
Signature · 1 line
2.52.0
Petr Pavlu
maintainerRe: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Quoted 13 lines · Matthew Wood
Add support for
stringas a parameter type in the module! macro.On the runtime side, add:
-set_string_param(): an extern "C" callback matching thekernel_param_ops::setsignature 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 statickernel_param_opsthat usesset_string_paramas its setter.
- ModuleParam impl for StringParam withtry_from_param_arg()returning-EINVAL, since string parameters are populated exclusively through the kernel's set callback.
Quoted 3 lines
On the macro side:
- Change theParameter::ptypefield from Ident tosyn::Typeto 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?
Quoted 22 lines
- Recognize the
stringshorthand 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.
- RoutestringtoPARAM_OPS_STRINGinparam_ops_path().Signed-off-by Matthew Wood <[email protected]>--- rust/kernel/module_param.rs | 48 +++++++++++++++++++++++++++++++++++++ rust/macros/module.rs | 42 +++++++++++++++++++++++++------- 2 files changed, 81 insertions(+), 9 deletions(-)rust/kernel/module_param.rs +1
-0@@ -86,6 +86,36 @@ pub trait ModuleParam: Sized + Copy { }) } +/// Set a string module parameter from a string.
rust/kernel/module_param.rs pub trait ModuleParam: Sized + Copy { · line 99
Quoted 10 lines
rust/kernel/module_param.rs +10
-0+/// +/// 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.
Signature · 2 lines
Thanks, Petr
Re: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
Quoted 15 lines · Petr Pavlu
Quoted 13 lines · Matthew Wood
Add support for
stringas a parameter type in the module! macro.On the runtime side, add:
-set_string_param(): an extern "C" callback matching thekernel_param_ops::setsignature 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 statickernel_param_opsthat usesset_string_paramas its setter.
- ModuleParam impl for StringParam withtry_from_param_arg()returning-EINVAL, since string parameters are populated exclusively through the kernel's set callback.
Quoted 9 lines
Quoted 3 lines
On the macro side:
- Change theParameter::ptypefield from Ident tosyn::Typeto 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.
Quoted 8 lines
Quoted 8 lines
rust/kernel/module_param.rs +8
-0+/// 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(
Quoted 9 lines
rust/kernel/module_param.rs pub trait ModuleParam: Sized + Copy { · line 99
Quoted 3 lines
rust/kernel/module_param.rs +3
-0+ 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, whereasset_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
Sami Tolvanen
maintainerRe: [PATCH 2/8] rust: module_param: wire StringParam into the module! macro
In reply to Matthew WoodQuoted 12 lines · Matthew Wood
rust/kernel/module_param.rs +12
-0+/// 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 () {
rust/kernel/module_param.rs pub trait ModuleParam: Sized + Copy { · line 110
Quoted 10 lines
rust/kernel/module_param.rs +10
-0+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?
rust/kernel/module_param.rs pub trait ModuleParam: Sized + Copy { · line 115
Quoted 5 lines
rust/kernel/module_param.rs +5
-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
Quoted 22 lines · Sami Tolvanen
Quoted 20 lines · Matthew Wood
rust/kernel/module_param.rs +20
-0+/// 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) }; +
Quoted 9 lines
rust/kernel/module_param.rs pub trait ModuleParam: Sized + Copy { · line 110
Quoted 2 lines
rust/kernel/module_param.rs +2
-0+// 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.
Quoted 11 lines
rust/kernel/module_param.rs pub trait ModuleParam: Sized + Copy { · line 115
Quoted 5 lines
rust/kernel/module_param.rs +5
-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
Yes, I'll fix that, the implementations should match.
Regards,
Mat
PATCH 3/8 samples: rust_minimal: demonstrate string module parameter
In reply to Matthew WoodAdd a test_str string parameter alongside the existing integer parameter (renamed from test_parameter to test_int for clarity) in the rust_minimal sample module.
The init function now prints both parameters to the kernel log, showing how string parameters are declared, defaulted, and read back via StringParam::as_cstr().
Also add module-level documentation showing usage via insmod and kernel command-line with dotted notation.
--- samples/rust/rust_minimal.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-)
samples/rust/rust_minimal.rs +28 -3
@@ -1,6 +1,23 @@// SPDX-License-Identifier: GPL-2.0 //! Rust minimal sample. +//! +//! This is a sample module written in Rust. It is intended to be a minimal +//! example of how to write a module in Rust. It does not do anything useful, +//! except print a message when it is loaded and unloaded. +//! +//! It provides examples of how to receive module parameters, which can be provided +//! by the user when the module is loaded: +//! +//! ``` +//! insmod /lib/modules/$(uname -r)/kernel/samples/rust/rust_minimal.ko test_int=2 test_str=world +//! ``` +//! +//! or via kernel cmdline with module dotted notation (when built-in and not built as a module): +//! +//! ``` +//! ... rust_minimal.test_int=2 rust_minimal.test_str=world ... +//! ``` use kernel::prelude::*;
@@ -11,10 +28,14 @@ description: "Rust minimal sample", license: "GPL", params: { - test_parameter: i64 { + test_int: i64 { default: 1, description: "This parameter has a default of 1", }, + test_str: string { + default:"hello" , + description:"This parameter has a default of hello" , + } }, }
@@ -26,9 +47,13 @@ impl kernel::Module for RustMinimal {fn init (_module: &'staticThisModule ) ->Result <Self > {pr_info! ("Rust minimal sample (init)\n" );pr_info! ("Am I built-in? {}\n" , !cfg! (MODULE )); +pr_info! ("test_int: {}\n" , *module_parameters::test_int.value ());pr_info! ( -"test_parameter: {}\n" , - *module_parameters::test_parameter.value () +"test_str: {}\n" , + module_parameters::test_str + .value () + .as_cstr () + .expect ("test_str has a default value" ) );let mut numbers =KVec ::new ();
Signature · 1 line
2.52.0
PATCH 4/8 rust: module_param: add ObsKernelParam type
In reply to Matthew WoodAdd ObsKernelParam, a #[repr(C)] struct that mirrors the C obs_kernel_param structure used by the __setup / early_param infrastructure to register boot-time command-line handlers.
The struct contains:
- str_: pointer to the null-terminated setup string
- setup_func: the callback invoked when the kernel parses the matching command-line token
- early: flag distinguishing early_param (1) from __setup (0)
Mark it Sync because instances are written at compile time and only read during single-threaded early boot initialization.
This type will be used by the module! macro to emit __setup entries in the .init.setup ELF section in subsequent patches.
--- rust/kernel/module_param.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
rust/kernel/module_param.rs +14 -0
@@ -26,6 +26,20 @@ pub const fn new(val: bindings::kernel_param) -> Self {// from Rust module. unsafe impl Sync for KernelParam {} +/// Placed in the `.init.setup` ELF section by the `module!` macro. +#[repr( C )] +pub struct ObsKernelParam { +/// Pointer to the null-terminated setup string (e.g., `"netconsole=\0"`). +pub str_: *const c_char , +/// The setup callback function. +pub setup_func:Option <unsafe extern "C" fn (*mut c_char ) ->c_int >, +/// Whether this is an early parameter (0 for `__setup`, 1 for `early_param`). +pub early:c_int , +} + +// SAFETY: Only written at compile time, read during single-threaded boot init. +unsafe impl Sync for ObsKernelParam {} +/// Types that can be used for module parameters. // NOTE: This trait is `Copy` because drop could produce unsoundness during teardown. pub trait ModuleParam :Sized +Copy {
Signature · 1 line
2.52.0
PATCH 5/8 rust: module_param: add from_setup_arg() to ModuleParam trait
In reply to Matthew WoodExtend the ModuleParam trait with from_setup_arg(), which constructs a parameter value from a raw C string pointer received via a __setup callback during early boot.
The default implementation converts the pointer to a CStr and delegates to try_from_param_arg(), which handles the parse-from-string path used by integer types.
StringParam overrides this method to store the raw pointer directly without parsing, since the pointer originates from static_command_line and remains valid for the kernel's lifetime.
Also add ModuleParamAccess::set_value() to allow the __setup callback generated by the module! macro to populate the SetOnce container with first-write-wins semantics.
--- rust/kernel/module_param.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+)
rust/kernel/module_param.rs +29 -0
@@ -45,6 +45,21 @@ unsafe impl Sync for ObsKernelParam {}pub trait ModuleParam :Sized +Copy {/// Parse a parameter argument into the parameter value. fn try_from_param_arg (arg: &BStr ) ->Result <Self >; + +/// Create a parameter value from a raw `__setup` callback argument. +/// +/// Default implementation: parse the null-terminated C string via +/// [`ModuleParam::try_from_param_arg`]. `StringParam` overrides this to store the pointer +/// directly. +/// +/// # Safety +/// +/// `val` must point to a valid null-terminated string. +unsafe fn from_setup_arg (val: *const c_char ) ->Result <Self > { +// SAFETY: Caller guarantees `val` points to a valid null-terminated string. +let cstr =unsafe {CStr ::from_char_ptr (val) }; +Self ::try_from_param_arg (cstr.as_ref ()) + } }/// Set the module parameter from a string.
@@ -226,6 +241,12 @@ fn try_from_param_arg(_arg: &BStr) -> Result<Self> {// when using PARAM_OPS_STRING. Err (EINVAL ) } + +unsafe fn from_setup_arg (val: *const c_char ) ->Result <Self > { +// SAFETY: Caller guarantees `val` points to a valid null-terminated string. +// The pointer comes from `static_command_line` which is valid for the kernel's lifetime. +Ok (unsafe {StringParam ::from_ptr (val) }) + } }/// A wrapper for kernel parameters.
@@ -266,6 +287,14 @@ pub fn value(&self) -> &T {pub const fn as_void_ptr (&self) -> *mut c_void { core::ptr::from_ref (self).cast_mut ().cast () } + +/// Set the parameter value directly. +/// +/// Returns `true` if successfully set, `false` if already populated +/// (first-write-wins semantics via [`SetOnce`]). +pub fn set_value (&self, val:T ) ->bool { + self.value.populate (val) + } }#[doc(hidden)]
Signature · 1 line
2.52.0
PATCH 6/8 rust: macros: add early_param support to module! macro
In reply to Matthew WoodAllow module parameters to be registered as early boot command-line parameters via the existing __setup infrastructure.
Add an optional early_param field to the parameter block in the module! macro. When specified, the macro generates:
- A setup callback that calls ModuleParam::from_setup_arg() and stores the result via ModuleParamAccess::set_value().
- A static string in .init.rodata with the command-line prefix.
- An ObsKernelParam entry in the .init.setup section linking the two together.
The generated code is gated behind #[cfg(not(MODULE))] since __setup parameters are only meaningful for built-in modules — loadable modules receive their parameters through the standard module_param mechanism.
--- rust/macros/lib.rs | 5 +++ rust/macros/module.rs | 81 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+)
rust/macros/lib.rs +5 -0
@@ -35,9 +35,14 @@/// parameter_name: type { /// default: default_value, /// description: "Description", +/// early_param: "cmdline_prefix=", // optional /// } /// ``` /// +/// The optional `early_param` field registers the parameter as an early +/// boot command-line parameter via `__setup`. The value is the command-line +/// prefix string (e.g. `"netconsole="`). +/// /// `type` may be one of /// /// - [`i8`]
rust/macros/module.rs +81 -0
131 lines not on this page · raw message
Signature · 1 line
2.52.0
Petr Pavlu
maintainerRe: [PATCH 6/8] rust: macros: add early_param support to module! macro
Quoted 11 lines · Matthew Wood
Allow module parameters to be registered as early boot command-line parameters via the existing
__setupinfrastructure.Add an optional
early_paramfield to the parameter block in the module! macro. When specified, the macro generates:- A setup callback that calls
ModuleParam::from_setup_arg()and stores the result viaModuleParamAccess::set_value().
- A static string in .init.rodata with the command-line prefix.
- An ObsKernelParam entry in the .init.setup section linking the two together.
The early_param() macro on the C side creates an obs_kernel_param entry with early=1. However, this patch handles the new early_param setting in Rust by creating an obs_kernel_param with early=0. Non-early obs_kernel_params are processed by obsolete_checksetup() during the parse_args("Booting kernel") call in start_kernel(), which also handles regular kernel_params.
Actual early parameters are handled by parse_early_param(). Note that the command line parsed in this case is marked as __initdata, so it would not be available for the kernel's entire lifetime, as the previous patches assume.
So I'm somewhat confused by this patch, or perhaps I misunderstood something?
Quoted 4 lines
rust/macros/lib.rs +0
-0
[...]
Quoted 8 lines
rust/macros/lib.rs +8
-0+#[link_section = ".init.setup" ] +#[used(compiler)] + static #setup_name: ::kernel::module_param::ObsKernelParam = + ::kernel::module_param::ObsKernelParam { + str_: #setup_str_name.as_ptr().cast(), + setup_func: ::core::option::Option::Some(#setup_fn_name), + early:0 , + };
Signature · 2 lines
Thanks, Petr
PATCH 7/8 samples: rust_minimal: demonstrate early_param usage
In reply to Matthew WoodAdd an early_param annotation to the test_str parameter in the rust_minimal sample module, registering it as "testing_early_str=" on the kernel command line.
When the module is built-in, this allows the parameter to be set directly on the boot command line without dotted module notation:
testing_early_str=world
--- samples/rust/rust_minimal.rs | 2 ++ 1 file changed, 2 insertions(+)
samples/rust/rust_minimal.rs +2 -0
@@ -35,6 +35,8 @@ test_str: string { default:"hello" , description:"This parameter has a default of hello" , +// This will allow the arg to be used in kernel cmdline without dotted notation + early_param:"testing_early_str=" , } }, }
Signature · 1 line
2.52.0
PATCH 8/8 rust: macros: add configurable initcall levels to module! macro
In reply to Matthew WoodCurrently all Rust modules using the module! macro are placed at initcall level 6 (device_initcall). Some modules need to initialize earlier in the boot sequence to provide services that other subsystems depend on.
Add an InitCallLevel enum representing all eight standard initcall levels (pure through late) and map each to its corresponding .initcallN.init ELF section.
Expose this as an optional initcall field in the module! macro. When omitted, the default remains level 6 (device) so existing modules are unaffected. Example usage:
module! {
...
initcall: subsys,
}This only affects built-in modules; loadable modules always enter through init_module() regardless of the declared level.
--- rust/macros/lib.rs | 4 ++++ rust/macros/module.rs | 56 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-)
rust/macros/lib.rs +4 -0
@@ -135,6 +135,10 @@/// - `alias`: array of ASCII string literals of the alias names of the kernel module. /// - `firmware`: array of ASCII string literals of the firmware files of /// the kernel module. +/// - `initcall`: initcall level for built-in modules. Valid values are: +/// `pure` (0), `core` (1), `postcore` (2), `arch` (3), `subsys` (4), +/// `fs` (5), `device` (6, the default), and `late` (7). +/// This only affects built-in modules; loadable modules always use `init_module()`. #[proc_macro] pub fn module (input:TokenStream ) ->TokenStream { module::module (parse_macro_input! (input))
rust/macros/module.rs +55 -1
92 lines not on this page · raw message
Signature · 1 line
2.52.0
Quoted 5 lines
This series extends the Rust module! macro with three capabilities that are available to C modules but currently missing from the Rust
abstractions: string parameters, early boot command-line parameters, and configurable initcall levels.
Quoted 7 lines
The existing Rust module parameter infrastructure supports integer types (i8..u64, isize, usize) but has no way to accept string values. Additionally, built-in Rust modules cannot register parameters for early boot command-line parsing (
__setup/early_param), and all Rust modules are hard-coded to initcall level 6 (device_initcall) with no way to control initialization ordering.
I forgot to mention that these changes are a dependency for a netconsole rust implementation
I'm working on and I need these three features to match the current behavior.
Regards,
Matthew