|
|
Log in / Subscribe / Register

Guidelines for panics in kernel code

By Daroc Alden
October 27, 2026

Kangrejos

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
ConferenceKangrejos/2026


to post comments

It may depend on the user more than the kernel developer

Posted Oct 27, 2026 21:56 UTC (Tue) by roc (subscriber, #30627) [Link] (3 responses)

For many users, security is a priority, and they'd much rather crash than let the kernel get into a bad state that raises the chance of compromise. This should probably be most users, these days.

For some users, they're depending on other security perimeters and don't need to trust the kernel all that much, so they might prefer the kernel to struggle on than crash if it's "probably OK".

It may depend on the user more than the kernel developer

Posted Oct 28, 2026 0:41 UTC (Wed) by Gnurou (subscriber, #85058) [Link] (2 responses)

"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.

To clarify, I was referring to Intel's 0-day CI emails. It happened a couple of times that something relying on build_assert! worked perfectly fine locally, only to fail on an unusual configuration after the patch is merged because (as you correctly said) the optimizer worked differently in that configuration.

There have been no updates to the Rust coding guidelines in the kernel since the conference.

... and I'm glad I waited a bit before sending them as this article gathered the discussion points and conclusions much more clearly than my recollection of the talk. :) Thank you for writing it!

It may depend on the user more than the kernel developer

Posted Oct 28, 2026 0:44 UTC (Wed) by Gnurou (subscriber, #85058) [Link]

Apologies, this was meant to be a new thread rather than a reply, I hit the wrong button. :( Would appreciate if a moderator could move into its own thread (I guess the title could be "Clarification on build_assert" or something).

It may depend on the user more than the kernel developer

Posted Oct 28, 2026 9:20 UTC (Wed) by micka (subscriber, #38720) [Link]

Are you refering to CI specific co figurations, the one tjat should end with "fix your CI setup"?

Erroneous behavior

Posted Oct 28, 2026 10:26 UTC (Wed) by taladar (subscriber, #68407) [Link] (3 responses)

I really don't agree with the idea that erroneous behavior is acceptable as an error handling technique. That is exactly the way you make life more complicated for everyone who has to debug any code that uses that function in the future. Much better to even panic in those cases since then at least it is obvious that something is in need of fixing.

Erroneous behavior

Posted Oct 28, 2026 11:13 UTC (Wed) by farnz (subscriber, #17727) [Link]

There's a nuance here - for things like udelay, documentation that says something like "attempts to busy-wait for the given Delta. If the Delta is more than 1 millisecond, will sleep for at least 1 ms, and up to an architecture-defined limit; may delay for up to 10% less than the requested time" means that udelay returning early if asked to delay for 3 ms is defined behaviour in the docs, but surprising to callers (especially since whether it works or not depends on architecture).

And this is a good example to play with precisely because of that "architecture-defined limit" and the "may return early". On some systems, it'll sleep for up to 5 ms; on others, up to 2 ms. Documenting 1 millisecond is safe, because that will always work; but depending on why you're using it, being able to sleep for a little bit over 1 ms is useful. In an ideal world, neither of those would be the case - the limit would be set by the kernel, not the architecture, and it would guarantee to delay for more than the requested time - but fixing that is a much bigger deal than accepting a small amount of (mostly harmless, in practice - you wouldn't want to busy wait for a long time, anyway) surprising behaviour.

Erroneous behavior

Posted Nov 6, 2026 17:29 UTC (Fri) by nytpu (guest, #181939) [Link] (1 responses)

Four words: Ariane 5 Flight 501

(The two redundant Inertial Reference System computers were running the same software and given the same inputs, and both of them raised an exception and shut down after receiving sensor values out of the expected range, causing the rocket to lose all inertial reference and begin to tumble in-flight. The values that that were outside of the expected range were completely irrelevant to the rocket while in flight and were only meaningful on the launch pad, so if it had just produced erroneous output it would've had literally zero effect on the rocket instead of causing complete loss of control)

Erroneous behavior

Posted Nov 6, 2026 17:58 UTC (Fri) by mb (subscriber, #50428) [Link]

Yeah, well. This is one example.
It's also possible to find examples of where continuing the execution would have been fatal and a coordinated reboot of the system would have been the correct solution.

Unfortunately these things are mutually exclusive and there isn't a right answer on this level.
If you want to be robust against these kind of failures, you have to implement safety measures to detect and handle them. Just continuing might not be acceptable. Just halting might not be acceptable. Just rebooting might not be acceptable. It all depends on the threat model of the system.

Clamping delay()

Posted Oct 28, 2026 10:36 UTC (Wed) by geert (subscriber, #98403) [Link] (1 responses)

Silently clamping delay() will cause hard to debug bugs in drivers.

Clamping delay()

Posted Oct 30, 2026 18:38 UTC (Fri) by marcH (subscriber, #57642) [Link]

Exactly where a warning can save a lot of time.

Logging wasn't part of this discussion at all? Disappointing.

Interestingly, the choice of the logging level for a given statement is not an exact science either - just like error handling. Because they're both about an uncertain future.

One of reasons to want to keep a system limping instead of dying is: more chance to collect more forensics while still limping. This is another way logging and error handling are connected to each other.

from_ghz overflow is probably defined in C

Posted Oct 31, 2026 18:48 UTC (Sat) by anton (subscriber, #25547) [Link]

In the from_ghz example, if the types in the equivalent C code are unsigned long, as the Rust names suggest, an overflow is defined as producing the result modulo 2^b-1 (where b is the number of bits of an unsigned long); I doubt that is intended in this case.

For 64-bit systems, the overflow happens in C for ghz>18446744073, and the function is probably never called with such an argument, at least for computer-internal frequencies. For 32-bit systems, however, the overflow happens in C for ghz>4, which happens to be true for the clock rate of my current CPU. unsigned long long might be an appropriate C type for the result of from_ghz, and in that case, e.g. GHZ_TO_HZ should be an unsigned long long to make the * become an unsigned long long multiplication.


Copyright © 2026, Eklektix, Inc.
This article may be redistributed under the terms of the Creative Commons CC BY-SA 4.0 license
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds