rust: extend `module!` macro with integer parameter support
Subsystems (4)
Andreas Hindborg
reviewerv14 cover rust: extend `module!` macro with integer parameter support
Extend the module! macro with support module parameters. Also add some string to integer parsing functions and updates BStr with a method to strip a string prefix.
Based on code by Adam Bratschi-Kaye lifted from the original rust branch [1].
---
Note: This series now depends on the atomics series [1].
[1] https://lore.kernel.org/all/[email protected]
Changes in v14:
- Remove unnecessary crate:: prefix from module_param::set_param.
- Make FromStrRadix safe again by moving unsafe blocks to macro implementation (thanks Benno).
- Use core::ptr::write in set_param and drop safety requirement regarding initialization.
- Add a TODO to use SyncUnsafeCell for ModuleParamAccess when available.
- Add a NOTE regarding Copy bound on ModuleParam.
- Remove 'static lifetime qualifier from ModuleParam::try_from_param_arg argument.
- Fix a typo in the safety requirements for set_param.
- Remove unused #[macro_export] attribute.
- Remove obsolete documentation for ModuleParam::try_from_param_arg.
- Make RacyKernelParam tuple field private.
- Introduce OnceLock and use that to synchronize population of parameter values.
- Link to v13: https://lore.kernel.org/r/[email protected]
Changes in v13:
- remove absolute path for ffi types.
- Split patch 2 into 4 separate patches.
- Overhaul safety framework for set_param.
- Remove generated docs for kernel_param_ops.
- Move parse_int to separate file.
- Rebase on v6.16-rc1
- Link to v12: https://lore.kernel.org/r/[email protected]
Changes in v12:
- Assign through pointer rather than using core::ptr::replace.
- Prevent a potential use-after-free during module teardown.
- Link to v11: https://lore.kernel.org/r/[email protected]
Changes in v11:
- Apply a few nits from Miguel.
- Link to v10: https://lore.kernel.org/r/[email protected]
Changes in v10:
- Apply fixups from Miguel:
- Add integer type suffixes to assert! in tests.
- Fix links to docs.kernel.org.
- Applyy markdown and intra-doc links where possible.
- Change to /// for mod docs.
- Slightly reword a comment.
- Pluralize "Examples" section name.
- Hide uses in example.
- Removed #[expect] for the rusttest target.
- Link to v9: https://lore.kernel.org/r/[email protected]
Changes in v9:
- Remove UB when parsing the minimum integer values.
- Make FromStr trait unsafe, since wrong implementations can cause UB.
- Drop patches that were applied to rust-next.
- Link to v8: https://lore.kernel.org/r/[email protected]
Changes in v8:
- Change print statement in sample to better communicate parameter name.
- Use imperative mode in commit messages.
- Remove prefix path from EINVAL.
- Change try_from_param_arg to accept &BStr rather than &[u8].
- Parse integers without 128 bit integer types.
- Seal trait FromStrRadix.
- Strengthen safety requirement of set_param.
- Remove comment about Display and PAGE_SIZE.
- Add note describing why ModuleParamAccess is pub.
- Typo and grammar fixes for documentation.
- Update MAINTAINERS with rust module files.
- Link to v7: https://lore.kernel.org/r/[email protected]
Changes in v7:
- Remove dependency on pr_warn_once patches, replace with TODO.
- Rework ParseInt::from_str to avoid allocating.
- Add a comment explaining how we parse "0".
- Change trait bound on Index impl for BStr to match std library approach.
- Link to v6: https://lore.kernel.org/r/[email protected]
Changes in v6:
- Fix a bug that prevented parsing of negative default values for
parameters in the module! macro.
- Fix a bug that prevented parsing zero in strip_radix. Also add a
test case for this.
- Add AsRef<BStr> for [u8] and BStr.
- Use impl AsRef<BStr> as type of prefix in BStr::strip_prefix.
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Fix a typo in a safety comment in set_param.
- Use a match statement in parse_int::strip_radix.
- Add an implementation of Index for BStr.
- Fix a logic inversion bug where parameters would not be parsed.
- Use kernel::ffi::c_char in set_param rather than the one in core.
- Use kernel::c_str! rather than c"..." literal in module macro.
- Rebase on v6.14-rc1.
- Link to v4: https://lore.kernel.org/r/[email protected]
Changes in v4:
- Add module maintainers to Cc list (sorry)
- Add a few missing [doc_links]
- Add panic section to expect_string_field
- Fix a typo in safety requirement of module_params::free
- Change assert! to pr_warn_once! in module_params::set_param
- Remove module_params::get_param and install null pointer instead
- Remove use of the unstable feature sync_unsafe_cell
- Link to v3: https://lore.kernel.org/r/[email protected]
Changes in v3:
- use SyncUnsafeCell rather than static mut and simplify parameter access
- remove Display bound from ModuleParam
- automatically generate documentation for PARAM_OPS_.*
- remove as *const _ as *mut_ phrasing
- inline parameter name in struct instantiation in emit_params
- move RacyKernelParam out of macro template
- use C string literals rather than byte string literals with explicit null
- template out __{name}_{param_name} in emit_param
- indent template in emit_params
- use let-else expression in emit_params to get rid of an indentation level
- document expect_string_field
- move invication of impl_int_module_param to be closer to macro def
- move attributes after docs in make_param_ops
- rename impl_module_param to impl_int_module_param`
- use ty instead of ident in impl_parse_int
- use BStr instead of &str for string manipulation
- move string parsing functions to seperate patch and add examples, fix bugs
- degrade comment about future support from doc comment to regular comment
- remove std lib path from Sized marker
- update documentation for trait ModuleParam
- Link to v2: https://lore.kernel.org/all/[email protected]/
Changes in v2:
- Remove support for params without values (NOARG_ALLOWED).
- Improve documentation for try_from_param_arg.
- Use prelude import.
- Refactor try_from_param_arg to return Result.
- Refactor ParseInt::from_str to return Result.
- Move C callable functions out of ModuleParam trait.
- Rename literal string field parser to expect_string_field.
- Move parameter parsing from generation to parsing stage.
- Use absolute type paths in macro code.
- Inline kparamand read_func values.
- Resolve TODO regarding alignment attributes.
- Remove unnecessary unsafe blocks in macro code.
- Improve error message for unrecognized parameter types.
- Do not use self receiver when reading parameter value.
- Add parameter documentation to module! macro.
- Use empty enum for parameter type.
- Use addr_of_mut to get address of parameter value variable.
- Enabled building of docs for for module_param module.
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/
---
Andreas Hindborg (7):
rust: sync: add OnceLock
rust: str: add radix prefixed integer parsing functions
rust: introduce module_param module
rust: module: use a reference in macros::module::module
rust: module: update the module macro with module parameter support
rust: samples: add a module parameter to the rust_minimal sample
modules: add rust modules files to MAINTAINERS
MAINTAINERS | 2 + rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 191 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++ rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++ rust/macros/helpers.rs | 25 ++++++ rust/macros/lib.rs | 31 +++++++ rust/macros/module.rs | 197 +++++++++++++++++++++++++++++++++++++----- samples/rust/rust_minimal.rs | 10 +++ 11 files changed, 692 insertions(+), 20 deletions(-)
---
base-commit: d9946fe286439c2aeaa7953b8c316efe5b83d515
change-id: 20241211-module-params-v3-ae7e5c8d8b5a
prerequisite-message-id: [email protected]
prerequisite-patch-id: 997f74bd63d81dc66725d7f84ffcf5a3517da1eb
prerequisite-patch-id: 3e3f8bdada027406a356a2b35aebe13edbda0a94
prerequisite-patch-id: 468b093532aa503c23302142b8cfe7989e3cb8f1
prerequisite-patch-id: 96ca162a1e95a29d3aca2e748d600a31417b83e5
prerequisite-patch-id: 8f78abede975c0c9690ee0f4cf4e7af3cb145191
prerequisite-patch-id: a716ee7a51184d224ef60812ecfffadb51980153
prerequisite-patch-id: e54f74896a75147b66e509c1281804047d41f08b
prerequisite-patch-id: 3f77e2179901ae664a2d2e58965a9725ad13189e
prerequisite-patch-id: e964a9576f9c3970bb7a34b4d2891ffb92939d0e
prerequisite-patch-id: bba35ecdf783653e0fa46015bc289706508fac55
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
reviewerPATCH v14 1/7 rust: sync: add `OnceLock`
Introduce the OnceLock type, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.
--- rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)
rust/kernel/sync.rs +1 -0
@@ -15,6 +15,7 @@mod condvar;pub mod lock;mod locked_by; +pub mod once_lock;pub mod poll;pub mod rcu;
rust/kernel/sync/once_lock.rs new file +104 -0
104 lines not on this page · raw message
Signature · 1 line
2.47.2
Alice Ryhl
maintainerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 6 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>
This type provides no way to wait for initialization to finish if it's ongoing. Do you not need that?
Quoted 10 lines
--- rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)rust/kernel/sync.rs +0
-0
rust/kernel/sync.rs line 18
Quoted 4 lines
rust/kernel/sync.rs +1
-0@@ -15,6 +15,7 @@mod condvar;pub mod lock;mod locked_by; +pub mod once_lock;
I would add a re-export so that users can import this as kernel::sync::OnceLock.
Quoted 17 lines
rust/kernel/sync.rs +0
-0pub mod poll;pub mod rcu;rust/kernel/sync/once_lock.rs new file +8
-0@@ -0,0 +1,104 @@ +//! A container that can be initialized at most once. + +use super ::atomic::ordering::Acquire ; +use super ::atomic::ordering::Release ; +use super ::atomic::Atomic ; +use kernel::types::Opaque ; + +/// A container that can be populated at most once. Thread safe.
rust/kernel/sync/once_lock.rs line 18
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// +/// Once the a [`OnceLock`] is populated, it remains populated by the same object for the +/// lifetime `Self`. +/// +/// # Invariants +/// +/// `init` tracks the state of the container: +/// +/// - If the container is empty, `init` is `0`. +/// - If the container is mutably accessed, `init` is `1`.
I would phrase this as "being initialized" instead of "mutably accessed". I initially thought this was talking about someone calling a &mut self method.
Quoted 12 lines
rust/kernel/sync/once_lock.rs new file +12
-0+/// - If the container is populated and ready for shared access, `init` is `2`. +/// +/// # Example +/// +/// ``` +/// # use kernel::sync::once_lock::OnceLock; +/// let value = OnceLock::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref());
rust/kernel/sync/once_lock.rs line 40
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >,
Opaque does not destroy the inner value. You are missing a destructor.
Quoted 29 lines
rust/kernel/sync/once_lock.rs new file +29
-0+} + +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >OnceLock <T > { +/// Create a new [`OnceLock`]. +/// +/// The returned instance will be empty. +pub const fn new () ->Self { +// INVARIANT: The container is empty and we set `init` to `0`. +Self { + value:Opaque ::uninit (), + init:Atomic ::new (0 ), + } + } + +/// Get a reference to the contained object. +/// +/// Returns [`None`] if this [`OnceLock`] is empty. +pub fn as_ref (&self) ->Option <&T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { &*self.value.get () }) + }else { +None
rust/kernel/sync/once_lock.rs line 79
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+ } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated. +pub fn populate (&self, value:T ) ->bool { +// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) {
This acquire can be Relaxed. All other accesses to self.value synchronize with the release store below, so you do not need acquire here to obtain exclusive access.
Quoted 30 lines
rust/kernel/sync/once_lock.rs new file +25
-1+// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else { +false + } + } +} + +impl <T :Copy >OnceLock <T > { +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + } + } +} --2.47.2
Andreas Hindborg
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 10 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>This type provides no way to wait for initialization to finish if it's ongoing. Do you not need that?
I don't, and in my use case it would cause a deadlock to wait. Anyway, it might be useful to others. Would you add it now, or wait for a user?
Quoted 6 lines
Quoted 6 lines
--- rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)
Quoted 11 lines
rust/kernel/sync.rs line 18
Quoted 9 lines
rust/kernel/sync.rs +1
-0@@ -15,6 +15,7 @@mod condvar;pub mod lock;mod locked_by; +pub mod once_lock;I would add a re-export so that users can import this as
kernel::sync::OnceLock.
OK.
Quoted 24 lines
Quoted 24 lines
rust/kernel/sync.rs +0
-0pub mod poll;pub mod rcu;rust/kernel/sync/once_lock.rs new file +14
-0@@ -0,0 +1,104 @@ +//! A container that can be initialized at most once. + +use super ::atomic::ordering::Acquire ; +use super ::atomic::ordering::Release ; +use super ::atomic::Atomic ; +use kernel::types::Opaque ; + +/// A container that can be populated at most once. Thread safe. +/// +/// Once the a [`OnceLock`] is populated, it remains populated by the same object for the +/// lifetime `Self`. +/// +/// # Invariants +///
Quoted 8 lines
rust/kernel/sync/once_lock.rs line 18
Quoted 4 lines
rust/kernel/sync/once_lock.rs new file +4
-0+/// `init` tracks the state of the container: +/// +/// - If the container is empty, `init` is `0`. +/// - If the container is mutably accessed, `init` is `1`. I would phrase this as "being initialized" instead of "mutably accessed". I initially thought this was talking about someone calling a &mut self method.
Makes sense, I will change that.
Quoted 17 lines
Quoted 17 lines
rust/kernel/sync/once_lock.rs new file +16
-0+/// - If the container is populated and ready for shared access, `init` is `2`. +/// +/// # Example +/// +/// ``` +/// # use kernel::sync::once_lock::OnceLock; +/// let value = OnceLock::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status);
Quoted 8 lines
rust/kernel/sync/once_lock.rs line 40
Quoted 6 lines
rust/kernel/sync/once_lock.rs new file +6
-0+/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >,Opaque does not destroy the inner value. You are missing a destructor.
Oops.
Quoted 36 lines
Quoted 36 lines
rust/kernel/sync/once_lock.rs new file +35
-0+} + +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >OnceLock <T > { +/// Create a new [`OnceLock`]. +/// +/// The returned instance will be empty. +pub const fn new () ->Self { +// INVARIANT: The container is empty and we set `init` to `0`. +Self { + value:Opaque ::uninit (), + init:Atomic ::new (0 ), + } + } + +/// Get a reference to the contained object. +/// +/// Returns [`None`] if this [`OnceLock`] is empty. +pub fn as_ref (&self) ->Option <&T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { &*self.value.get () }) + }else { +None + } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated.
Quoted 8 lines
rust/kernel/sync/once_lock.rs line 79
Quoted 4 lines
rust/kernel/sync/once_lock.rs new file +4
-0+pub fn populate (&self, value:T ) ->bool { +// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) {This acquire can be Relaxed. All other accesses to self.value synchronize with the release store below, so you do not need acquire here to obtain exclusive access.
Right, thanks.
Best regards,
Andreas Hindborg
Alice Ryhl
maintainerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 9 lines · Andreas Hindborg
Quoted 6 lines · Alice Ryhl
Quoted 5 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Signed-off-by Andreas Hindborg <[email protected]>This type provides no way to wait for initialization to finish if it's ongoing. Do you not need that?
I don't, and in my use case it would cause a deadlock to wait. Anyway, it might be useful to others. Would you add it now, or wait for a user?
Waiting would require additional fields so it should probably be a different type. It's more that we probably want the OnceLock name for that other type for consistency with stdlib, so perhaps this should be renamed? The name could be SetOnce or similar.
Alice
Andreas Hindborg
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 12 lines · Alice Ryhl
Quoted 11 lines · Andreas Hindborg
Quoted 8 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
This type provides no way to wait for initialization to finish if it's ongoing. Do you not need that?
I don't, and in my use case it would cause a deadlock to wait. Anyway, it might be useful to others. Would you add it now, or wait for a user?
Waiting would require additional fields so it should probably be a different type.
That depends on the kind of waiting. If we do unfair waiting, with spinning, we can have unlimited waiters with this type. We can also use the remaining 29 bits of the atomic to encode ordering to get fair queuing for spinning waiters.
Putting waiters to sleep would require more fields.
Quoted 3 lines
It's more that we probably want the OnceLock name for
that other type for consistency with stdlib, so perhaps this should be renamed? The name could be SetOnce or similar.
The feature set is very similar to std::sync::OnceLock, that is why I picked that name. We can expand this to allow resetting without too much effort, and we can do fair waiting with spinning for a reasonable amount of waiters.
But I am also OK with changing the name to SetOnce if we envision a OnceLock with thread sleep blocking at some point.
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
In reply to Andreas HindborgQuoted 15 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)rust/kernel/sync.rs +0
-0
rust/kernel/sync.rs line 18
Quoted 4 lines
rust/kernel/sync.rs +1
-0@@ -15,6 +15,7 @@mod condvar;pub mod lock;mod locked_by; +pub mod once_lock;
As Alice already said, we should reexport the type. And then make the module private, no need to have kernel::sync::OnceLock and kernel::sync::once_lock::OnceLock...
Also, I agree with the name change to SetOnce or something similar.
Quoted 17 lines
rust/kernel/sync.rs +0
-0pub mod poll;pub mod rcu;rust/kernel/sync/once_lock.rs new file +8
-0@@ -0,0 +1,104 @@ +//! A container that can be initialized at most once. + +use super ::atomic::ordering::Acquire ; +use super ::atomic::ordering::Release ; +use super ::atomic::Atomic ; +use kernel::types::Opaque ; + +/// A container that can be populated at most once. Thread safe.
rust/kernel/sync/once_lock.rs line 18
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// +/// Once the a [`OnceLock`] is populated, it remains populated by the same object for the +/// lifetime `Self`. +/// +/// # Invariants +/// +/// `init` tracks the state of the container: +/// +/// - If the container is empty, `init` is `0`. +/// - If the container is mutably accessed, `init` is `1`.
I think we should swap the order and change the ifs to iffs:
- init == 0 iff the container is empty.
- init == 1 iff the container is being accessed mutably.
rust/kernel/sync/once_lock.rs line 19
Quoted 1 line
rust/kernel/sync/once_lock.rs new file +1
-0+/// - If the container is populated and ready for shared access, `init` is `2`.
You also need that init is only increased and never decreases. Otherwise you could read a 2 and then access the value, but init changed under your nose to 0.
Then the INVARIANT comments below also need to be updated.
Quoted 37 lines
rust/kernel/sync/once_lock.rs new file +37
-0+/// +/// # Example +/// +/// ``` +/// # use kernel::sync::once_lock::OnceLock; +/// let value = OnceLock::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >, +} + +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >OnceLock <T > { +/// Create a new [`OnceLock`]. +/// +/// The returned instance will be empty. +pub const fn new () ->Self { +// INVARIANT: The container is empty and we set `init` to `0`. +Self { + value:Opaque ::uninit (),
rust/kernel/sync/once_lock.rs line 66
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+ init: Atomic::new(0), + } + } + +/// Get a reference to the contained object. +/// +/// Returns [`None`] if this [`OnceLock`] is empty. +pub fn as_ref (&self) ->Option <&T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access.
// SAFETY: By the safety requirements of `Self`, `self.init == 2` means that `self.value` contains
// a valid value.Quoted 26 lines
rust/kernel/sync/once_lock.rs new file +26
-0+Some (unsafe { &*self.value.get () }) + }else { +None + } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated. +pub fn populate (&self, value:T ) ->bool { +// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) { +// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else { +false + } + } +} + +impl <T :Copy >OnceLock <T > {
rust/kernel/sync/once_lock.rs line 102
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }
The impl can just be:
self.as_ref().copied()
Would it make sense for this function to take self instead & we make the OnceLock also Copy if T: Copy? Maybe not...
rust/kernel/sync/once_lock.rs line 104
Quoted 2 lines
rust/kernel/sync/once_lock.rs new file +2
-0+ } +}
You can move this method into the block above and just add `where T:
Copy` on the method.
---
Cheers,
Benno
Alice Ryhl
maintainerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 14 lines · Benno Lossin
rust/kernel/sync/once_lock.rs line 102
Quoted 11 lines · Andreas Hindborg
rust/kernel/sync/once_lock.rs new file +11
-0+impl <T :Copy >OnceLock <T > { +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }
Quoted 6 lines
The impl can just be:
self.as_ref().copied()Would it make sense for this function to take
selfinstead & we make theOnceLockalsoCopyifT: Copy? Maybe not...
Atomics are not Copy.
Alice
Benno Lossin
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 14 lines · Alice Ryhl
Quoted 13 lines · Benno Lossin
Quoted 11 lines · Andreas Hindborg
rust/kernel/sync/once_lock.rs new file +11
-0+impl <T :Copy >OnceLock <T > { +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }
Quoted 8 lines
Quoted 6 lines
The impl can just be:
self.as_ref().copied()Would it make sense for this function to take
selfinstead & we make theOnceLockalsoCopyifT: Copy? Maybe not...Atomics are not Copy.
Ah right... Yeah it probably also isn't useful.
---
Cheers,
Benno
Andreas Hindborg
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
In reply to Benno LossinQuoted 11 lines · Benno Lossin
Quoted 10 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)
Quoted 13 lines
rust/kernel/sync.rs line 18
Quoted 9 lines
rust/kernel/sync.rs +1
-0@@ -15,6 +15,7 @@mod condvar;pub mod lock;mod locked_by; +pub mod once_lock;As Alice already said, we should reexport the type. And then make the module private, no need to have
kernel::sync::OnceLockandkernel::sync::once_lock::OnceLock...
Will do.
Quoted 2 lines
Also, I agree with the name change to
SetOnceor something similar.
I'm OK with that, but please see my comments on Alice suggestion.
Quoted 31 lines
Quoted 18 lines
rust/kernel/sync.rs +0
-0pub mod poll;pub mod rcu;rust/kernel/sync/once_lock.rs new file +8
-0@@ -0,0 +1,104 @@ +//! A container that can be initialized at most once. + +use super ::atomic::ordering::Acquire ; +use super ::atomic::ordering::Release ; +use super ::atomic::Atomic ; +use kernel::types::Opaque ; + +/// A container that can be populated at most once. Thread safe. rust/kernel/sync/once_lock.rs line 18
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// +/// Once the a [`OnceLock`] is populated, it remains populated by the same object for the +/// lifetime `Self`. +/// +/// # Invariants +/// +/// `init` tracks the state of the container: +/// +/// - If the container is empty, `init` is `0`. +/// - If the container is mutably accessed, `init` is `1`. I think we should swap the order and change the ifs to iffs:
Quoted 2 lines
-
init == 0iff the container is empty.
-init == 1iff the container is being accessed mutably.
Right, that is better, but I will expand "iff".
Quoted 8 lines
rust/kernel/sync/once_lock.rs line 19
Quoted 2 lines
rust/kernel/sync/once_lock.rs new file +1
-0+/// - If the container is populated and ready for shared access, `init` is `2`. You also need that
initis only increased and never decreases. Otherwise you could read a2and then access the value, butinitchanged under your nose to0.Then the INVARIANT comments below also need to be updated.
OK.
Quoted 43 lines
Quoted 43 lines
rust/kernel/sync/once_lock.rs new file +42
-0+/// +/// # Example +/// +/// ``` +/// # use kernel::sync::once_lock::OnceLock; +/// let value = OnceLock::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >, +} + +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >OnceLock <T > { +/// Create a new [`OnceLock`]. +/// +/// The returned instance will be empty. +pub const fn new () ->Self { +// INVARIANT: The container is empty and we set `init` to `0`. +Self { + value:Opaque ::uninit (), + init:Atomic ::new (0 ), + } + } + +/// Get a reference to the contained object.
Quoted 8 lines
rust/kernel/sync/once_lock.rs line 66
Quoted 5 lines
rust/kernel/sync/once_lock.rs new file +5
-0+/// +/// Returns [`None`] if this [`OnceLock`] is empty. +pub fn as_ref (&self) ->Option <&T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. // SAFETY: By the safety requirements of `Self`, `self.init == 2` means that `self.value` contains // a valid value.
By the *type invariants* I guess?
Quoted 40 lines
Quoted 27 lines
rust/kernel/sync/once_lock.rs new file +26
-0+Some (unsafe { &*self.value.get () }) + }else { +None + } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated. +pub fn populate (&self, value:T ) ->bool { +// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) { +// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else { +false + } + } +} + +impl <T :Copy >OnceLock <T > {rust/kernel/sync/once_lock.rs line 102
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }The impl can just be:
Quoted 1 line
self.as_ref().copied()
Nice. I was thinking of dropping this method and just have callers do
my_once_lock.as_ref().map(|v| v.copied())
What do you think?
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 53 lines · Andreas Hindborg
Quoted 43 lines · Benno Lossin
Quoted 42 lines · Andreas Hindborg
rust/kernel/sync/once_lock.rs new file +42
-0+/// +/// # Example +/// +/// ``` +/// # use kernel::sync::once_lock::OnceLock; +/// let value = OnceLock::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >, +} + +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >OnceLock <T > { +/// Create a new [`OnceLock`]. +/// +/// The returned instance will be empty. +pub const fn new () ->Self { +// INVARIANT: The container is empty and we set `init` to `0`. +Self { + value:Opaque ::uninit (), + init:Atomic ::new (0 ), + } + } + +/// Get a reference to the contained object. Quoted 8 lines
rust/kernel/sync/once_lock.rs line 66
Quoted 5 lines
rust/kernel/sync/once_lock.rs new file +5
-0+/// +/// Returns [`None`] if this [`OnceLock`] is empty. +pub fn as_ref (&self) ->Option <&T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. // SAFETY: By the safety requirements of `Self`, `self.init == 2` means that `self.value` contains // a valid value.
Quoted 1 line
By the *type invariants* I guess?
Oh yeah.
Quoted 39 lines
Quoted 39 lines
Quoted 26 lines
rust/kernel/sync/once_lock.rs new file +26
-0+Some (unsafe { &*self.value.get () }) + }else { +None + } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated. +pub fn populate (&self, value:T ) ->bool { +// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) { +// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else { +false + } + } +} + +impl <T :Copy >OnceLock <T > {rust/kernel/sync/once_lock.rs line 102
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }The impl can just be:
Quoted 7 lines
Quoted 1 line
self.as_ref().copied()Nice. I was thinking of dropping this method and just have callers do
my_once_lock.as_ref().map(|v|
v.copied())What do you think?
There is Option::copied, so no need for the .map call. I don't really have a preference, if users always want to access it by-value, then we should have copy.
---
Cheers,
Benno
Andreas Hindborg
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 3 lines · Benno Lossin
Quoted 2 lines · Andreas Hindborg
Quoted 1 line · Benno Lossin
On Wed Jul 2, 2025 at 3:18 PM CEST, Andreas Hindborg wrote:
[...]
Quoted 41 lines
Quoted 41 lines
Quoted 40 lines
Quoted 26 lines
rust/kernel/sync/once_lock.rs new file +26
-0+Some (unsafe { &*self.value.get () }) + }else { +None + } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated. +pub fn populate (&self, value:T ) ->bool { +// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) { +// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else { +false + } + } +} + +impl <T :Copy >OnceLock <T > {rust/kernel/sync/once_lock.rs line 102
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }The impl can just be:
self.as_ref().copied()
Quoted 7 lines
Quoted 5 lines
Nice. I was thinking of dropping this method and just have callers do
my_once_lock.as_ref().map(|v|
v.copied())What do you think?
There is
Option::copied, so no need for the.mapcall.
Cool.
Quoted 3 lines
I don't
really have a preference, if users always want to access it by-value, then we should havecopy.
But should it be copy or copied like Option?
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 28 lines · Andreas Hindborg
Quoted 19 lines · Benno Lossin
Quoted 18 lines · Andreas Hindborg
Quoted 16 lines · Benno Lossin
rust/kernel/sync/once_lock.rs line 102
Quoted 11 lines · Andreas Hindborg
rust/kernel/sync/once_lock.rs new file +11
-0+impl <T :Copy >OnceLock <T > { +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > { +if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + }The impl can just be:
self.as_ref().copied()Quoted 7 lines
Quoted 5 lines
Nice. I was thinking of dropping this method and just have callers do
my_once_lock.as_ref().map(|v|
v.copied())What do you think?
There is
Option::copied, so no need for the.mapcall.
Quoted 7 lines
Cool.
Quoted 3 lines
I don't
really have a preference, if users always want to access it by-value, then we should havecopy.But should it be
copyorcopiedlikeOption?
I'd say copy. With copied I'm thinking of something that turns OnceLock<&T> into OnceLock<T>, which is weird...
---
Cheers,
Benno
Re: [PATCH v14 1/7] rust: sync: add `OnceLock`
In reply to Andreas HindborgQuoted 59 lines · Andreas Hindborg
Introduce the
OnceLocktype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/sync.rs | 1 + rust/kernel/sync/once_lock.rs | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)rust/kernel/sync.rs +1
-0@@ -15,6 +15,7 @@mod condvar;pub mod lock;mod locked_by; +pub mod once_lock;pub mod poll;pub mod rcu;rust/kernel/sync/once_lock.rs new file +31
-0@@ -0,0 +1,104 @@ +//! A container that can be initialized at most once. + +use super ::atomic::ordering::Acquire ; +use super ::atomic::ordering::Release ; +use super ::atomic::Atomic ; +use kernel::types::Opaque ; + +/// A container that can be populated at most once. Thread safe. +/// +/// Once the a [`OnceLock`] is populated, it remains populated by the same object for the +/// lifetime `Self`. +/// +/// # Invariants +/// +/// `init` tracks the state of the container: +/// +/// - If the container is empty, `init` is `0`. +/// - If the container is mutably accessed, `init` is `1`. +/// - If the container is populated and ready for shared access, `init` is `2`. +/// +/// # Example +/// +/// ``` +/// # use kernel::sync::once_lock::OnceLock; +/// let value = OnceLock::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy());
rust/kernel/sync/once_lock.rs line 41
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >, +}
This type looks very much like the Once type in rust's stdlib. I am wondering if the api could be changed to match that api. I know that this type is trying to provide a version subset of std::sync::OnceLock that doesn't allow resetting the type like these apis:
* https://doc.rust-lang.org/std/sync/struct.OnceLock.html#method.get_mut
* https://doc.rust-lang.org/std/sync/struct.OnceLock.html#method.take
However, these methods can only be used on mut. See here for failing example: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=a78e51203c5b9555e3c151e162f0acab
I think it might make more sense to match the api of the stdlib API and maybe only implement the methods you need.
rust/kernel/sync/once_lock.rs line 47
Quoted 6 lines
rust/kernel/sync/once_lock.rs new file +6
-0+ +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +}
Any reason not to use #[derive(Default)]?
rust/kernel/sync/once_lock.rs line 53
Quoted 6 lines
rust/kernel/sync/once_lock.rs new file +6
-0+ +impl <T >OnceLock <T > { +/// Create a new [`OnceLock`]. +/// +/// The returned instance will be empty. +pub const fn new () ->Self {
Like new in std OnceLock. Matches. Good.
rust/kernel/sync/once_lock.rs line 64
Quoted 11 lines
rust/kernel/sync/once_lock.rs new file +11
-0+// INVARIANT: The container is empty and we set `init` to `0`. +Self { + value:Opaque ::uninit (), + init:Atomic ::new (0 ), + } + } + +/// Get a reference to the contained object. +/// +/// Returns [`None`] if this [`OnceLock`] is empty. +pub fn as_ref (&self) ->Option <&T > {
Looks like the get method in the OnceLock.
rust/kernel/sync/once_lock.rs line 76
Quoted 12 lines
rust/kernel/sync/once_lock.rs new file +12
-0+if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { &*self.value.get () }) + }else { +None + } + } + +/// Populate the [`OnceLock`]. +/// +/// Returns `true` if the [`OnceLock`] was successfully populated. +pub fn populate (&self, value:T ) ->bool {
Looks like set in OnceLock.
Might also be worth implementing get_or_{try,}init, which get the value while initializing.
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) { +// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else {
rust/kernel/sync/once_lock.rs line 96
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+false + } + } +} + +impl <T :Copy >OnceLock <T > { +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > {
No equivalent in OnceLock. Similar to something like this:
x.get().copied().unwrap(); // x is a OnceLock
Maybe not specifically needed?
Quoted 9 lines
rust/kernel/sync/once_lock.rs new file +8
-0+if self.init.load (Acquire ) ==2 { +// SAFETY: As determined by the load above, the object is ready for shared access. +Some (unsafe { *self.value.get () }) + }else { +None + } + } +}
Signature · 1 line
You're more amazing than you think!
Andreas Hindborg
reviewerRe: [PATCH v14 1/7] rust: sync: add `OnceLock`
Quoted 1 line · Wren Turkal
On 7/2/25 6:18 AM, Andreas Hindborg wrote:
[...]
Quoted 13 lines
rust/kernel/sync/once_lock.rs line 41
Quoted 4 lines
rust/kernel/sync/once_lock.rs new file +4
-0+pub struct OnceLock <T > { + init:Atomic <u32 >, + value:Opaque <T >, +}This type looks very much like the Once type in rust's stdlib. I am wondering if the api could be changed to match that api. I know that this type is trying to provide a version subset of
std::sync::OnceLockthat doesn't allow resetting the type like these apis:* https://doc.rust-lang.org/std/sync/struct.OnceLock.html#method.get_mut
* https://doc.rust-lang.org/std/sync/struct.OnceLock.html#method.take
Quoted 6 lines
However, these methods can only be used on mut. See here for failing example:
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=a78e51203c5b9555e3c151e162f0acabI think it might make more sense to match the api of the stdlib API and maybe only implement the methods you need.
I agree, it would be nice to match the names to std. But I do not like that they have OnceLock::set, OnceLock::try_init and OnceLock::get_or{_try}_init. Why is it not OnceLock::init or OnceLock::try_set?
Quoted 9 lines
rust/kernel/sync/once_lock.rs line 47
Quoted 7 lines
rust/kernel/sync/once_lock.rs new file +6
-0+ +impl <T >Default for OnceLock <T > { +fn default () ->Self { +Self ::new () + } +}Any reason not to use #[derive(Default)]?
We don't have Default for neither Atomic or Opaque.
[...]
Quoted 2 lines
Might also be worth implementing get_or_{try,}init, which get the value while initializing.
I did not have a user for those, so not adding for now. It would be dead code. They should be fairly straight forward to add though.
Quoted 24 lines
Quoted 11 lines
rust/kernel/sync/once_lock.rs new file +10
-0+// INVARIANT: We obtain exclusive access to the contained allocation and write 1 to +// `init`. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Acquire ) { +// SAFETY: We obtained exclusive access to the contained object. +unsafe { core::ptr::write (self.value.get (), value) }; +// INVARIANT: We release our exclusive access and transition the object to shared +// access. + self.init.store (2 ,Release ); +true + }else {rust/kernel/sync/once_lock.rs line 96
Quoted 10 lines
rust/kernel/sync/once_lock.rs new file +10
-0+false + } + } +} + +impl <T :Copy >OnceLock <T > { +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`OnceLock`] is empty. +pub fn copy (&self) ->Option <T > {No equivalent in OnceLock. Similar to something like this:
Quoted 6 lines
x.get().copied().unwrap(); // x is a OnceLock
Maybe not specifically needed?
I don't actually have a user for this, so I think I will drop it.
Best regards,
Andreas Hindborg
Andreas Hindborg
reviewerPATCH v14 2/7 rust: str: add radix prefixed integer parsing functions
In reply to Andreas HindborgAdd 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 | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+)
rust/kernel/str.rs +2 -0
@@ -8,6 +8,8 @@use crate ::prelude::*; +pub mod parse_int; +/// Byte string without UTF-8 validity guarantee. #[repr(transparent)] pub struct BStr ([u8 ]);
rust/kernel/str/parse_int.rs new file +148 -0
148 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v14 3/7 rust: introduce module_param module
In reply to Andreas HindborgAdd types and traits for interfacing the C moduleparam API.
--- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 191 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 192 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -87,6 +87,7 @@pub mod list;pub mod miscdevice;pub mod mm; +pub mod module_param;#[cfg( CONFIG_NET )] pub mod net;pub mod of;
rust/kernel/module_param.rs new file +191 -0
191 lines not on this page · raw message
Signature · 1 line
2.47.2
Re: [PATCH v14 3/7] rust: introduce module_param module
Quoted 3 lines · Andreas Hindborg
Add types and traits for interfacing the C moduleparam API.
Signed-off-by Andreas Hindborg <[email protected]>
I have some nits below, but overall
Quoted 4 lines
--- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 191 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 192 insertions(+)
I really like how the OnceLock usage turned out here! Thanks for the quick impl!
Quoted 24 lines
rust/kernel/lib.rs +1
-0@@ -87,6 +87,7 @@pub mod list;pub mod miscdevice;pub mod mm; +pub mod module_param;#[cfg( CONFIG_NET )] pub mod net;pub mod of;rust/kernel/module_param.rs new file +5
-0@@ -0,0 +1,191 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Support for module parameters. +//! +//! C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
rust/kernel/module_param.rs line 15
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+ +use crate ::prelude::*; +use crate ::str::BStr ; +use bindings; +use kernel::sync::once_lock::OnceLock ; + +/// Newtype to make `bindings::kernel_param` [`Sync`]. +#[repr(transparent)] +#[doc(hidden)] +pub struct RacyKernelParam (bindings::kernel_param );
Can you remind me why this is called Racy? Maybe add the explainer in a comment? (and if it's named racy, why is it okay?)
If it doesn't have a real reason, maybe it should be called KernelParam?
Quoted 12 lines
rust/kernel/module_param.rs new file +12
-0+ +impl RacyKernelParam { +#[doc(hidden)] +pub const fn new (val: bindings::kernel_param ) ->Self { +Self (val) + } +} + +// SAFETY: C kernel handles serializing access to this type. We never access it +// from Rust module. +unsafe impl Sync for RacyKernelParam {} +
rust/kernel/module_param.rs line 37
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+/// 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 { +/// The [`ModuleParam`] will be used by the kernel module through this type. +/// +/// This may differ from `Self` if, for example, `Self` needs to track +/// ownership without exposing it or allocate extra space for other possible +/// parameter values. +// This is required to support string parameters in the future. +type Value : ?Sized ;
This isn't used anywhere in the patchset and AFAIK the kernel is moving away from module params, so I'm not so sure if we're going to have strings as params.
Or do you already have those patches ready/plan to use strings? If not, then I think we should just remove this type and when we actually need them add it.
Quoted 17 lines
rust/kernel/module_param.rs new file +16
-0+ +/// Parse a parameter argument into the parameter value. +fn try_from_param_arg (arg: &BStr ) ->Result <Self >; +} + +impl <T >ModuleParamAccess <T > { +#[doc(hidden)] +pub const fn new (default:T ) ->Self { +Self { + value:OnceLock ::new (), + default, + } + } + +/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a
rust/kernel/module_param.rs line 154
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + } + +/// Get a mutable pointer to `self`. +/// +/// NOTE: In most cases it is not safe deref the returned pointer. +pub const fn as_void_ptr (&self) -> *mut c_void { + (selfas *const Self ).cast_mut ().cast ()
There is core::ptr::from_ref that we should use instead of the as cast.
---
Cheers,
Benno
Quoted 37 lines
rust/kernel/module_param.rs new file +37
-0+ } +} + +#[doc(hidden)] +/// Generate a static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) struct. +/// +/// # Examples +/// +/// ```ignore +/// make_param_ops!( +/// /// Documentation for new param ops. +/// PARAM_OPS_MYTYPE, // Name for the static. +/// MyType // A type which implements [`ModuleParam`]. +/// ); +/// ``` +macro_rules! make_param_ops { + ($ops:ident, $ty:ty) => { +#[doc(hidden)] +pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops { + flags:0 , + set:Some (set_param ::<$ty>), + get:None , + free:None , + }; + }; +} + +make_param_ops! (PARAM_OPS_I8 ,i8 ); +make_param_ops! (PARAM_OPS_U8 ,u8 ); +make_param_ops! (PARAM_OPS_I16 ,i16 ); +make_param_ops! (PARAM_OPS_U16 ,u16 ); +make_param_ops! (PARAM_OPS_I32 ,i32 ); +make_param_ops! (PARAM_OPS_U32 ,u32 ); +make_param_ops! (PARAM_OPS_I64 ,i64 ); +make_param_ops! (PARAM_OPS_U64 ,u64 ); +make_param_ops! (PARAM_OPS_ISIZE ,isize ); +make_param_ops! (PARAM_OPS_USIZE ,usize );
Andreas Hindborg
reviewerRe: [PATCH v14 3/7] rust: introduce module_param module
Quoted 55 lines · Benno Lossin
Quoted 3 lines · Andreas Hindborg
Add types and traits for interfacing the C moduleparam API.
Signed-off-by Andreas Hindborg <[email protected]>I have some nits below, but overall
Reviewed-by Benno Lossin <[email protected]>Quoted 4 lines
--- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 191 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 192 insertions(+)I really like how the
OnceLockusage turned out here! Thanks for the quick impl!Quoted 24 lines
rust/kernel/lib.rs +1
-0@@ -87,6 +87,7 @@pub mod list;pub mod miscdevice;pub mod mm; +pub mod module_param;#[cfg( CONFIG_NET )] pub mod net;pub mod of;rust/kernel/module_param.rs new file +5
-0@@ -0,0 +1,191 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Support for module parameters. +//! +//! C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h) rust/kernel/module_param.rs line 15
Quoted 10 lines
rust/kernel/module_param.rs new file +10
-0+ +use crate ::prelude::*; +use crate ::str::BStr ; +use bindings; +use kernel::sync::once_lock::OnceLock ; + +/// Newtype to make `bindings::kernel_param` [`Sync`]. +#[repr(transparent)] +#[doc(hidden)] +pub struct RacyKernelParam (bindings::kernel_param );Can you remind me why this is called
Racy? Maybe add the explainer in a comment? (and if it's named racy, why is it okay?)
Quoted 2 lines
If it doesn't have a real reason, maybe it should be called
KernelParam?
It is an inherited name from way back. The type exists to allow a static bindings::kernel_param, as this C type is not Sync.
I agree, it should just be KernelParam.
Quoted 19 lines
Quoted 19 lines
rust/kernel/module_param.rs new file +18
-0+ +impl RacyKernelParam { +#[doc(hidden)] +pub const fn new (val: bindings::kernel_param ) ->Self { +Self (val) + } +} + +// SAFETY: C kernel handles serializing access to this type. We never access it +// from Rust module. +unsafe impl Sync for RacyKernelParam {} + +/// 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 { +/// The [`ModuleParam`] will be used by the kernel module through this type. +/// +/// This may differ from `Self` if, for example, `Self` needs to track
Quoted 8 lines
rust/kernel/module_param.rs line 37
Quoted 4 lines
rust/kernel/module_param.rs new file +4
-0+/// ownership without exposing it or allocate extra space for other possible +/// parameter values. +// This is required to support string parameters in the future. +type Value : ?Sized ;This isn't used anywhere in the patchset and AFAIK the kernel is moving away from module params, so I'm not so sure if we're going to have strings as params.
The kernel dropping module parameters depends on who you ask. But regardless, we should probably remove it for now.
Quoted 4 lines
Or do you already have those patches ready/plan to use strings? If not, then I think we should just remove this type and when we actually need them add it.
They are in the old rust branch and they need some work. I do not have a user for them, which is why I am not including them in this series.
Quoted 23 lines
Quoted 23 lines
rust/kernel/module_param.rs new file +21
-0+ +/// Parse a parameter argument into the parameter value. +fn try_from_param_arg (arg: &BStr ) ->Result <Self >; +} + +impl <T >ModuleParamAccess <T > { +#[doc(hidden)] +pub const fn new (default:T ) ->Self { +Self { + value:OnceLock ::new (), + default, + } + } + +/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a +// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + } +
Quoted 8 lines
rust/kernel/module_param.rs line 154
Quoted 5 lines
rust/kernel/module_param.rs new file +5
-0+/// Get a mutable pointer to `self`. +/// +/// NOTE: In most cases it is not safe deref the returned pointer. +pub const fn as_void_ptr (&self) -> *mut c_void { + (selfas *const Self ).cast_mut ().cast ()There is
core::ptr::from_refthat we should use instead of theascast.
Cool 👍
Best regards,
Andreas Hindborg
Re: [PATCH v14 3/7] rust: introduce module_param module
Quoted 2 lines · Andreas Hindborg
It is an inherited name from way back.
Yeah, that name comes from one of the very first PRs. I think we may have discussed its name in one of the early calls or maybe I just came up with the name.
Either way, it is almost 5 years old so I would suggest taking a look at naming etc. with fresh eyes.
Cheers,
Miguel
Danilo Krummrich
reviewerRe: [PATCH v14 3/7] rust: introduce module_param module
In reply to Andreas Hindborgrust/kernel/module_param.rs line 148
Quoted 6 lines · Andreas Hindborg
rust/kernel/module_param.rs new file +6
-0+/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a +// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + }
I think you forgot to rename this.
Andreas Hindborg
reviewerRe: [PATCH v14 3/7] rust: introduce module_param module
Quoted 9 lines · Danilo Krummrich
rust/kernel/module_param.rs line 148
Quoted 6 lines · Andreas Hindborg
rust/kernel/module_param.rs new file +6
-0+/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a +// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + }I think you forgot to rename this.
Yes, thanks for being persistent on this :)
Best regards,
Andreas Hindborg
Andreas Hindborg
reviewerRe: [PATCH v14 3/7] rust: introduce module_param module
Quoted 10 lines · Andreas Hindborg
Quoted 8 lines · Danilo Krummrich
Quoted 6 lines · Andreas Hindborg
rust/kernel/module_param.rs new file +6
-0+/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a +// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + }
Quoted 3 lines
Quoted 1 line
I think you forgot to rename this.
Yes, thanks for being persistent on this :)
Actually, there is a discussion on whether to keep the API similar to std::sync::OnceLock [1] but also whether to rename this to something other than OnceLock [2]. Depending on how that resolves, it might make sense to stay with get or rename to something else.
Best regards,
Andreas Hindborg
[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/CAH5fLggY2Ei14nVJzLBEoR1Rut1GKU4SZX=+14tuRH1aSuQVTA@mail.gmail.com
Benno Lossin
reviewerRe: [PATCH v14 3/7] rust: introduce module_param module
Quoted 12 lines · Andreas Hindborg
Quoted 10 lines · Andreas Hindborg
Quoted 8 lines · Danilo Krummrich
Quoted 6 lines · Andreas Hindborg
rust/kernel/module_param.rs new file +6
-0+/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a +// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + }
Quoted 8 lines
Quoted 3 lines
Quoted 1 line
I think you forgot to rename this.
Yes, thanks for being persistent on this :)
Actually, there is a discussion on whether to keep the API similar to
std::sync::OnceLock[1] but also whether to rename this to something other thanOnceLock[2]. Depending on how that resolves, it might make sense to stay withgetor rename to something else.
But this is for the ModuleParamAccess, right? There I think it makes sense to choose access or value.
---
Cheers,
Benno
Quoted 6 lines
Best regards,
Andreas Hindborg[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/CAH5fLggY2Ei14nVJzLBEoR1Rut1GKU4SZX=+14tuRH1aSuQVTA@mail.gmail.com
Andreas Hindborg
reviewerRe: [PATCH v14 3/7] rust: introduce module_param module
Quoted 17 lines · Benno Lossin
Quoted 16 lines · Andreas Hindborg
Quoted 13 lines · Andreas Hindborg
Quoted 9 lines · Danilo Krummrich
rust/kernel/module_param.rs line 148
Quoted 6 lines · Andreas Hindborg
rust/kernel/module_param.rs new file +6
-0+/// Get a shared reference to the parameter value. +// Note: When sysfs access to parameters are enabled, we have to pass in a +// held lock guard here. +pub fn get (&self) -> &T { + self.value.as_ref ().unwrap_or (&self.default) + }I think you forgot to rename this.
Yes, thanks for being persistent on this :)
Quoted 7 lines
Quoted 4 lines
Actually, there is a discussion on whether to keep the API similar to
std::sync::OnceLock[1] but also whether to rename this to something other thanOnceLock[2]. Depending on how that resolves, it might make sense to stay withgetor rename to something else.But this is for the
ModuleParamAccess, right? There I think it makes sense to chooseaccessorvalue.
Right, sorry. My context window was too small here.
Best regards,
Andreas Hindborg
Andreas Hindborg
reviewerPATCH v14 4/7 rust: module: use a reference in macros::module::module
In reply to Andreas HindborgWhen we add parameter support to the module macro, we want to be able to pass a reference to ModuleInfo to a helper function. That is not possible when we move out of the local modinfo. So change the function to access the local via reference rather than value.
--- rust/macros/module.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-)
rust/macros/module.rs +10 -10
@@ -179,26 +179,26 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {// Rust does not allow hyphens in identifiers, use underscore instead. let ident = info.name.replace ('-' ,"_" );let mut modinfo =ModInfoBuilder ::new (ident.as_ref ()); -if let Some (author) = info.author { - modinfo.emit ("author" , &author); +if let Some (author) = &info.author { + modinfo.emit ("author" , author); } -if let Some (authors) = info.authors { +if let Some (authors) = &info.authors {for authorin authors { - modinfo.emit ("author" , &author); + modinfo.emit ("author" , author); } } -if let Some (description) = info.description { - modinfo.emit ("description" , &description); +if let Some (description) = &info.description { + modinfo.emit ("description" , description); } modinfo.emit ("license" , &info.license); -if let Some (aliases) = info.alias { +if let Some (aliases) = &info.alias {for aliasin aliases { - modinfo.emit ("alias" , &alias); + modinfo.emit ("alias" , alias); } } -if let Some (firmware) = info.firmware { +if let Some (firmware) = &info.firmware {for fwin firmware { - modinfo.emit ("firmware" , &fw); + modinfo.emit ("firmware" , fw); } }
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v14 5/7 rust: module: update the module macro with module parameter support
In reply to Andreas HindborgAllow module parameters to be declared in the rust module! macro.
--- rust/macros/helpers.rs | 25 +++++++ rust/macros/lib.rs | 31 +++++++++ rust/macros/module.rs | 177 ++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 223 insertions(+), 10 deletions(-)
rust/macros/helpers.rs +25 -0
@@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { } } +pub (crate )fn try_sign (it: &mut token_stream::IntoIter ) ->Option <char > { +let peek = it.clone ().next (); +match peek { +Some (TokenTree ::Punct (punct))if punct.as_char () =='-' => { +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 ())
@@ -103,3 +114,17 @@ pub(crate) fn file() -> String { proc_macro::Span ::call_site ().file () } } + +/// Parse a token stream of the form `expected_name: "value",` and return the +/// string in the position of "value". +/// +/// # Panics +/// +/// - On parse error. +pub (crate )fn expect_string_field (it: &mut token_stream::IntoIter , expected_name: &str ) ->String { +assert_eq! (expect_ident (it), expected_name); +assert_eq! (expect_punct (it),':' ); +let string =expect_string (it); +assert_eq! (expect_punct (it),',' ); + string +}
rust/macros/lib.rs +31 -0
@@ -28,6 +28,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
@@ -44,6 +68,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);
@@ -52,6 +82,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 +167 -10
251 lines not on this page · raw message
Signature · 1 line
2.47.2
Re: [PATCH v14 5/7] rust: module: update the module macro with module parameter support
Quoted 3 lines · Andreas Hindborg
Allow module parameters to be declared in the rust
module!macro.Signed-off-by Andreas Hindborg <[email protected]>
A few nits below, with those fixed
Quoted 19 lines
--- rust/macros/helpers.rs | 25 +++++++ rust/macros/lib.rs | 31 +++++++++ rust/macros/module.rs | 177 ++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 223 insertions(+), 10 deletions(-)rust/macros/module.rs +13
-0+fn emit_params (&mut self, info: &ModuleInfo ) { +let Some (params) = &info.paramselse { +return ; + }; + +for paramin params { +let ops =param_ops_path (¶m.ptype); + +// Note: The spelling of these fields is dictated by the user space +// tool `modinfo`. + self.emit_param ("parmtype" , ¶m.name, ¶m.ptype); + self.emit_param ("parm" , ¶m.name, ¶m.description); +
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 130
Quoted 10 lines
rust/macros/module.rs +10
-0+write! ( + self.param_buffer, + " + pub(crate) static {param_name}: + ::kernel::module_param::ModuleParamAccess<{param_type}> = + ::kernel::module_param::ModuleParamAccess::new({param_default}); + + #[link_section = \"__param\"] + #[used] +static __{module_name}_{param_name}_struct:
Does it make sense to move this static to a const _: () = {}; block?
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 134
Quoted 4 lines
rust/macros/module.rs +4
-0+ ::kernel::module_param::RacyKernelParam = + ::kernel::module_param::RacyKernelParam::new( + ::kernel::bindings::kernel_param {{ + name: if cfg!(MODULE) {{
s/cfg/::core::cfg/
:)
Also there seems to only be a 2-space indentation here.
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 146
Quoted 12 lines
rust/macros/module.rs +12
-0+ ::kernel::c_str!(\"{param_name}\").as_bytes_with_nul() + }} else {{ + ::kernel::c_str!(\"{module_name}.{param_name}\").as_bytes_with_nul() + }}.as_ptr(), +// SAFETY: `__this_module` is constructed by the kernel at load time +// and will not be freed until the module is unloaded. +#[cfg( MODULE )] + mod_: unsafe {{ + (&::kernel::bindings::__this_module +as *const ::kernel::bindings::module ) + .cast_mut () + }},
It doesn't stop with the improvements...
https://github.com/Rust-for-Linux/linux/issues/1176
Maybe we should also have one to use it here, but eh we can do that later (and it's not as bad to forget about :)
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 149
Quoted 3 lines
rust/macros/module.rs +3
-0+#[cfg(not( MODULE ))] + mod_: ::core::ptr::null_mut(), + ops: &{ops} as *const ::kernel::bindings::kernel_param_ops,
::core::ptr::from_ref(&{ops})rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 7 lines
rust/macros/module.rs +7
-0+ perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},
Formatting?
+ __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {{
+ arg: {param_name}.as_void_ptr()
+ }},
---
Cheers,
Benno
Quoted 13 lines
rust/macros/module.rs +13
-0+ }} + ); + ", + module_name = info.name, + param_type = param.ptype, + param_default = param.default, + param_name = param.name, + ops = ops, + ) + .unwrap (); + } + } +}
Andreas Hindborg
reviewerRe: [PATCH v14 5/7] rust: module: update the module macro with module parameter support
Quoted 32 lines · Benno Lossin
Quoted 3 lines · Andreas Hindborg
Allow module parameters to be declared in the rust
module!macro.Signed-off-by Andreas Hindborg <[email protected]>A few nits below, with those fixed
Reviewed-by Benno Lossin <[email protected]>Quoted 23 lines
--- rust/macros/helpers.rs | 25 +++++++ rust/macros/lib.rs | 31 +++++++++ rust/macros/module.rs | 177 ++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 223 insertions(+), 10 deletions(-)rust/macros/module.rs +17
-0+fn emit_params (&mut self, info: &ModuleInfo ) { +let Some (params) = &info.paramselse { +return ; + }; + +for paramin params { +let ops =param_ops_path (¶m.ptype); + +// Note: The spelling of these fields is dictated by the user space +// tool `modinfo`. + self.emit_param ("parmtype" , ¶m.name, ¶m.ptype); + self.emit_param ("parm" , ¶m.name, ¶m.description); + +write! ( + self.param_buffer, + " +pub (crate )static {param_name}:
Quoted 8 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 130
Quoted 6 lines
rust/macros/module.rs +6
-0+ ::kernel::module_param::ModuleParamAccess<{param_type}> = + ::kernel::module_param::ModuleParamAccess ::new ({param_default}); + + #[link_section = \"__param\"] +#[used] + static __{module_name}_{param_name}_struct:Does it make sense to move this static to a
const _: () = {};block?
Yes, that makes sense.
Quoted 7 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 134
Quoted 5 lines
rust/macros/module.rs +4
-0+ ::kernel::module_param::RacyKernelParam = + ::kernel::module_param::RacyKernelParam::new( + ::kernel::bindings::kernel_param {{ + name: if cfg!(MODULE) {{s/cfg/::core::cfg/
OK.
Quoted 4 lines
:)
Also there seems to only be a 2-space indentation here.
Fixed.
Quoted 14 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 146
Quoted 13 lines
rust/macros/module.rs +12
-0+ ::kernel::c_str!(\"{param_name}\").as_bytes_with_nul() + }} else {{ + ::kernel::c_str!(\"{module_name}.{param_name}\").as_bytes_with_nul() + }}.as_ptr(), +// SAFETY: `__this_module` is constructed by the kernel at load time +// and will not be freed until the module is unloaded. +#[cfg( MODULE )] + mod_: unsafe {{ + (&::kernel::bindings::__this_module +as *const ::kernel::bindings::module ) + .cast_mut () + }},
Quoted 6 lines
It doesn't stop with the improvements...
https://github.com/Rust-for-Linux/linux/issues/1176Maybe we should also have one to use it here, but eh we can do that later (and it's not as bad to forget about :)
Applying from_ref.
Quoted 6 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 149
Quoted 4 lines
rust/macros/module.rs +3
-0+#[cfg(not( MODULE ))] + mod_: ::core::ptr::null_mut(), + ops: &{ops} as *const ::kernel::bindings::kernel_param_ops,::core::ptr::from_ref(&{ops})
👍
Quoted 11 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 8 lines
rust/macros/module.rs +7
-0+ perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},Formatting?
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 3 lines
rust/macros/module.rs +3
-0+ __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},
That makes the line more than 100 characters after changing other formatting things. Perhaps I should just left shift all this?
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v14 5/7] rust: module: update the module macro with module parameter support
Quoted 12 lines · Andreas Hindborg
Quoted 11 lines · Benno Lossin
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 7 lines · Andreas Hindborg
rust/macros/module.rs +7
-0+ perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},Formatting?
Quoted 7 lines
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 3 lines
rust/macros/module.rs +3
-0+ __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},That makes the line more than 100 characters after changing other formatting things. Perhaps I should just left shift all this?
Not sure what you mean by left shift? When I tried it, it was fine, but it could have changed with the other things... Do you have a branch with your changes?
---
Cheers,
Benno
Andreas Hindborg
reviewerRe: [PATCH v14 5/7] rust: module: update the module macro with module parameter support
Quoted 18 lines · Benno Lossin
Quoted 17 lines · Andreas Hindborg
Quoted 14 lines · Benno Lossin
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 7 lines · Andreas Hindborg
rust/macros/module.rs +7
-0+ perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},Formatting?
rust/macros/module.rs +3
-0+ __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},
Quoted 6 lines
Quoted 2 lines
That makes the line more than 100 characters after changing other formatting things. Perhaps I should just left shift all this?
Not sure what you mean by left shift? When I tried it, it was fine, but it could have changed with the other things... Do you have a branch with your changes?
Move all the code template so the least indented start at column 0.
My WIP branch is here [1].
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v14 5/7] rust: module: update the module macro with module parameter support
Quoted 22 lines · Andreas Hindborg
Quoted 21 lines · Benno Lossin
Quoted 19 lines · Andreas Hindborg
Quoted 11 lines · Benno Lossin
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 7 lines · Andreas Hindborg
rust/macros/module.rs +7
-0+ perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},Formatting?
rust/macros/module.rs fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { · line 156
Quoted 3 lines
rust/macros/module.rs +3
-0+ __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr () + }},That makes the line more than 100 characters after changing other formatting things. Perhaps I should just left shift all this?
Quoted 7 lines
Quoted 3 lines
Not sure what you mean by left shift? When I tried it, it was fine, but it could have changed with the other things... Do you have a branch with your changes?
Move all the code template so the least indented start at column 0.
My WIP branch is here [1].
If you dedent the contents of the string once, then everything fits in 100 columns.
---
Cheers,
Benno
Quoted 5 lines
Best regards,
Andreas Hindborg
Andreas Hindborg
reviewerPATCH v14 6/7 rust: samples: add a module parameter to the rust_minimal sample
In reply to Andreas HindborgShowcase the rust module parameter support by adding a module parameter to the rust_minimal sample.
--- samples/rust/rust_minimal.rs | 10 ++++++++++ 1 file changed, 10 insertions(+)
samples/rust/rust_minimal.rs +10 -0
@@ -10,6 +10,12 @@ authors: ["Rust for Linux Contributors"], description: "Rust minimal sample", license: "GPL", + params: { + test_parameter: i64 { + default: 1, + description:"This parameter has a default of 1" , + }, + }, }struct RustMinimal {
@@ -20,6 +26,10 @@ impl kernel::Module for RustMinimal {fn init (_module: &'staticThisModule ) ->Result <Self > {pr_info! ("Rust minimal sample (init)\n" );pr_info! ("Am I built-in? {}\n" , !cfg! (MODULE )); +pr_info! ( +"test_parameter: {}\n" , + *module_parameters::test_parameter.get () + );let mut numbers =KVec ::new (); numbers.push (72 ,GFP_KERNEL )?;
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v14 7/7 modules: add rust modules files to MAINTAINERS
In reply to Andreas HindborgThe module subsystem people agreed to maintain rust support for modules [1]. Thus, add entries for relevant files to modules entry in MAINTAINERS.
--- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+)
MAINTAINERS +2 -0
@@ -16796,6 +16796,8 @@ F: include/linux/module*.h F: kernel/module/ F: lib/test_kmod.c F: lib/tests/module/ +F: rust/kernel/module_param.rs +F: rust/macros/module.rs F: scripts/module* F: tools/testing/selftests/kmod/ F: tools/testing/selftests/module/
Signature · 1 line
2.47.2