Guidelines for panics in kernel code
Alexandre Courbot spends most of his time working on the kernel doing code reviews. Recently, he's been wondering about what the standards should be for when Rust code is allowed to panic, and how it should do error handling more generally. Unlike many of the other talks at Kangrejos 2026, his talk was not presenting some existing work, but rather hoping to solicit opinions on the topic from the assembled Rust for Linux developers. He brought along a collection of tricky cases that he had run into recently to prompt discussion.
There is a "ladder of desirability
" in how to handle errors, Courbot
said. The best case is code that cannot fail, which people should try to
write whenever possible. Below that are failures that are checked for at compile
time, subdivided into those that are guaranteed to be caught, and those that
will be caught on a best-effort basis. Next are run-time checks using
Result and, as a last resort, panicking. He then gave small examples
of each of these, to ensure everyone was on the same page.
Generally, kernel developers and reviewers want code to be as high on that ladder as possible. For example, something that came up in doing code review of the Nova driver was how to represent the state of a virtual GPU (vGPU). The code originally used a structure that had a count of virtual functions (a virtual device with its own PCI memory space) and a flag for whether the vGPU was enabled. That led to a lot of run-time checks to ensure that the count was never zero when the vGPU was enabled. Rewriting that code as a Rust enumeration completely eliminated those run-time checks, since invalid states weren't possible to represent anymore—an example of the highest rung on the ladder.
struct VgpuState {
enabled: bool,
total_vfs: u16,
}
became:
enum VgpuState {
Disabled,
Enabled {
total_vfs: NonZero<u16>,
},
}
Compile-time checks are used throughout the kernel's Rust code, often in the form of build_assert!() (which checks that some code is optimized out of the final build) or static_assert!() (which checks that some condition always holds). Run-time checks using the Result type are also used frequently in Rust code.
The least desirable kind of error handling in Rust is panicking. It's used in two scenarios, he said: when something happening is definitely a bug, and when the programmer believes that a case will not happen. There is only one mention of panics in the kernel's Rust coding guidelines, and it just says that it is preferable to use Result, advice that developers do not always follow.
Each panic is a potential landmine, Courbot said. Linus Torvalds is strongly against bugs that make it possible to crash the kernel. Even the panics used for impossible cases, which the compiler can often optimize away, burden the reader of the code with needing to think about the panic when they change nearby code. Ard Biesheuvel said that panics are baked into the Rust language, and that it would not be possible to completely eliminate them. Courbot conceded the point that eliminating every single panic would be difficult, but still thought that reducing the number of panics in the code was desirable.
He then presented the first of his real-life examples, and asked what people thought the correct guideline should be. There is a udelay() function that takes an amount of time to sleep in microseconds, but it is considered a bug to call it with a timeout longer than an architecture-specific constant:
/// ... it is considered a bug to call this function with an out-of-range
/// value.
pub fn udelay(delta: Delta) {
debug_assert!(delta.as_nanos() >= 0);
debug_assert!(delta <= MAX_UDELAY_DELTA);
let delay = min(max(delta.as_nanos(), 0), MAX_UDELAY_DELTA);
...
}
In this case, the code clamped the provided delta to lie in the correct range and proceeded. But there are alternatives: the code could return a Result type, forcing the caller to check for EINVAL; the code could use a restrictive type to enforce that the provided delay is not too big; or the code could be changed to accept larger delays and just call the udelay() function on the C side multiple times.
Miguel Ojeda pointed out that what the code had been implemented to do (clamping the input and continuing anyway) was another general error-handling option that Courbot had not previously listed. In the Rust world, that kind of design is referred to as "erroneous behavior", he explained. It's an operation that is an error; it is still bad, but it has defined semantics instead of doing something unsafe. Another example of that in the kernel's Rust bindings is how the code handles errors outside the valid errno range: any error codes that are too big are turned into EINVAL when crossing the C-to-Rust boundary. It's still a bug, but it has a defined, safe behavior.
Courbot agreed that erroneous behavior was a good approach, at least in this case; it's what he had ended up recommending during code review. But there was another superficially similar case where erroneous behavior was not a good design choice. In this code, from the Rust binder driver, an argument is added to a "death list" to track some resources that need to be cleaned up when a driver exits. Just like before, calling the function with an invalid argument is an error:
pub(crate) fn add_death(&self, death: ...) {
assert!(
core::ptr::eq(self, &**death.node),
"attempt to add NodeDeath to the wrong death list"
)
}
Specifically, if the caller tries to add a NodeDeath structure to the wrong list, the resources in question would be cleaned up at the wrong time. So, there's no clear erroneous-but-safe behavior that can be introduced here, Courbot said. Benno Lossin questioned why the code couldn't just skip inserting the NodeDeath pointer into the list and return. Courbot supposed that would work, but it would leave the Rust binder in a weird state, which is not ideal. Gary Guo agreed, noting that the Android developers would probably prefer for the system to die if anything were to go wrong.
Courbot suggested that the function could return a Result, but that
would lead to somewhat pointless error handling. Or, the function could be
marked unsafe and proceed without the check, but that's not a clearly better
solution either.
Ojeda thought that this was a case where a panic was acceptable: "If you're
the maintainer, and you want to crash, that's fine
". Cases like this are
exactly what he had in mind when he wrote in the coding guidelines that it is
sometimes permissible to panic.
Courbot's next example was a panic that was conditionally compiled based on Kconfig settings. One of the maintainers of the kernel's Rust bitmap implementation added a bitmap_assert_return!() macro that is equivalent to assert!() if CONFIG_RUST_BITMAP_HARDENED is set, and otherwise just prints an error and returns when the condition does not hold. It is used to check that the provided index of a bit within the bitmap is less than the bitmap's allocated length.
Ojeda noted that he was not sure whether he should fight about this or not, when
he was reviewing the patch set. He could maybe see the argument for having a
global Kconfig setting for the whole kernel, but he wasn't sure he approved of
having separate Kconfig entries for every subsystem. Biesheuvel asked: "How
on Earth is the author of the bitmap library abstraction going to decide on the
policy of when it is right to panic or not?
"
Courbot agreed that it was a good question, and asked the kernel maintainers whether they thought that this code was wrong. Ojeda, Andreas Hindborg, and Greg Kroah-Hartman all agreed that it should be fixed. Kroah-Hartman noted that in this case, the Rust code was a faithful translation of the C code, which does the same thing. Guo thought the cases weren't analogous, because the C version of the structure had undefined behavior if used with an invalid index. Ultimately, the consensus seemed to be that conditionally panicking based on a per-subsystem Kconfig was wrong, but that this specific case was minimally acceptable because it was mimicking the existing C code.
Macros are not the only way to have conditional panic behavior. Courbot shared an example of a function that panics differently depending on how it is invoked:
impl Hertz {
const GHZ_TO_HZ: c_ulong = 1_000_000_000;
pub const fn from_ghz(ghz: c_ulong) -> Self {
Self(ghz * Self::GHZ_TO_HZ)
}
}
If from_ghz() is called at compile time (which is possible because it is a const function) with a value that causes arithmetic overflow, it results in a build error. When called at run time, it causes a panic. The function could be redefined to return a Result, or to have some other documented behavior when given an invalid argument, but Courbot didn't want to suppress the build error: getting a build error when something is incorrect is a good thing. There could be two versions of the function, one const and one non-const, Ojeda suggested, but he wasn't enthusiastic about the prospect.
Guo said that in his opinion, it should be fine for Rust code to panic when equivalent C code has undefined behavior. After all, if the component was being written in C, the compiler would be allowed to turn that undefined behavior into a panic. In this specific case, though, he thought that having erroneous behavior, such as safely wrapping or saturating the multiplication, would be fine. Courbot pointed out that this code could also be triggered by user space, and wondered if that changed anyone's minds, but it did not appear to do so.
Alice Ryhl called this example an easy case. The harder cases, in her opinion,
are cases like indexing into a dynamically sized type, something that Courbot
agreed with. Daniel Almieda asked whether
some future way to mark a function as being panic-free would help with this case.
Ojeda did not
think that it would, because this function can panic. He said that a
call to build_assert!() could potentially be used, though. Courbot responded:
"build_assert!() sounds like the right solution to many problems,
and then you start receiving zero-day notifications.
" He did not elaborate
on why, but it seems likely that he was referring to the fact that
build_assert!() relies on the optimizer, and so can have unpredictable
behavior.
Guo suggested using a macro that implements something like a pattern type, in advance of Rust adding support for pattern types. That led to an extended discussion about the usability of custom types in this situation. At the end of the discussion, people were less in agreement than before, with Rhyl noting that she did not believe that there is a single answer to the dilemma Courbot was proposing. Courbot accepted that, but still wanted some kind of guidance on how to make the decision.
There is also the problem that many panics are not obvious when reviewing code. He had looked at the Nova driver, and found that of 170 places where the code could panic, 140 were related to arithmetic overflow or underflow. All of those should be entirely avoidable, he said, with enough care and attention. Some of the arithmetic-related panics come from functions that have been inlined from the core crate, however, and he acknowledged that those would be a lot harder to fix.
One place in particular that bothered him was code that converted between null-terminated strings and Rust strings (which use an explicit length, instead). That code generated an overflow check for the calculated string length, even though a string occupying all of virtual memory would mean the system has larger problems. That's an example of a place where it is obvious to a human that the check is not needed, but since the generated overflow check is invisible, nobody had bothered to optimize it. Ryhl said she would accept a pull request from Courbot to fix that in the Rust standard library.
At that point, Courbot had run out of examples, so he attempted to summarize where that discussion stood. Everyone had agreed that dealing with errors at compile time was better than dealing with them at run time, and that reachable panics should be bugs. The kernel developers had agreed on little else.
Ojeda said that he thought the exact choice of when a panic is acceptable should be up to individual maintainers, but that generally he thinks drivers should have to justify potential panics more carefully than core code. Courbot thought that any code called from a device driver should probably not panic. Kent Overstreet cautioned against applying any rules too strictly, noting that people attempting to comply with strict requirements could mess the code up more than just accepting the occasional bit of messy code. Guo broadly agreed, saying that he thought it was a bad idea to try to eliminate panics completely. He would prefer self-contained components to be able to panic when given incorrect inputs, rather than pushing complexity onto calling code by returning a Result.
The word "self-contained" was the most important aspect of that, Courbot said.
If a component is self-contained, then it can be acceptable to panic, he said.
Ojeda added that many components aren't self-contained "with respect to
time
", and that panics can be hard for normal users to notice, report, and
diagnose.
At that point, the session ran out of time with no further agreement. There have been no updates to the Rust coding guidelines in the kernel since the conference. There were clearly some aspects of Rust coding style that the developers agreed on, but articulating those aspects as concrete guidelines may be a difficult task.
[ Thanks to the Linux Foundation, LWN's travel sponsor, for assistance with traveling to Kangrejos. ]
| Index entries for this article | |
|---|---|
| Conference | Kangrejos/2026 |
