rust: build_assert: document and fix use with function arguments
Subsystems (6)
Alexandre Courbot
maintainerv2 cover rust: build_assert: document and fix use with function arguments
build_assert relies on the compiler to optimize out its error path, lest build fails with the dreaded error:
ERROR: modpost: "rust_build_error" [path/to/module.ko] undefined!
It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever CLIPPY=1 was set. The same behavior was also observed until different, very similar conditions [1][2].
The cause, as pointed out by Gary Guo [3], appears to be that the failing function is eventually using build_assert with its argument, but is only annotated with #[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.
The fix is to annotate functions passing their argument to build_assert with #[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.
This series fixes all possible points of failure in the kernel crate, and adds documentation to build_assert explaining how to properly inline functions for which this behavior may arise.
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
---
Changes in v2:
- Turn into a series and address other similar cases in the kernel crate.
- Link to v1: https://patch.msgid.link/[email protected]
---
Alexandre Courbot (7):
rust: build_assert: add instructions for use with function arguments
rust: io: always inline functions using build_assert with arguments
rust: cpufreq: always inline functions using build_assert with arguments
rust: bits: always inline functions using build_assert with arguments
rust: sync: refcount: always inline functions using build_assert with arguments
rust: irq: always inline functions using build_assert with arguments
rust: num: bounded: add missing comment for always inlined function
rust/kernel/bits.rs | 6 ++++-- rust/kernel/build_assert.rs | 7 ++++++- rust/kernel/cpufreq.rs | 2 ++ rust/kernel/io.rs | 9 ++++++--- rust/kernel/io/resource.rs | 2 ++ rust/kernel/irq/flags.rs | 2 ++ rust/kernel/num/bounded.rs | 1 + rust/kernel/sync/refcount.rs | 3 ++- 8 files changed, 25 insertions(+), 7 deletions(-)
---
base-commit: 54e3eae855629702c566bd2e130d9f40e7f35bde
change-id: 20251127-io-build-assert-3579a5bfb81c
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH v2 1/7 rust: build_assert: add instructions for use with function arguments
build_assert relies on the compiler to optimize out its error path, lest build fails with the dreaded error:
ERROR: modpost: "rust_build_error" [path/to/module.ko] undefined!
It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever CLIPPY=1 was set. The same behavior was also observed until different, very similar conditions [1][2].
The cause appears to be that the failing function is eventually using build_assert with its argument, but is only annotated with #[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.
The fix is to annotate functions passing their argument to build_assert with #[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.
Add a paragraph instructing to annotate such functions with #[inline(always)] in build_assert's documentation, and split its example to illustrate.
--- rust/kernel/build_assert.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
rust/kernel/build_assert.rs +6 -1
@@ -61,8 +61,13 @@ macro_rules! build_error {/// build_assert!(N > 1); // Build-time check /// assert!(N > 1); // Run-time check /// } +/// ``` /// -/// #[inline] +/// When a condition depends on a function argument, the function must be annotated with +/// `#[inline(always)]`. Without this attribute, the compiler may choose to not inline the +/// function, preventing it from optimizing out the error path. +/// ``` +/// #[inline(always)] /// fn bar(n: usize) { /// // `static_assert!(n > 1);` is not allowed /// build_assert!(n > 1); // Build-time check
Signature · 1 line
2.52.0
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 15 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path, lest build fails with the dreaded error:ERROR: modpost: "
rust_build_error" [path/to/module.ko] undefined!It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever
CLIPPY=1was set. The same behavior was also observed until different, very similar conditions [1][2].The cause appears to be that the failing function is eventually using
build_assertwith its argument, but is only annotated with#[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.
Quoted 4 lines
The fix is to annotate functions passing their argument to
build_assertwith#[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.
Very interesting. So by adding a partially faulty build_assert!() call, these functions were actually wrong when they created! Maybe a Fixes:
tag is warranted.
thanks,
Signature · 1 line
John Hubbard
Quoted 30 lines
Add a paragraph instructing to annotate such functions with
#[inline(always)]inbuild_assert's documentation, and split its example to illustrate.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/build_assert.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)rust/kernel/build_assert.rs +6
-1@@ -61,8 +61,13 @@ macro_rules! build_error {/// build_assert!(N > 1); // Build-time check /// assert!(N > 1); // Run-time check /// } +/// ``` /// -/// #[inline] +/// When a condition depends on a function argument, the function must be annotated with +/// `#[inline(always)]`. Without this attribute, the compiler may choose to not inline the +/// function, preventing it from optimizing out the error path. +/// ``` +/// #[inline(always)] /// fn bar(n: usize) { /// // `static_assert!(n > 1);` is not allowed /// build_assert!(n > 1); // Build-time check
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 4 lines · John Hubbard
Very interesting. So by adding a partially faulty build_assert!() call, these functions were actually wrong when they created! Maybe a Fixes:
tag is warranted.
To clarify: it is the lack of optimization in certain configs (-Os, CLIPPY=1...) as well as possibly certain code patterns that may trigger it, not that the calls were faulty (note that always doesn't guarantee it either anyway).
Daniel suggested Fixes in #0 -- if any of these trigger a build error (like the Bounded one), then yeah. Cc: stable@ too.
Thanks!
Cheers,
Miguel
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 9 lines · Miguel Ojeda
Quoted 4 lines · John Hubbard
Very interesting. So by adding a partially faulty build_assert!() call, these functions were actually wrong when they created! Maybe a Fixes:
tag is warranted.To clarify: it is the lack of optimization in certain configs (-Os, CLIPPY=1...) as well as possibly certain code patterns that may trigger it, not that the calls were faulty (note that
alwaysdoesn't
It seems pretty clear that if one writes a *build* assertion about a function argument, then that is just conceptually wrong unless it is inlined. Because it can only really be a run-time assertion.
This is what Alex pointed out, and looking at the code I agree.
Thoughts?
Quoted 1 line
guarantee it either anyway).
Yes, understood. So maybe "Fixes" is too strong. It's more like "Mitigates:". :)
thanks,
Signature · 1 line
John Hubbard
Quoted 8 lines
Daniel suggested Fixes in #0 -- if any of these trigger a build error (like the
Boundedone), then yeah. Cc: stable@ too.Thanks!
Cheers,
Miguel
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 6 lines · John Hubbard
It seems pretty clear that if one writes a *build* assertion about a function argument, then that is just conceptually wrong unless it is inlined. Because it can only really be a run-time assertion.
This is what Alex pointed out, and looking at the code I agree.
No, the function here was already inline.
What Alexandre wrote, which is correct, is that the fix is about asking for *more* inlining.
The build assertion itself is fine. What is "wrong" is that the inlining wasn't enough.
Nevertheless, it is (or at least some of these are) definitely a "fix" in the sense that it did fix cases we hit where the inlining wasn't enough, like Clippy ones which may change codegen (which in turn is why we say it cannot be used in "production" kernel builds:
https://github.com/rust-lang/rust-clippy/pull/8037 -- back then it disabled MIR optimizations).
Cheers,
Miguel
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 9 lines · Miguel Ojeda
Quoted 6 lines · John Hubbard
It seems pretty clear that if one writes a *build* assertion about a function argument, then that is just conceptually wrong unless it is inlined. Because it can only really be a run-time assertion.
This is what Alex pointed out, and looking at the code I agree.
No, the function here was already inline.
More precisely, it was already *hinted* to be inline.
Quoted 6 lines
What Alexandre wrote, which is correct, is that the fix is about asking for *more* inlining.
The build assertion itself is fine. What is "wrong" is that the inlining wasn't enough.
I'm having a difficult time with that statement, because if you write:
fn bar(n: usize) {
build_assert!(n > 1);
...
}Then that is conceptually wrong, because it must be a runtime check.
The only way it can be a compile-time check is if you have some way to *guarantee* that the function is inlined into code that has a const n.
Absent such guarantees (and we have "nearly none", right?), we have been writing "partly wrong" code in all such cases.
Why? Are the guarantees stronger than they look? Or other reasoning?
Quoted 8 lines
Nevertheless, it is (or at least some of these are) definitely a "fix" in the sense that it did fix cases we hit where the inlining wasn't enough, like Clippy ones which may change codegen (which in turn is why we say it cannot be used in "production" kernel builds:
https://github.com/rust-lang/rust-clippy/pull/8037 -- back then it disabled MIR optimizations).
Sorry for the fussy detailed questioning here. I'm trying to bottom out here because CLIPPY=1 is a very solid requirement before posting patches.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 2 lines · John Hubbard
More precisely, it was already *hinted* to be inline.
By inline I mean it is marked #[inline], which may or may not get inlined, but it also has other implications, e.g. codegen can get delayed even if there are no callers and is concrete.
Quoted 1 line
Then that is conceptually wrong, because it must be a runtime check.
No, it is not true it must be a runtime check -- it depends: you can use such a function in some cases just fine.
That is the point of build_assert!, after all.
Quoted 3 lines
Sorry for the fussy detailed questioning here. I'm trying to bottom out here because CLIPPY=1 is a very solid requirement before posting patches.
No worries, but I don't follow what you mean here. CLIPPY=1 is still required to be clean etc.
Cheers,
Miguel
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 8 lines · Miguel Ojeda
Quoted 2 lines · John Hubbard
More precisely, it was already *hinted* to be inline.
By inline I mean it is marked
#[inline], which may or may not get inlined, but it also has other implications, e.g. codegen can get delayed even if there are no callers and is concrete.
Quoted 6 lines
Quoted 1 line
Then that is conceptually wrong, because it must be a runtime check.
No, it is not true it must be a runtime check -- it depends: you can use such a function in some cases just fine.
That is the point of
build_assert!, after all.
This seems strange: something called build_assert!() should not be put in places where it might not be possible to verify at build-time. It's built right into the name.
Quoted 8 lines
Quoted 4 lines
Sorry for the fussy detailed questioning here. I'm trying to bottom out here because CLIPPY=1 is a very solid requirement before posting patches.
No worries, but I don't follow what you mean here.
CLIPPY=1is still required to be clean etc.
CLIPPY=1 is effectively part of the developers' tool chain. It is also one of the ways to break the build_assert!() call sites.
So now we have to go around and annotate the functions that *contain* uses of build_assert!(). Otherwise we end up with an unreliable tool chain for developers. This is not where we should want to be, in the long run.
Is there proc macro magic we can come up with? Or rustc or clippy changes? So that this is becomes a better foundation upon which to build?
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 4 lines · John Hubbard
This seems strange: something called build_assert!() should not be put in places where it might not be possible to verify at build-time. It's built right into the name.
The build prefix means the assert is done at build time, not that it can always be verified. Even other asserts could also "fail" in a certain sense (diverging, conditional compilation...).
Detecting "unreasonable" uses that are likely to fail would be nice, of course.
Quoted 2 lines
So now we have to go around and annotate the functions that *contain* uses of build_assert!().
Only for those that need it.
Quoted 3 lines
Otherwise we end up with an unreliable tool
chain for developers. This is not where we should want to be, in the long run.
It is not a black or white issue. Conditional compilation also breaks if someone misuses it, and that alone doesn't mean we stop using it. It is a tradeoff at the end of the day.
Nevertheless, also note that the C side also relies on optimizations.
Quoted 3 lines
Is there proc macro magic we can come up with? Or rustc or clippy changes? So that this is becomes a better foundation upon which to build?
Converting more code to macros has their own set of tradeoffs, but it depends on what you mean. Do you have something in mind?
And yes, I have had it in our usual lists for a long time and we mentioned it to upstream Rust and so on. We are well aware that build_assert! isn't ideal, and in many cases it is best to avoid it when there is a better approach.
Now, if a company has the means to improve the situation, e.g. by sponsoring someone upstream to work on features like this, then by all means, please go ahead! That would be very welcome, and we have some contacts that could be interested in working on things like that, so please feel free to ping.
Cheers,
Miguel
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 1 line · Miguel Ojeda
On Mon, Dec 1, 2025 at 5:36 AM John Hubbard <[email protected]> wrote:
...
Quoted 6 lines
Quoted 3 lines
Is there proc macro magic we can come up with? Or rustc or clippy changes? So that this is becomes a better foundation upon which to build?
Converting more code to macros has their own set of tradeoffs, but it depends on what you mean. Do you have something in mind?
Mainly just: is there a way to automatically "derive" (generate) an always-inline directive for any function that attempts to call build_assert!() on any of its arguments? And in fact, *force* the always-inline, if it is not forced hard enough today.
Something along those lines.
Quoted 6 lines
And yes, I have had it in our usual lists for a long time and we mentioned it to upstream Rust and so on. We are well aware that
build_assert!isn't ideal, and in many cases it is best to avoid it when there is a better approach.
Quoted 6 lines
Now, if a company has the means to improve the situation, e.g. by sponsoring someone upstream to work on features like this, then by all means, please go ahead! That would be very welcome, and we have some contacts that could be interested in working on things like that, so please feel free to ping.
I will bring this up (along with the KSYM_NAME_LEN hashed symbol project) to our internal Rust groups. Both of these seem like nice, self-contained projects that someone could really get into.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 7 lines · John Hubbard
Mainly just: is there a way to automatically "derive" (generate) an always-inline directive for any function that attempts to call build_assert!() on any of its arguments? And in fact, *force* the always-inline, if it is not forced hard enough today.
Something along those lines.
"Wide-scoped" macros can do passes like that, i.e. like some projects do to add extra syntax everywhere. Not sure we want to get into that world, though.
Instead, if we are just talking about checking, then I think we could have an attribute macro to mark such functions, and then build_assert! could fail "by default" unless inside one of those, and it would get rewritten into the proper form by the macro, so any call without it would fail. It is always nice to mark special functions anyway, just like our export one.
Otherwise, for more than just checking, I guess a custom tool like Klint could also do it for us (I am sure Gary has ideas here).
Quoted 3 lines
I will bring this up (along with the
KSYM_NAME_LENhashed symbol project) to our internal Rust groups. Both of these seem like nice, self-contained projects that someone could really get into.
That is great -- thanks!
On related news, Antoni (Cc'd) told me yesterday that he noticed inline(always) was needed when using the GCC backend too, so this series will help him too.
Cheers,
Miguel
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 20 lines · Miguel Ojeda
Quoted 7 lines · John Hubbard
Mainly just: is there a way to automatically "derive" (generate) an always-inline directive for any function that attempts to call build_assert!() on any of its arguments? And in fact, *force* the always-inline, if it is not forced hard enough today.
Something along those lines.
"Wide-scoped" macros can do passes like that, i.e. like some projects do to add extra syntax everywhere. Not sure we want to get into that world, though.
Instead, if we are just talking about checking, then I think we could have an attribute macro to mark such functions, and then
build_assert!could fail "by default" unless inside one of those, and it would get rewritten into the proper form by the macro, so any call without it would fail. It is always nice to mark special functions anyway, just like ourexportone.
Quoted 8 lines
Otherwise, for more than just checking, I guess a custom tool like Klint could also do it for us (I am sure Gary has ideas here).
Quoted 3 lines
I will bring this up (along with the
KSYM_NAME_LENhashed symbol project) to our internal Rust groups. Both of these seem like nice, self-contained projects that someone could really get into.That is great -- thanks!
For the build_assert!() project, I didn't even get that far, because it turns out that Joel Fernandes (+Cc) is already working hard on this.
Quoted 7 lines
On related news, Antoni (Cc'd) told me yesterday that he noticed
inline(always)was needed when using the GCC backend too, so this series will help him too.Cheers,
Miguel
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
In reply to Alexandre CourbotQuoted 35 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path, lest build fails with the dreaded error:ERROR: modpost: "
rust_build_error" [path/to/module.ko] undefined!It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever
CLIPPY=1was set. The same behavior was also observed until different, very similar conditions [1][2].The cause appears to be that the failing function is eventually using
build_assertwith its argument, but is only annotated with#[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.The fix is to annotate functions passing their argument to
build_assertwith#[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.Add a paragraph instructing to annotate such functions with
#[inline(always)]inbuild_assert's documentation, and split its example to illustrate.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/build_assert.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)rust/kernel/build_assert.rs +0
-0@@ -61,8 +61,13 @@ macro_rules! build_error {/// build_assert!(N > 1); // Build-time check
rust/kernel/build_assert.rs macro_rules! build_error { · line 70
Quoted 10 lines
rust/kernel/build_assert.rs +6
-1/// assert!(N > 1); // Run-time check /// } +/// ``` /// -/// #[inline] +/// When a condition depends on a function argument, the function must be annotated with +/// `#[inline(always)]`. Without this attribute, the compiler may choose to not inline the +/// function, preventing it from optimizing out the error path. +/// ``` +/// #[inline(always)]
The compiler may still choose to not inline the function, even under #[inline(always)]:
"#[inline(always)] suggests that inline expansion should always be performed." [1]
"Note: In every form the attribute is a hint. The compiler may ignore it." [also 1]
1: https://doc.rust-lang.org/reference/attributes/codegen.html
Regards,
Edwin Peer
Alexandre Courbot
maintainerRe: [PATCH v2 1/7] rust: build_assert: add instructions for use with function arguments
Quoted 51 lines · Edwin Peer
Quoted 35 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path, lest build fails with the dreaded error:ERROR: modpost: "
rust_build_error" [path/to/module.ko] undefined!It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever
CLIPPY=1was set. The same behavior was also observed until different, very similar conditions [1][2].The cause appears to be that the failing function is eventually using
build_assertwith its argument, but is only annotated with#[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.The fix is to annotate functions passing their argument to
build_assertwith#[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.Add a paragraph instructing to annotate such functions with
#[inline(always)]inbuild_assert's documentation, and split its example to illustrate.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/build_assert.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)rust/kernel/build_assert.rs +0
-0@@ -61,8 +61,13 @@ macro_rules! build_error {/// build_assert!(N > 1); // Build-time check rust/kernel/build_assert.rs macro_rules! build_error { · line 70
Quoted 10 lines
rust/kernel/build_assert.rs +6
-1/// assert!(N > 1); // Run-time check /// } +/// ``` /// -/// #[inline] +/// When a condition depends on a function argument, the function must be annotated with +/// `#[inline(always)]`. Without this attribute, the compiler may choose to not inline the +/// function, preventing it from optimizing out the error path. +/// ``` +/// #[inline(always)] The compiler may still choose to not inline the function, even under
#[inline(always)]:
Quoted 5 lines
"#[inline(always)] suggests that inline expansion should always be performed." [1]
"Note: In every form the attribute is a hint. The compiler may ignore it." [also 1]
This is true, but AFAICT this is the best we can do as of today (and in practice it thankfully never failed so far). If there is a more reliable way to always inline functions we should definitely use that though.
Alexandre Courbot
maintainerPATCH v2 2/7 rust: io: always inline functions using build_assert with arguments
In reply to Alexandre Courbotbuild_assert relies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path of build_assert might not be optimized out, triggering a build error.
--- rust/kernel/io.rs | 9 ++++++--- rust/kernel/io/resource.rs | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-)
rust/kernel/io.rs +6 -3
@@ -120,7 +120,8 @@ macro_rules! define_read {/// Bound checks are performed on compile time, hence if the offset is not known at compile /// time, the build will fail. $(#[$attr])* - #[inline] + // Always inline to optimize out error path of `io_addr_assert`. + #[inline(always)] pub fn $name(&self, offset: usize) -> $type_name { let addr = self.io_addr_assert::<$type_name>(offset);
@@ -149,7 +150,8 @@ macro_rules! define_write {/// Bound checks are performed on compile time, hence if the offset is not known at compile /// time, the build will fail. $(#[$attr])* - #[inline] + // Always inline to optimize out error path of `io_addr_assert`. + #[inline(always)] pub fn $name(&self, value: $type_name, offset: usize) { let addr = self.io_addr_assert::<$type_name>(offset);
@@ -217,7 +219,8 @@ fn io_addr<U>(&self, offset: usize) -> Result<usize> { self.addr ().checked_add (offset).ok_or (EINVAL ) } -#[inline] +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] fn io_addr_assert <U >(&self, offset:usize ) ->usize {build_assert! (Self ::offset_valid ::<U >(offset,SIZE ));
rust/kernel/io/resource.rs +2 -0
@@ -223,6 +223,8 @@ impl Flags {/// Resource represents a memory region that must be ioremaped using `ioremap_np`. pub const IORESOURCE_MEM_NONPOSTED :Flags =Flags ::new (bindings::IORESOURCE_MEM_NONPOSTED ); +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn new (value:u32 ) ->Self {crate ::build_assert!(valueas u64 <= c_ulong::MAX as u64 );Flags (valueas c_ulong )
Signature · 1 line
2.52.0
Re: [PATCH v2 2/7] rust: io: always inline functions using build_assert with arguments
Quoted 50 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path ofbuild_assertmight not be optimized out, triggering a build error.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 9 ++++++--- rust/kernel/io/resource.rs | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-)rust/kernel/io.rs +6
-3@@ -120,7 +120,8 @@ macro_rules! define_read {/// Bound checks are performed on compile time, hence if the offset is not known at compile /// time, the build will fail. $(#[$attr])* - #[inline] + // Always inline to optimize out error path of `io_addr_assert`. + #[inline(always)] pub fn $name(&self, offset: usize) -> $type_name { let addr = self.io_addr_assert::<$type_name>(offset);@@ -149,7 +150,8 @@ macro_rules! define_write {/// Bound checks are performed on compile time, hence if the offset is not known at compile /// time, the build will fail. $(#[$attr])* - #[inline] + // Always inline to optimize out error path of `io_addr_assert`. + #[inline(always)] pub fn $name(&self, value: $type_name, offset: usize) { let addr = self.io_addr_assert::<$type_name>(offset);@@ -217,7 +219,8 @@ fn io_addr<U>(&self, offset: usize) -> Result<usize> { self.addr ().checked_add (offset).ok_or (EINVAL ) } -#[inline] +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] fn io_addr_assert <U >(&self, offset:usize ) ->usize {build_assert! (Self ::offset_valid ::<U >(offset,SIZE ));rust/kernel/io/resource.rs +0
-0
rust/kernel/io/resource.rs impl Flags { · line 228
Quoted 6 lines
rust/kernel/io/resource.rs +2
-0@@ -223,6 +223,8 @@ impl Flags {/// Resource represents a memory region that must be ioremaped using `ioremap_np`. pub const IORESOURCE_MEM_NONPOSTED :Flags =Flags ::new (bindings::IORESOURCE_MEM_NONPOSTED ); +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn new (value:u32 ) ->Self {
Does the build_assert problem actually manifest for const functions?
Regards,
Edwin Peer
Quoted 3 lines
rust/kernel/io/resource.rs +0
-0crate ::build_assert!(valueas u64 <= c_ulong::MAX as u64 );Flags (valueas c_ulong )
Alice Ryhl
maintainerRe: [PATCH v2 2/7] rust: io: always inline functions using build_assert with arguments
Quoted 11 lines · Edwin Peer
Quoted 8 lines · Alexandre Courbot
rust/kernel/io/resource.rs +0
-0@@ -223,6 +223,8 @@ impl Flags {/// Resource represents a memory region that must be ioremaped using `ioremap_np`. pub const IORESOURCE_MEM_NONPOSTED :Flags =Flags ::new (bindings::IORESOURCE_MEM_NONPOSTED );
Quoted 5 lines
rust/kernel/io/resource.rs impl Flags { · line 228
Quoted 3 lines
rust/kernel/io/resource.rs +2
-0+// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn new (value:u32 ) ->Self {Does the
build_assertproblem actually manifest for const functions?
Yes, the const marker only allows you to call it from const context. It does not change behavior when it is called from non-const context.
Alice
Alexandre Courbot
maintainerPATCH v2 3/7 rust: cpufreq: always inline functions using build_assert with arguments
In reply to Alexandre Courbotbuild_assert relies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path of build_assert might not be optimized out, triggering a build error.
--- rust/kernel/cpufreq.rs | 2 ++ 1 file changed, 2 insertions(+)
rust/kernel/cpufreq.rs +2 -0
@@ -1015,6 +1015,8 @@ impl<T: Driver> Registration<T> { ..pin_init::zeroed () }; +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn copy_name (name: &'staticCStr ) -> [c_char ;CPUFREQ_NAME_LEN ] {let src = name.to_bytes_with_nul ();let mut dst = [0 ;CPUFREQ_NAME_LEN ];
Signature · 1 line
2.52.0
Re: [PATCH v2 3/7] rust: cpufreq: always inline functions using build_assert with arguments
Quoted 15 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path ofbuild_assertmight not be optimized out, triggering a build error.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/cpufreq.rs | 2 ++ 1 file changed, 2 insertions(+)rust/kernel/cpufreq.rs +0
-0
rust/kernel/cpufreq.rs impl<T: Driver> Registration<T> { · line 1022
Quoted 8 lines
rust/kernel/cpufreq.rs +2
-0@@ -1015,6 +1015,8 @@ impl<T: Driver> Registration<T> { ..pin_init::zeroed () }; +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn copy_name (name: &'staticCStr ) -> [c_char ;CPUFREQ_NAME_LEN ] {let src = name.to_bytes_with_nul ();let mut dst = [0 ;CPUFREQ_NAME_LEN ];
Lemme know if you want me to pick this instead.
Signature · 1 line
viresh
Alice Ryhl
maintainerRe: [PATCH v2 3/7] rust: cpufreq: always inline functions using build_assert with arguments
Quoted 27 lines · Viresh Kumar
Quoted 15 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path ofbuild_assertmight not be optimized out, triggering a build error.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/cpufreq.rs | 2 ++ 1 file changed, 2 insertions(+)rust/kernel/cpufreq.rs +0
-0rust/kernel/cpufreq.rs impl<T: Driver> Registration<T> { · line 1022
Quoted 8 lines
rust/kernel/cpufreq.rs +2
-0@@ -1015,6 +1015,8 @@ impl<T: Driver> Registration<T> { ..pin_init::zeroed () }; +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn copy_name (name: &'staticCStr ) -> [c_char ;CPUFREQ_NAME_LEN ] {let src = name.to_bytes_with_nul ();let mut dst = [0 ;CPUFREQ_NAME_LEN ];Acked-by Viresh Kumar <[email protected]>
Quoted 1 line
Lemme know if you want me to pick this instead.
There's no reason these can't be picked up independently, so it would be fine if you pick up this one.
Alice
Re: [PATCH v2 3/7] rust: cpufreq: always inline functions using build_assert with arguments
Quoted 28 lines · Alice Ryhl
Quoted 27 lines · Viresh Kumar
Quoted 15 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path ofbuild_assertmight not be optimized out, triggering a build error.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/cpufreq.rs | 2 ++ 1 file changed, 2 insertions(+)rust/kernel/cpufreq.rs +0
-0rust/kernel/cpufreq.rs impl<T: Driver> Registration<T> { · line 1022
Quoted 8 lines
rust/kernel/cpufreq.rs +2
-0@@ -1015,6 +1015,8 @@ impl<T: Driver> Registration<T> { ..pin_init::zeroed () }; +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn copy_name (name: &'staticCStr ) -> [c_char ;CPUFREQ_NAME_LEN ] {let src = name.to_bytes_with_nul ();let mut dst = [0 ;CPUFREQ_NAME_LEN ];Acked-by Viresh Kumar <[email protected]>
Quoted 4 lines
Quoted 1 line
Lemme know if you want me to pick this instead.
There's no reason these can't be picked up independently, so it would be fine if you pick up this one.
Applied. Thanks.
Signature · 1 line
viresh
Alexandre Courbot
maintainerPATCH v2 4/7 rust: bits: always inline functions using build_assert with arguments
In reply to Alexandre Courbotbuild_assert relies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path of build_assert might not be optimized out, triggering a build error.
--- rust/kernel/bits.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
rust/kernel/bits.rs +4 -2
@@ -27,7 +27,8 @@ pub fn [<checked_bit_ $ty>](n: u32) -> Option<$ty> {/// /// This version is the default and should be used if `n` is known at /// compile time. -#[inline] +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] pub const fn [<bit_ $ty>](n: u32) -> $ty {build_assert! (n < <$ty>::BITS ); (1 as $ty) << n
@@ -75,7 +76,8 @@ pub fn [<genmask_checked_ $ty>](range: RangeInclusive<u32>) -> Option<$ty> {/// This version is the default and should be used if the range is known /// at compile time. $(#[$genmask_ex])* - #[inline] + // Always inline to optimize out error path of `build_assert`. + #[inline(always)] pub const fn [<genmask_ $ty>](range: RangeInclusive<u32>) -> $ty { let start = *range.start(); let end = *range.end();
Signature · 1 line
2.52.0
Alexandre Courbot
maintainerPATCH v2 5/7 rust: sync: refcount: always inline functions using build_assert with arguments
In reply to Alexandre Courbotbuild_assert relies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path of build_assert might not be optimized out, triggering a build error.
--- rust/kernel/sync/refcount.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
rust/kernel/sync/refcount.rs +2 -1
@@ -23,7 +23,8 @@ impl Refcount {/// Construct a new [`Refcount`] from an initial value. /// /// The initial value should be non-saturated. -#[inline] +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] pub fn new (value:i32 ) ->Self {build_assert! (value >=0 ,"initial value saturated" );// SAFETY: There are no safety requirements for this FFI call.
Signature · 1 line
2.52.0
Alexandre Courbot
maintainerPATCH v2 6/7 rust: irq: always inline functions using build_assert with arguments
In reply to Alexandre Courbotbuild_assert relies on the compiler to optimize out its error path. Functions using it with its arguments must thus always be inlined, otherwise the error path of build_assert might not be optimized out, triggering a build error.
--- rust/kernel/irq/flags.rs | 2 ++ 1 file changed, 2 insertions(+)
rust/kernel/irq/flags.rs +2 -0
@@ -96,6 +96,8 @@ pub(crate) fn into_inner(self) -> c_ulong { self.0 } +// Always inline to optimize out error path of `build_assert`. +#[inline(always)] const fn new (value:u32 ) ->Self {build_assert! (valueas u64 <= c_ulong::MAX as u64 );Self (valueas c_ulong )
Signature · 1 line
2.52.0
Alexandre Courbot
maintainerPATCH v2 7/7 rust: num: bounded: add missing comment for always inlined function
In reply to Alexandre CourbotThis code is always inlined to avoid a build error if the error path of build_assert cannot be optimized out. Add a comment justifying the #[inline(always)] property to avoid it being taken away by mistake.
--- rust/kernel/num/bounded.rs | 1 + 1 file changed, 1 insertion(+)
rust/kernel/num/bounded.rs +1 -0
@@ -363,6 +363,7 @@ pub fn try_new(value: T) -> Option<Self> {/// assert_eq!(Bounded::<u8, 1>::from_expr(1).get(), 1); /// assert_eq!(Bounded::<u16, 8>::from_expr(0xff).get(), 0xff); /// ``` +// Always inline to optimize out error path of `build_assert`. #[inline(always)] pub fn from_expr (expr:T ) ->Self {crate ::build_assert!(
Signature · 1 line
2.52.0
Quoted 58 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path, lest build fails with the dreaded error:ERROR: modpost: "
rust_build_error" [path/to/module.ko] undefined!It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever
CLIPPY=1was set. The same behavior was also observed until different, very similar conditions [1][2].The cause, as pointed out by Gary Guo [3], appears to be that the failing function is eventually using
build_assertwith its argument, but is only annotated with#[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.The fix is to annotate functions passing their argument to
build_assertwith#[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.This series fixes all possible points of failure in the kernel crate, and adds documentation to
build_assertexplaining how to properly inline functions for which this behavior may arise.[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/Signed-off-by Alexandre Courbot <[email protected]>---
Changes in v2:
- Turn into a series and address other similar cases in the kernel crate.
- Link to v1: https://patch.msgid.link/[email protected]---
Alexandre Courbot (7):
rust:build_assert: add instructions for use with function arguments
rust: io: always inline functions usingbuild_assertwith arguments
rust: cpufreq: always inline functions usingbuild_assertwith arguments
rust: bits: always inline functions usingbuild_assertwith arguments
rust: sync: refcount: always inline functions usingbuild_assertwith arguments
rust: irq: always inline functions usingbuild_assertwith arguments
rust: num: bounded: add missing comment for always inlined functionrust/kernel/bits.rs | 6 ++++-- rust/kernel/build_assert.rs | 7 ++++++- rust/kernel/cpufreq.rs | 2 ++ rust/kernel/io.rs | 9 ++++++--- rust/kernel/io/resource.rs | 2 ++ rust/kernel/irq/flags.rs | 2 ++ rust/kernel/num/bounded.rs | 1 + rust/kernel/sync/refcount.rs | 3 ++- 8 files changed, 25 insertions(+), 7 deletions(-)
Quoted 8 lines
---
base-commit:54e3eae855629702c566bd2e130d9f40e7f35bde
change-id: 20251127-io-build-assert-3579a5bfb81cBest regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Thanks for fixing this. I was _very_ confused when it happened to me.
Daniel Almeida
maintainerQuoted 58 lines · Alexandre Courbot
build_assertrelies on the compiler to optimize out its error path, lest build fails with the dreaded error:ERROR: modpost: "
rust_build_error" [path/to/module.ko] undefined!It has been observed that very trivial code performing I/O accesses (sometimes even using an immediate value) would seemingly randomly fail with this error whenever
CLIPPY=1was set. The same behavior was also observed until different, very similar conditions [1][2].The cause, as pointed out by Gary Guo [3], appears to be that the failing function is eventually using
build_assertwith its argument, but is only annotated with#[inline]. This gives the compiler freedom to not inline the function, which it notably did when Clippy was active, triggering the error.The fix is to annotate functions passing their argument to
build_assertwith#[inline(always)], telling the compiler to be as aggressive as possible with their inlining. This is also the correct behavior as inlining is mandatory for correct behavior in these cases.This series fixes all possible points of failure in the kernel crate, and adds documentation to
build_assertexplaining how to properly inline functions for which this behavior may arise.[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/Signed-off-by Alexandre Courbot <[email protected]>---
Changes in v2:
- Turn into a series and address other similar cases in the kernel crate.
- Link to v1: https://patch.msgid.link/[email protected]---
Alexandre Courbot (7):
rust:build_assert: add instructions for use with function arguments
rust: io: always inline functions usingbuild_assertwith arguments
rust: cpufreq: always inline functions usingbuild_assertwith arguments
rust: bits: always inline functions usingbuild_assertwith arguments
rust: sync: refcount: always inline functions usingbuild_assertwith arguments
rust: irq: always inline functions usingbuild_assertwith arguments
rust: num: bounded: add missing comment for always inlined functionrust/kernel/bits.rs | 6 ++++-- rust/kernel/build_assert.rs | 7 ++++++- rust/kernel/cpufreq.rs | 2 ++ rust/kernel/io.rs | 9 ++++++--- rust/kernel/io/resource.rs | 2 ++ rust/kernel/irq/flags.rs | 2 ++ rust/kernel/num/bounded.rs | 1 + rust/kernel/sync/refcount.rs | 3 ++- 8 files changed, 25 insertions(+), 7 deletions(-)
Quoted 9 lines
---
base-commit:54e3eae855629702c566bd2e130d9f40e7f35bde
change-id: 20251127-io-build-assert-3579a5bfb81cBest regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Ah, should this have a Fixes: tag?
— Daniel
Quoted 2 lines · Daniel Almeida
Ah, should this have a Fixes: tag?
Yes for those that trigger an error, e.g. the Bounded one with -Os in mainline soon. We probably want Cc: stable@ too -- it is not too risky to add these anyway.
However, the tag should be different for each commit depending on where each method was introduced. #1 and #7 are not really fixes, so they don't need it.
Cheers,
Miguel
Alexandre Courbot
maintainerQuoted 5 lines · Miguel Ojeda
Quoted 2 lines · Daniel Almeida
Ah, should this have a Fixes: tag?
Quoted 7 lines
Yes for those that trigger an error, e.g. the
Boundedone with -Os in mainline soon. We probably want Cc: stable@ too -- it is not too risky to add these anyway.However, the tag should be different for each commit depending on where each method was introduced. #1 and #7 are not really fixes, so they don't need it.
Shall I respin with some Fixes: tags where appropriate then?
Quoted 2 lines · Alexandre Courbot
Shall I respin with some
Fixes:tags where appropriate then?
If you can, then that would be great, yeah. Thanks!
Cheers,
Miguel