rust: configfs abstractions
Subsystems (3)
Andreas Hindborg
maintainerv6 cover rust: configfs abstractions
Add a safe Rust API that allows Rust modules to interface the configfs machinery.
Add an example for the samples folder to demonstrate usage of the API.
Add a maintainer entry for the Rust configfs abstractions in the last patch, to make it absolutely clear that I will commit to maintain these abstractions, if required.
The series is a dependency of rnull, the Rust null block driver. Please see [1] for initial configfs support in rnull.
[1] https://github.com/metaspace/linux/tree/9ac53130f5fb05b9b3074fa261b445b8fde547dd/drivers/block/rnull
---
Changes in v6:
- Use &raw const and &raw mut instead of addr_of! and addr_of_mut! macros.
- Drop use of ForeignOwnable.
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Remove as _ casts.
- Document ID type parameter of AttributeOperations.
- Add documentation at macro call sites in example.
- Add example expansion of configfs_attrs!.
- Move trait bound in AttributeList::add
- Improve safety requirement for AttributeList::new.
- Fix a copy/paste error in print in sample.
- Clarify use of {} for empty struct in sample.
- Improve documentation for AttributeList.
- Remove kernel:: prefix from container_of! invocation.
- Reword safety comment in get_group_data.
- Correct commit message in relation to unstable feature additions.
- Use imperative language in commit messages.
- Consistently capitalize the word "Rust" in commit messages.
- Explain that "drop" in GroupOperations::drop_item is not related to Rust drop.
- Link to v4: https://lore.kernel.org/r/[email protected]
Changes in v4:
- Fix a build issue by depending on v18 of "rust: types: add ForeignOwnable::PointedTo"
- Link to v3: https://lore.kernel.org/r/[email protected]
Changes in v3:
- Allow trailing commas in invocation of configfs_attrs!.
- Use a more suitable C initialization function when initializing Subsystem.
- Split sample into separate patch.
- Add an inline example.
The remaining changes in this version are style fixes, documentation improvements and typo fixes. They are enumerated below:
- Consolidate paste macro calls.
- Do not hard code page size in example.
- Remove prefix of c_str! in sample.
- Use a more descriptive variable name in into_foreign.
- Improve code formatting in macros invocations.
- Add comment related to null terminator in configfs_attrs!
- Move attributes below docstrings.
- Remove a rogue todo.
- Remove trait bound from struct definition GroupOperationsVTable.
- Remove as _ casts.
- Remove GroupOprations::Parent associated type.
- General documentation improvements.
- Explicitly use ArcBorrow for drop_item parameter type.
- Add a comment describing expansion to a call to Attribute::add.
- Add a comment explaining bound check in Attribute::add.
- Link to v2: https://lore.kernel.org/r/[email protected]
Changes in v2:
- Remove generalization over pointer type and enforce use of Arc.
- Use type system to enforce connection between ItemType and Subsystem or Group. Differentiate construction of vtables on this type difference.
- Move drop logic of child nodes from parent to child.
- Pick ForeignOwnable::PointedTo patch as dependency instead of including it here.
- Fix some rustdoc warnings.
- Use CamelCase for generic type parameter declaration.
- Destroy mutex in Subsystem::drop.
- Move GroupOperationsVTable struct definition next to implementation.
- Rebase on v6.14-rc1.
- Link to v1: https://lore.kernel.org/r/[email protected]
---
Andreas Hindborg (3):
rust: configfs: introduce rust support for configfs
rust: configfs: add a sample demonstrating configfs usage
MAINTAINERS: add configfs Rust abstractions
MAINTAINERS | 2 + rust/bindings/bindings_helper.h | 1 + rust/helpers/mutex.c | 5 + rust/kernel/configfs.rs | 1048 +++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 +++++++ 8 files changed, 1262 insertions(+)
---
base-commit: b4432656b36e5cc1d50a1f2dc15357543add530e
change-id: 20250131-configfs-b888cd82d84a
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
maintainerPATCH v6 1/3 rust: configfs: introduce rust support for configfs
Add a Rust API for configfs, thus allowing Rust modules to use configfs for configuration. Make the implementation a shim on top of the C configfs implementation, allowing safe use of the C infrastructure from Rust.
---
This patch is a direct dependency for rnull, the rust null block driver.
--- rust/bindings/bindings_helper.h | 1 + rust/helpers/mutex.c | 5 + rust/kernel/configfs.rs | 1048 +++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 1056 insertions(+)
rust/bindings/bindings_helper.h +1 -0
@@ -10,6 +10,7 @@#include <linux/blk-mq.h> #include <linux/blk_types.h> #include <linux/blkdev.h> +#include <linux/configfs.h> #include <linux/cpumask.h> #include <linux/cred.h> #include <linux/device/faux.h>
rust/helpers/mutex.c +5 -0
@@ -17,3 +17,8 @@ void rust_helper_mutex_assert_is_held(struct mutex *mutex) {lockdep_assert_held (mutex); } + +void rust_helper_mutex_destroy (struct mutex *lock) +{ +mutex_destroy (lock); +}
rust/kernel/configfs.rs new file +1048 -0
1,048 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -42,6 +42,8 @@pub mod block;#[doc(hidden)] pub mod build_assert; +#[cfg( CONFIG_CONFIGFS_FS )] +pub mod configfs;pub mod cred;pub mod device;pub mod device_id;
Signature · 1 line
2.47.2
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 5 lines · Andreas Hindborg
Signed-off-by Andreas Hindborg <[email protected]>---
Spurious newlines.
Quoted 2 lines
This patch is a direct dependency for
rnull, the rust null block driver.
---
By the way, you don't need this ---.
Quoted 1 line
+//!
configfsinterface.
I don't know if configfs is supposed to be written in code spans, but I appreciate you are trying to be throughout in your Markdown use ;) It may be easier to read to not have it in code spans, since we have many already and it is not code anyway.
By the way, you may want to mention somehow the title they use in their docs: "Userspace-driven Kernel Object Configuration".
Quoted 1 line
+//! See the [
rust_configfs.rs] sample for a full example use of this module.
Files are, though, like the C header below, so: [rust_configfs.rs]
Quoted 1 line
+/// with configfs, embed a field of this type into your kernel module struct.
Either with or without a code span, i.e. being consistent is best.
Quoted 1 line
+ /// Return the address of the
bindings::config_groupembedded inSelf.
I think you may be able to use intra-doc links for [Self].
rust/kernel/configfs.rs line 557
Quoted 4 lines
rust/kernel/configfs.rs new file +4
-0+let c_group: *mut bindings::config_group = +// SAFETY: By function safety requirements, `item` is embedded in a +// `config_group`. +unsafe {container_of! (item, bindings::config_group, cg_item) }.cast_mut ();
It doesn't work to put the safety comment on top? (We had issues similar to this in the past, so if it is intentional, that is fine).
rust/kernel/configfs.rs line 679
Quoted 2 lines
rust/kernel/configfs.rs new file +2
-0+/// This type is constructed statically at compile time and is by the +/// [`kernel::configfs_attrs`] macro.
Sentence is missing something. Also, we never used # Note yet, but I guess it is fine.
Quoted 1 line
+ /// Null terminated Array of pointers to
Attribute. The type isc_void
Intar-doc link(s)?
rust/kernel/configfs.rs line 718
Quoted 4 lines
rust/kernel/configfs.rs new file +4
-0+// We need a space at the end of our list for a null terminator. +if I >=N -1 { + kernel::build_error!("Invalid attribute index" ); + }
Would the following work instead?
const { assert!(I < N - 1, "Invalid attribute index") };(Please double-check it actually catches the cases you need)
Thanks!
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 8 lines · Miguel Ojeda
Quoted 5 lines · Andreas Hindborg
Signed-off-by Andreas Hindborg <[email protected]>---
Spurious newlines.
The one just before the cut?
Quoted 5 lines
Quoted 3 lines
This patch is a direct dependency for
rnull, the rust null block driver.
---By the way, you don't need this
---.
b4 adds it 🤷
Quoted 7 lines
Quoted 2 lines
+//!
configfsinterface.I don't know if configfs is supposed to be written in code spans, but I appreciate you are trying to be throughout in your Markdown use ;) It may be easier to read to not have it in code spans, since we have many already and it is not code anyway.
OK
Quoted 3 lines
By the way, you may want to mention somehow the title they use in their docs: "Userspace-driven Kernel Object Configuration".
Will do.
Quoted 4 lines
Quoted 2 lines
+//! See the [
rust_configfs.rs] sample for a full example use of this module.Files are, though, like the C header below, so: [
rust_configfs.rs]
OK
Quoted 4 lines
Quoted 2 lines
+/// with configfs, embed a field of this type into your kernel module struct.
Either with or without a code span, i.e. being consistent is best.
I am! Consistently inconsistent. Very much so in this series. Will fix.
Quoted 4 lines
Quoted 2 lines
+ /// Return the address of the
bindings::config_groupembedded inSelf.I think you may be able to use intra-doc links for [
Self].
Thanks. Would be nice with a lint for missed intra-doc links.
Quoted 8 lines
rust/kernel/configfs.rs line 557
Quoted 5 lines
rust/kernel/configfs.rs new file +4
-0+let c_group: *mut bindings::config_group = +// SAFETY: By function safety requirements, `item` is embedded in a +// `config_group`. +unsafe {container_of! (item, bindings::config_group, cg_item) }.cast_mut ();It doesn't work to put the safety comment on top? (We had issues similar to this in the past, so if it is intentional, that is fine).
Clippy gets mad if we move it up. Because rustfmt wants the unsafe block to a new line:
warning: unsafe block missing a safety comment
--> rust/kernel/configfs.rs:557:13
|
557 | unsafe { container_of!(item, bindings::config_group, cg_item) }.cast_mut();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| = help: consider adding a safety comment on the preceding line
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#undocumented_unsafe_blocks
= note: requested on the command line with -W clippy::undocumented-unsafe-blocks
Quoted 6 lines
rust/kernel/configfs.rs line 679
Quoted 3 lines
rust/kernel/configfs.rs new file +2
-0+/// This type is constructed statically at compile time and is by the +/// [`kernel::configfs_attrs`] macro. Sentence is missing something. Also, we never used
# Noteyet, but I guess it is fine.
Thanks, rephrased:
# Note
Instances of this type are constructed statically at compile by the [kernel::configfs_attrs] macro.
Quoted 10 lines
Quoted 2 lines
+ /// Null terminated Array of pointers to
Attribute. The type isc_voidIntar-doc link(s)?
rust/kernel/configfs.rs line 718
Quoted 4 lines
rust/kernel/configfs.rs new file +4
-0+// We need a space at the end of our list for a null terminator. +if I >=N -1 { + kernel::build_error!("Invalid attribute index" ); + }
Quoted 5 lines
Would the following work instead?
const { assert!(I < N - 1, "Invalid attribute index") };(Please double-check it actually catches the cases you need)
The reason I choose build_error is that if this should somehow end up being evaluated in non-const context at some point, I want the build to fail if the condition is not true. I don't think I get that with assert?
Best regards,
Andreas Hindborg
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 2 lines · Andreas Hindborg
The one just before the cut?
Both.
Quoted 1 line
Thanks. Would be nice with a lint for missed intra-doc links.
Definitely -- I filled it a while back:
https://github.com/rust-lang/rust/issues/131510
Quoted 2 lines
Clippy gets mad if we move it up. Because rustfmt wants the unsafe block to a new line:
Yeah, then it is one of the cases I was referring to. In that case, it is fine, but please indent the safety comment to match the unsafe block.
Quoted 3 lines
The reason I choose
build_erroris that if this should somehow end up being evaluated in non-const context at some point, I want the build to fail if the condition is not true. I don't think I get that with assert?
I am not sure what you mean. My understanding is that const blocks, if execution reaches them, are always evaluated at compile-time (they are a const context):
https://doc.rust-lang.org/reference/expressions/block-expr.html#const-blocks
e.g.
https://godbolt.org/z/h36s3nqWK
We are lucky to have Gary with us, since he stabilized this particular language feature, so he can correct us! :)
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 5 lines · Miguel Ojeda
Quoted 2 lines · Andreas Hindborg
The one just before the cut?
Both.
But why does that matter? Anything in the commit message after the cut is dropped when applying the patch, right?
Quoted 5 lines
Quoted 2 lines
Thanks. Would be nice with a lint for missed intra-doc links.
Definitely -- I filled it a while back:
Quoted 8 lines
https://github.com/rust-lang/rust/issues/131510Quoted 2 lines
Clippy gets mad if we move it up. Because rustfmt wants the unsafe block to a new line:
Yeah, then it is one of the cases I was referring to. In that case, it is fine, but please indent the safety comment to match the
unsafeblock.
OK. rustfmt does not seem to care about this though.
Quoted 9 lines
Quoted 4 lines
The reason I choose
build_erroris that if this should somehow end up being evaluated in non-const context at some point, I want the build to fail if the condition is not true. I don't think I get that with assert?I am not sure what you mean. My understanding is that
constblocks, if execution reaches them, are always evaluated at compile-time (they are a const context):
Quoted 8 lines
https://doc.rust-lang.org/reference/expressions/block-expr.html#const-blocks
e.g.
https://godbolt.org/z/h36s3nqWKWe are lucky to have Gary with us, since he stabilized this particular language feature, so he can correct us! :)
I might not have the full picture, but it is my understanding that while const fn are evaluated in const context when called from const context, they _may_ be called from non-const context, and then they are evaluated in non-const context if their arguments are not const [1]. They are not guaranteed to be evaluated in const context.
So my thinking is that down the road, refactoring of this code may cause the AttributeList::add to be called in a way so that it is not evaluated in const context, and then the assert would be evaluated at run time. With build_error we would get an error during build.
But I should probably use build_assert instead of the conditional with build_error.
Best regards,
Andreas Hindborg
[1] https://doc.rust-lang.org/reference/const_eval.html#r-const-eval.const-expr.list
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 3 lines · Andreas Hindborg
But why does that matter? Anything in the commit message after the cut is dropped when applying the patch, right?
Yes, but it is not common to add a newline there. I mentioned it because it looked odd, no worries.
Quoted 10 lines
I might not have the full picture, but it is my understanding that while
const fnare evaluated in const context when called from const context, they _may_ be called from non-const context, and then they are evaluated in non-const context if their arguments are not const [1]. They are not guaranteed to be evaluated in const context.So my thinking is that down the road, refactoring of this code may cause the
AttributeList::addto be called in a way so that it is not evaluated in const context, and then theassertwould be evaluated at run time. Withbuild_errorwe would get an error during build.
No, it will always be evaluated at compile-time (if it is evaluated at all).
Please see again the links I provided. There is no const fn in the example I provided, and yet it is a build error.
From your link, it is clear const blocks are a const context, which are always evaluated at compile time:
Certain forms of expressions, called constant expressions, can be evaluated at compile time.
In const contexts, these are the only allowed expressions, and are always evaluated at compile time.
A const context is one of the following: (...) A const block
And from mine, it mentions that it is guaranteed to be evaluated if execution reaches that point and that such evaluation would happen at compile time:
A const block is a variant of a block expression whose body
evaluates at compile-time instead of at runtime.
If the const block expression is executed at runtime, then the
constant is guaranteed to be evaluated, even if its return value is
ignored:
fn foo<T>() -> usize {
// If this code ever gets executed, then the assertion has
// definitely been evaluated at compile-time.
const { assert!(std::mem::size_of::<T>() > 0); }
// Here we can have unsafe code relying on the type being
// non-zero-sized.
/* ... */
42
}That example they give is precisely about using a const block for guaranteeing something that unsafe code relies on.
I hope that helps.
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 56 lines · Miguel Ojeda
Quoted 3 lines · Andreas Hindborg
But why does that matter? Anything in the commit message after the cut is dropped when applying the patch, right?
Yes, but it is not common to add a newline there. I mentioned it because it looked odd, no worries.
Quoted 10 lines
I might not have the full picture, but it is my understanding that while
const fnare evaluated in const context when called from const context, they _may_ be called from non-const context, and then they are evaluated in non-const context if their arguments are not const [1]. They are not guaranteed to be evaluated in const context.So my thinking is that down the road, refactoring of this code may cause the
AttributeList::addto be called in a way so that it is not evaluated in const context, and then theassertwould be evaluated at run time. Withbuild_errorwe would get an error during build.No, it will always be evaluated at compile-time (if it is evaluated at all).
Please see again the links I provided. There is no
const fnin the example I provided, and yet it is a build error.From your link, it is clear
constblocks are a const context, which are always evaluated at compile time:Certain forms of expressions, called constant expressions, can be evaluated at compile time.
In const contexts, these are the only allowed expressions, and are always evaluated at compile time.
A const context is one of the following: (...) A const block
And from mine, it mentions that it is guaranteed to be evaluated if execution reaches that point and that such evaluation would happen at compile time:
A const block is a variant of a block expression whose body evaluates at compile-time instead of at runtime. If the const block expression is executed at runtime, then the constant is guaranteed to be evaluated, even if its return value is ignored: fn foo<T>() -> usize { // If this code ever gets executed, then the assertion has // definitely been evaluated at compile-time. const { assert!(std::mem::size_of::<T>() > 0); } // Here we can have unsafe code relying on the type being // non-zero-sized. /* ... */ 42 }
Quoted 4 lines
That example they give is precisely about using a
constblock for guaranteeing something that unsafe code relies on.I hope that helps.
Ah - I understand. I missed that you wrapped the assert in a const block, a quite important bit 🤦 Thanks for explaining!
Best regards,
Andreas Hindborg
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 3 lines · Andreas Hindborg
Ah - I understand. I missed that you wrapped the assert in a const block, a quite important bit 🤦 Thanks for explaining!
Ah -- that explains it. Yeah, your calls to add were from const contexts, which explains what you were trying to say.
You're welcome!
Cheers,
Miguel
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 3 lines · Miguel Ojeda
Ah -- that explains it. Yeah, your calls to
addwere from const contexts, which explains what you were trying to say.
No, wait, they are not from const context. So a "normal" assert! there would have never worked.
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 8 lines · Miguel Ojeda
Quoted 3 lines · Miguel Ojeda
Ah -- that explains it. Yeah, your calls to
addwere from const contexts, which explains what you were trying to say.No, wait, they are not from const context. So a "normal"
assert!there would have never worked.
Right, they are not from const context, but they are inside a let statement, so if all the captured variables are constant (which they are), the let statement will be evaluated in const context [1], right?
Best regards,
Andreas Hindborg
[1] https://doc.rust-lang.org/reference/const_eval.html#r-const-eval.const-context.init
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 4 lines · Andreas Hindborg
Right, they are not from const context, but they are inside a
letstatement, so if all the captured variables are constant (which they are), the let statement will be evaluated in const context [1], right?
No, I don't think so. Though I don't know what you mean by "captured variables" here or why you point to [const-eval.const-context.init].
The way I read the reference is that Rust only guarantees evaluation at compile-time within const contexts, and a let statement is not a const context and its initializer is not one of the ones listed in [const-eval.const-context.init]. const fn isn't a const context either.
Which makes sense -- the let initializers are just "normal" expressions, i.e. you don't want to limit the kinds of code you can run there.
For instance, here there is a panic at runtime trying to mimic a bit the patch:
https://godbolt.org/z/v5qdK9vve
Similarly, if I take your patch and put there an assert!(false) in add -- I see no build error and objdump shows the panic call from the sample.
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 8 lines · Miguel Ojeda
Quoted 4 lines · Andreas Hindborg
Right, they are not from const context, but they are inside a
letstatement, so if all the captured variables are constant (which they are), the let statement will be evaluated in const context [1], right?No, I don't think so. Though I don't know what you mean by "captured variables" here or why you point to [const-eval.const-context.init].
I see. it is not guaranteed, but it _may_ be.
Regarding captured variables, I was referring to "any operands". From [const-eval.const-context.init]:
Const context is one of the following:
...
The initializer of statics.
From [const-eval.const-expr.list]:
The following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any Drop::drop calls to be run.
...
[const-eval.const-expr.block]:
...
let statements
So I was thinking that because I am initializing a static with a let statement, it would run in const context. But I see that it is not actually guaranteed.
Quoted 5 lines
The way I read the reference is that Rust only guarantees evaluation at compile-time within const contexts, and a
letstatement is not a const context and its initializer is not one of the ones listed in [const-eval.const-context.init].const fnisn't a const context either.
I agree. No guarantees, [const-eval.const-expr.runtime-context]:
In other places, such as let statements, constant expressions may be, but are not guaranteed to be, evaluated at compile time.
Quoted 11 lines
Which makes sense -- the
letinitializers are just "normal" expressions, i.e. you don't want to limit the kinds of code you can run there.For instance, here there is a panic at runtime trying to mimic a bit the patch:
https://godbolt.org/z/v5qdK9vveSimilarly, if I take your patch and put there an
assert!(false)inadd-- I see no build error andobjdumpshows the panic call from the sample.
Right. Which is why I opted for build_error. But with the const block solution you suggested is better.
Best regards,
Andreas Hindborg
Re: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 4 lines · Andreas Hindborg
So I was thinking that because I am initializing a static with a let statement, it would run in const context. But I see that it is not actually guaranteed.
No, that is actually guaranteed, i.e. when initializing a static. But you aren't initializing a static here, no? Which static are you referring to? If you were, then the "normal" assert! would work, because it would be a const context.
The add calls I see are just in the let statement, not initializing any static:
{
const N: usize = 0usize;
unsafe { CONFIGURATION_ATTRS.add::<N, 0,
_>(&CONFIGURATION_MESSAGE_ATTR) };
}So it also means this comment is wrong:
+ // SAFETY: This function is only called through the `configfs_attrs` + // macro. This ensures that we are evaluating the function in const + // context when initializing a static. As such, the reference created + // below will be exclusive.
Please double-check all this... :)
Quoted 2 lines
Right. Which is why I opted for
build_error. But with theconstblock solution you suggested is better.
I thought you opted for that because you thought the assert! would only work if not refactored. What I tried to point out was that the assert! wouldn't have worked even before the refactoring.
I hope that helps.
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 27 lines · Miguel Ojeda
Quoted 4 lines · Andreas Hindborg
So I was thinking that because I am initializing a static with a let statement, it would run in const context. But I see that it is not actually guaranteed.
No, that is actually guaranteed, i.e. when initializing a static. But you aren't initializing a static here, no? Which static are you referring to? If you were, then the "normal"
assert!would work, because it would be a const context.The
addcalls I see are just in theletstatement, not initializing any static:{ const N: usize = 0usize; unsafe { CONFIGURATION_ATTRS.add::<N, 0, _>(&CONFIGURATION_MESSAGE_ATTR) }; }So it also means this comment is wrong:
(quoted diff) +4
-0+ // SAFETY: This function is only called through the `configfs_attrs` + // macro. This ensures that we are evaluating the function in const + // context when initializing a static. As such, the reference created + // below will be exclusive.
Quoted 1 line
Please double-check all this... :)
Oops.
Quoted 7 lines
Quoted 3 lines
Right. Which is why I opted for
build_error. But with theconstblock solution you suggested is better.I thought you opted for that because you thought the
assert!would only work if not refactored. What I tried to point out was that theassert!wouldn't have worked even before the refactoring.
I made a mistake in thinking this was in const context. I'll see if I can fix that.
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerRe: [PATCH v6 1/3] rust: configfs: introduce rust support for configfs
Quoted 37 lines · Andreas Hindborg
Quoted 27 lines · Miguel Ojeda
Quoted 4 lines · Andreas Hindborg
So I was thinking that because I am initializing a static with a let statement, it would run in const context. But I see that it is not actually guaranteed.
No, that is actually guaranteed, i.e. when initializing a static. But you aren't initializing a static here, no? Which static are you referring to? If you were, then the "normal"
assert!would work, because it would be a const context.The
addcalls I see are just in theletstatement, not initializing any static:{ const N: usize = 0usize; unsafe { CONFIGURATION_ATTRS.add::<N, 0, _>(&CONFIGURATION_MESSAGE_ATTR) }; }So it also means this comment is wrong:
(quoted diff) +4
-0+ // SAFETY: This function is only called through the `configfs_attrs` + // macro. This ensures that we are evaluating the function in const + // context when initializing a static. As such, the reference created + // below will be exclusive.Quoted 1 line
Please double-check all this... :)
Oops.
Quoted 4 lines
Quoted 3 lines
Right. Which is why I opted for
build_error. But with theconstblock solution you suggested is better.
Quoted 6 lines
Quoted 3 lines
I thought you opted for that because you thought the
assert!would only work if not refactored. What I tried to point out was that theassert!wouldn't have worked even before the refactoring.I made a mistake in thinking this was in const context. I'll see if I can fix that.
I think I can fix it like this:
modified rust/kernel/configfs.rs
@@ -703,8 +703,8 @@ impl<const N: usize, Data> AttributeList<N, Data> {
/// # Safety
///
- /// This function can only be called by the [`kernel::configfs_attrs`]
- /// macro.
+ /// The caller must ensure that there are no other concurrent accesses to
+ /// `self`. That is, the caller has exclusive access to `self.`
#[doc(hidden)]
pub const unsafe fn add<const I: usize, const ID: u64, O>(
&'static self,
@@ -715,10 +715,8 @@ impl<const N: usize, Data> AttributeList<N, Data> {
// We need a space at the end of our list for a null terminator.
const { assert!(I < N - 1, "Invalid attribute index") };- // SAFETY: This function is only called through the
- // [kernel::`configfs_attrs`] macro. This ensures that we are evaluating
- // the function in const context when initializing a static. As such,
- // the reference created below will be exclusive.
+ // SAFETY: By function safety requirements, we have exclusive access to
+ // `self` and the reference created below will be exclusive.
unsafe {
(&mut *self.0.get())[I] = (attribute as *const Attribute<ID, O, Data>)
.cast_mut()
@@ -955,7 +953,12 @@ macro_rules! configfs_attrs {
@assign($($assign)* {
const N: usize = $cnt;
// The following macro text expands to a call to `Attribute::add`.
- // SAFETY: We are expanding [`kernel::configfs_attrs`].
+
+ // SAFETY: By design of this macro, the name of the variable we
+ // invoke the `add` method on below, is not visible outside of
+ // the macro expansion. The macro does not operate concurrently
+ // on this variable, and thus we have exclusive access to the
+ // variable.
unsafe {
$crate::macros::paste!(
[< $data:upper _ATTRS >]Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH v6 2/3 rust: configfs: add a sample demonstrating configfs usage
In reply to Andreas HindborgAdd a sample to the samples folder, demonstrating the intended use of the Rust configfs API.
--- samples/rust/Kconfig | 11 +++ samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 204 insertions(+)
samples/rust/Kconfig +11 -0
@@ -10,6 +10,17 @@ menuconfig SAMPLES_RUST if SAMPLES_RUST +config SAMPLE_RUST_CONFIGFS + tristate "Configfs sample" + depends on CONFIGFS_FS + help + This option builds the Rust configfs sample. + + To compile this as a module, choose M here: + the module will be called rust_configfs. + + If unsure, say N. + config SAMPLE_RUST_MINIMAL tristate "Minimal" help
samples/rust/Makefile +1 -0
@@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) += rust_driver_faux.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/rust_configfs.rs new file +192 -0
192 lines not on this page · raw message
Signature · 1 line
2.47.2
Re: [PATCH v6 2/3] rust: configfs: add a sample demonstrating configfs usage
Quoted 180 lines · Andreas Hindborg
Add a sample to the samples folder, demonstrating the intended use of the Rust configfs API.
Signed-off-by Andreas Hindborg <[email protected]>--- samples/rust/Kconfig | 11 +++ samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 204 insertions(+)samples/rust/Kconfig +11
-0@@ -10,6 +10,17 @@ menuconfig SAMPLES_RUST if SAMPLES_RUST +config SAMPLE_RUST_CONFIGFS + tristate "Configfs sample" + depends on CONFIGFS_FS + help + This option builds the Rust configfs sample. + + To compile this as a module, choose M here: + the module will be called rust_configfs. + + If unsure, say N. + config SAMPLE_RUST_MINIMAL tristate "Minimal" helpsamples/rust/Makefile +1
-0@@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) += rust_driver_faux.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.osamples/rust/rust_configfs.rs new file +130
-0@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust configfs sample. + +use kernel::alloc::flags; +use kernel::c_str; +use kernel::configfs; +use kernel::configfs_attrs; +use kernel::new_mutex; +use kernel::page::PAGE_SIZE ; +use kernel::prelude::*; +use kernel::sync::Mutex ; + +module! { +type :RustConfigfs , + name:"rust_configfs" , + author:"Rust for Linux Contributors" , + description:"Rust configfs sample" , + license:"GPL" , +} + +#[pin_data] +struct RustConfigfs { +#[pin] + config: configfs::Subsystem <Configuration >, +} + +#[pin_data] +struct Configuration { + message: &'staticCStr , +#[pin] + bar:Mutex <(KBox <[u8 ;PAGE_SIZE ]>,usize )>, +} + +impl Configuration { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + message:c_str! ("Hello World\n" ), + bar <-new_mutex! ((KBox ::new ([0 ;PAGE_SIZE ], flags::GFP_KERNEL )?,0 )), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { +fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +pr_info! ("Rust configfs sample (init)\n" ); + +// Define a subsystem with the data type `Configuration`, two +// attributes, `message` and `bar` and child group type `Child`. `mkdir` +// in the directory representing this subsystem will create directories +// backed by the `Child` type. +let item_type =configfs_attrs! { + container: configfs::Subsystem <Configuration >, + data:Configuration , + child:Child , + attributes: [ + message:0 , + bar:1 , + ], + }; + +try_pin_init! (Self { + config <- configfs::Subsystem ::new ( +c_str! ("rust_configfs" ), item_type,Configuration ::new () + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { +type Child =Child ; + +fn make_group (&self, name: &CStr ) ->Result <impl PinInit <configfs::Group <Child >,Error >> { +// Define a group with data type `Child`, one attribute `baz` and child +// group type `GrandChild`. `mkdir` in the directory representing this +// group will create directories backed by the `GrandChild` type. +let tpe =configfs_attrs! { + container: configfs::Group <Child >, + data:Child , + child:GrandChild , + attributes: [ + baz:0 , + ], + }; + +Ok (configfs::Group ::new (name.try_into ()?, tpe,Child ::new ())) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize > { +pr_info! ("Show message\n" ); +let data = container.message; + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +} + +#[vtable] +impl configfs::AttributeOperations <1 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize > { +pr_info! ("Show bar\n" ); +let guard = container.bar.lock (); +let data = guard.0 .as_slice (); +let len = guard.1 ; + page[0 ..len].copy_from_slice (&data[0 ..len]); +Ok (len) + } + +fn store (container: &Configuration , page: &[u8 ]) ->Result { +pr_info! ("Store bar\n" ); +let mut guard = container.bar.lock (); + guard.0 [0 ..page.len ()].copy_from_slice (page); + guard.1 = page.len (); +Ok (()) + } +} + +// `pin_data` cannot handle structs without braces. +#[pin_data] +struct Child {} + +impl Child { +fn new () ->impl PinInit <Self ,Error > {
samples/rust/rust_configfs.rs line 140
Quoted 10 lines
samples/rust/rust_configfs.rs new file +10
-0+try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::GroupOperations for Child { +type Child =GrandChild ; + +fn make_group (&self, name: &CStr ) ->Result <impl PinInit <configfs::Group <GrandChild >,Error >> { +// Define a group with data type `GrandChild`, one attribute `gz`. As no
Hi Andreas,
Maybe you meant "one attribute gc" here?
C. Mitrodimas
Quoted 52 lines
samples/rust/rust_configfs.rs new file +52
-0+// child type is specified, it will not be possible to create subgroups +// in this group, and `mkdir`in the directory representing this group +// will return an error. +let tpe =configfs_attrs! { + container: configfs::Group <GrandChild >, + data:GrandChild , + attributes: [ + gc:0 , + ], + }; + +Ok (configfs::Group ::new ( + name.try_into ()?, + tpe, +GrandChild ::new (), + )) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Child { +type Data =Child ; + +fn show (_container: &Child , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize > { +pr_info! ("Show baz\n" ); +let data =c"Hello Baz\n" .to_bytes (); + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +} + +// `pin_data` cannot handle structs without braces. +#[pin_data] +struct GrandChild {} + +impl GrandChild { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for GrandChild { +type Data =GrandChild ; + +fn show (_container: &GrandChild , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize > { +pr_info! ("Show grand child\n" ); +let data =c"Hello GC\n" .to_bytes (); + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +}
Andreas Hindborg
maintainerRe: [PATCH v6 2/3] rust: configfs: add a sample demonstrating configfs usage
Quoted 195 lines · Charalampos Mitrodimas
Quoted 180 lines · Andreas Hindborg
Add a sample to the samples folder, demonstrating the intended use of the Rust configfs API.
Signed-off-by Andreas Hindborg <[email protected]>--- samples/rust/Kconfig | 11 +++ samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 204 insertions(+)samples/rust/Kconfig +11
-0@@ -10,6 +10,17 @@ menuconfig SAMPLES_RUST if SAMPLES_RUST +config SAMPLE_RUST_CONFIGFS + tristate "Configfs sample" + depends on CONFIGFS_FS + help + This option builds the Rust configfs sample. + + To compile this as a module, choose M here: + the module will be called rust_configfs. + + If unsure, say N. + config SAMPLE_RUST_MINIMAL tristate "Minimal" helpsamples/rust/Makefile +1
-0@@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) += rust_driver_faux.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.osamples/rust/rust_configfs.rs new file +130
-0@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust configfs sample. + +use kernel::alloc::flags; +use kernel::c_str; +use kernel::configfs; +use kernel::configfs_attrs; +use kernel::new_mutex; +use kernel::page::PAGE_SIZE ; +use kernel::prelude::*; +use kernel::sync::Mutex ; + +module! { +type :RustConfigfs , + name:"rust_configfs" , + author:"Rust for Linux Contributors" , + description:"Rust configfs sample" , + license:"GPL" , +} + +#[pin_data] +struct RustConfigfs { +#[pin] + config: configfs::Subsystem <Configuration >, +} + +#[pin_data] +struct Configuration { + message: &'staticCStr , +#[pin] + bar:Mutex <(KBox <[u8 ;PAGE_SIZE ]>,usize )>, +} + +impl Configuration { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + message:c_str! ("Hello World\n" ), + bar <-new_mutex! ((KBox ::new ([0 ;PAGE_SIZE ], flags::GFP_KERNEL )?,0 )), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { +fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +pr_info! ("Rust configfs sample (init)\n" ); + +// Define a subsystem with the data type `Configuration`, two +// attributes, `message` and `bar` and child group type `Child`. `mkdir` +// in the directory representing this subsystem will create directories +// backed by the `Child` type. +let item_type =configfs_attrs! { + container: configfs::Subsystem <Configuration >, + data:Configuration , + child:Child , + attributes: [ + message:0 , + bar:1 , + ], + }; + +try_pin_init! (Self { + config <- configfs::Subsystem ::new ( +c_str! ("rust_configfs" ), item_type,Configuration ::new () + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { +type Child =Child ; + +fn make_group (&self, name: &CStr ) ->Result <impl PinInit <configfs::Group <Child >,Error >> { +// Define a group with data type `Child`, one attribute `baz` and child +// group type `GrandChild`. `mkdir` in the directory representing this +// group will create directories backed by the `GrandChild` type. +let tpe =configfs_attrs! { + container: configfs::Group <Child >, + data:Child , + child:GrandChild , + attributes: [ + baz:0 , + ], + }; + +Ok (configfs::Group ::new (name.try_into ()?, tpe,Child ::new ())) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize > { +pr_info! ("Show message\n" ); +let data = container.message; + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +} + +#[vtable] +impl configfs::AttributeOperations <1 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize > { +pr_info! ("Show bar\n" ); +let guard = container.bar.lock (); +let data = guard.0 .as_slice (); +let len = guard.1 ; + page[0 ..len].copy_from_slice (&data[0 ..len]); +Ok (len) + } + +fn store (container: &Configuration , page: &[u8 ]) ->Result { +pr_info! ("Store bar\n" ); +let mut guard = container.bar.lock (); + guard.0 [0 ..page.len ()].copy_from_slice (page); + guard.1 = page.len (); +Ok (()) + } +} + +// `pin_data` cannot handle structs without braces. +#[pin_data] +struct Child {} + +impl Child { +fn new () ->impl PinInit <Self ,Error > {samples/rust/rust_configfs.rs line 140
Quoted 10 lines
samples/rust/rust_configfs.rs new file +10
-0+try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::GroupOperations for Child { +type Child =GrandChild ; + +fn make_group (&self, name: &CStr ) ->Result <impl PinInit <configfs::Group <GrandChild >,Error >> { +// Define a group with data type `GrandChild`, one attribute `gz`. As no Hi Andreas,
Quoted 1 line
Maybe you meant "one attribute
gc" here?
Yes, thanks!
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH v6 3/3 MAINTAINERS: add configfs Rust abstractions
In reply to Andreas HindborgAdd rust files to configfs MAINTAINERS entry.
--- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+)
MAINTAINERS +2 -0
@@ -5982,7 +5982,9 @@ S: Supported T: git git://git.kernel.org/pub/scm/linux/kernel/git/a.hindborg/linux.git configfs-next F: fs/configfs/ F: include/linux/configfs.h +F: rust/kernel/configfs.rs F: samples/configfs/ +F: samples/rust/rust_configfs.rs CONGATEC BOARD CONTROLLER MFD DRIVER M: Thomas Richard <[email protected]>
Signature · 1 line
2.47.2