Safe self-referential data structures in kernel Rust
Self-referential structures that can be used without unsafe code have posed a problem for Rust for years. There are many cases where a self-referential data structure is the elegant algorithmic choice, but implementing it in accordance with Rust's lifetime rules is all but impossible. At Kangrejos 2026, Gary Guo presented a clever solution to the problem in the context of the kernel's pin_init crate, which helps with the creation of immovable data structures, typically for interoperability with C. Guo's changes could help remove most of the unsafe code related to lifetimes in the Nova driver and, eventually, other Rust components.
Type theory background
Guo began with some background definitions from his slides that are necessary to understand the problem and his solution to it. Many programming languages have a notion of subtyping. For example, in Python all classes are subtypes of object. Rust has extremely limited subtyping, which only applies to types that differ only with regard to lifetimes. But, for example, the reference type &'a Foo is considered a subtype of &'b Foo when the lifetime 'a lasts longer than 'b. To put it another way, whenever the program asks for a reference that lasts at least as long as 'b, it is valid to supply an &'a Foo as long as 'a is, in fact, a lifetime that outlasts 'b.
For generic types, we can introduce some further relationships related to subtyping, he said. If some type Sub is a subtype of Super, then a generic type where Generic<Sub> is a subtype of Generic<Super> is called covariant. Built-in references are an example of a covariant type: an &&'a Foo (a reference to a reference to a Foo) is a subtype of &&'b Foo under the same conditions as the example above. On the other hand, some types work the opposite way. When Generic<Sub> is a supertype of Generic<Super>, Generic is said to be contravariant. An example is function types; the type fn(&'b Foo) is a subtype of fn(&'a Foo) because it is less demanding. Passing a function that expects a reference which lives at least as long as 'b to a piece of code that is going to give it something that lives for 'a is valid, as long as 'a outlives 'b.
And, of course, most generic types are neither subtypes nor supertypes of each other, even if they take the same type parameter. This case is called invariance. Mutable containers are almost always invariant, since if it were possible to write a supertype of the contained item into them, this could result in a container that contains the wrong type of item. An &mut &'a Foo and an &mut &'b Foo are not interchangeable in either direction, since the mutable reference can be read from (a covariant operation) and written to (a contravariant operation).
Another important background concept, Guo explained, is the idea of well-formedness. Referring to a type in a Rust program at all requires the compiler to check that the type is well-formed (i.e., that the type being named is allowed to exist at all). For example, if two lifetimes 'c and 'd exist and don't overlap at all, then trying to name the type "&'c &'d Foo" doesn't make sense, because no such thing can possibly exist. At the time the 'c lifetime starts, there can't be any 'd references, and vice versa. Writing a nested reference like the above requires that 'd lasts longer than 'c.
Rust programmers don't typically need to worry much about well-formedness, because the compiler inserts the necessary type bounds automatically. One use that does require manual tweaking is when the compiler warns that some generic type parameter needs to live for the 'static lifetime — that requirement comes from needing the type to outlive with some other lifetime in the program, and the only lifetime that outlives all other lifetimes is 'static.
One subtle detail about well-formedness in Rust was necessary to highlight: there is a difference between type inference in function signatures and function bodies. When a type appears in a function signature, the compiler assumes that it must be well-formed, and generates bounds that must be satisfied by the caller of the function to ensure that is the case. When a type appears in a function body, the compiler directly checks whether the written type is well-formed or not.
The last piece that Guo needed to introduce was a little more complicated. Polymorphism is the type-theory word for generics; a function is polymorphic if it takes a generic type parameter, and can therefore be called on several different types. Languages differ in exactly how they implement polymorphism, primarily on whether it is possible to define polymorphic function pointers, or whether function pointers must have a concrete type specified in advance. Rust chose the former option, which is known as higher-rank polymorphism, although it only allows it to apply to lifetime parameters. As a result, the following Rust code works:
fn foo<'a>(x: &'a u32) {}
fn test() {
// bar is a reference to a function ...
let bar = &foo;
// ... that can be called on references
// with two different lifetimes:
bar(&identity(1));
bar(&identity(2));
}
Note that the identity() function, which simply returns its input, is necessary here to prevent the compiler from determining the lifetimes to be 'static and therefore equivalent. Since the example takes references to two different temporary values, the former is always cleaned up by the time the latter executes, so the lifetimes are disjoint.
That example uses type inference to determine the type of bar, but if required to write it out, the programmer would write "&dyn for<'a> Fn(&'a u32)". That is, a pointer to a function that has a parameter which is a reference to a u32 that is valid for any lifetime that the caller names.
Device resource lifetimes
With that background out of the way, Guo was able talk about why the kernel needs self-referential structures. Devices can have resources that may only be accessed as long as the device is bound. For example, unplugging a device can unbind it, making it invalid to access its device memory. The original solution to modeling this in the Rust driver bindings was the Devres type, which used a Revocable pointer internally to force users to check that their device still existed on every access to it. This was messy, because it introduced fallible access paths across driver code, when the driver should really already know when a device is bound or unbound.
Eventually, an in-progress patch set needed access to a device while within the Drop implementation of a type, which is not permitted to fail. Fixing that with the existing abstractions would have required rewriting the type to not reference the device, which would have turned into a large refactoring of the driver's logic. Since it was obvious to human examination that the device could not be unbound in the relevant context, it would have also introduced several unreachable error paths. So, Guo began looking for a way to model this problem with Rust lifetimes, so that the compiler could be used to prove that the various error paths really were unnecessary.
The first problem is dealing with type erasure. Drivers can provide "auxiliary buses", which are interfaces that are exposed to other drivers. When another driver binds to the auxiliary bus, it receives an auxiliary::Device structure, which erases any type information about the driver it is bound to. If a driver's main structure does not have any generic lifetime parameters, it is easy to convert a Device to the expected type using Any:
impl auxiliary::Device {
fn registration_data<'this, T: Any>(&'this self)
-> Option<&'this T>;
}
The above is a simplified type compared to the implementation in the kernel, but it captures the same operation: given a reference to a Device, and some expected type T, registration_data() will either return a reference to T valid for the same lifetime, or fail. That only works when T implements Any, but only types that do not contain non-'static lifetimes are allowed to implement Any. So, in order to allow driver resources to be associated with lifetimes, Guo needed to change the registration_data() API to avoid using Any.
His proposed solution looks like this:
impl auxiliary::Device {
fn registration_data<'this,
for<'a> T<'a>
>(&'this self)
-> Option<&'this T<'this>>;
}
That is, require a driver type T to be well-formed for any lifetime, as expressed using a higher-rank polymorphic type (technically, a higher-kinded type, meaning a type that passes generic arguments to a type variable). That means that now, when trying to down-cast a Device into a T, the code can always produce a T value that lives for as long as the provided reference does. This is safe because the driver providing the auxiliary bus already needs to live for that lifetime. The change essentially allows the lifetime to be passed through the type-erased interface.
The problem is that Rust does not currently support writing the above. It may do so in the future, since the compiler team has been expanding support for higher-rank polymorphic types throughout the language slowly and cautiously, to avoid breaking the type system. Not much code needs to write higher-ranked types, so this is not normally a problem.
The fact that other parts of the language do support higher-rank polymorphic types, however, means that it is possible to implement a workaround by defining some helper traits and rewriting the function signature to use them. Implementing the helper trait correctly is tedious (and can sometimes expose bugs in the current trait solver), so the kernel provides a CovariantForLt!() macro (and a non-covariant version) that implements the boilerplate automatically. With that in place, the signature essentially becomes:
impl auxiliary::Device {
fn registration_data<'this,
T: CovariantForLt + 'static
>(&'this self)
-> Option<&'this T::Of<'this>>
}
The actual signature in the kernel also adds a Pin wrapper and uses Result to provide a more informative error message. With the problem of converting type-erased auxiliary::Device structures back into typed driver structures involving lifetimes solved, it is now possible to rewrite existing driver structures that use Devres to use plain references. For example:
struct MyDriver {
device: ARef<Device>,
pci_bar: Arc<Devres<Bar<BAR_SIZE>>>,
}
becomes:
struct MyDriver<'bound> {
device: &'bound Device,
pci_bar: Arc<Bar<'bound, BAR_SIZE>>,
}
This is better, but it still includes a reference-counted pointer, Arc, when it really shouldn't be needed: conceptually, the PCI base address register (BAR) should live for the same amount of time as the Device structure. That can be worked around; the Nova driver uses unsafe code to initialize a structure that looks like this:
#[pin_data]
struct NovaCore<'bound> {
reg: auxiliary::Registration<
'bound, ForLt!(NovaCoreApi<'_>)
>,
gpu: Gpu<'bound>,
bar: Bar<'bound, BAR_SIZE>,
}
The reason that code is unsafe is that gpu holds a reference to the BAR internally, so it should not outlive the Bar structure, but this declaration says that they live for the same amount of time. That makes constructing and deconstructing values of this type require a small amount of unsafe code. It would be a better solution if it were possible to teach the existing pin_init!() macro to handle all of the unsafe parts and make creating a NovaCore structure safe. The entire effort began by trying to remove unnecessary error paths in drivers; replacing those with more unsafe code would not be a huge improvement.
This is a known problem in the Rust ecosystem, Guo said. Several existing crates, such as moveit, rental, yoke, and ouroboros implement self-referential structure initialization for safe code. The kernel's requirements make adopting their use quite difficult, however. The user-space crates all assume that implicit allocation is acceptable in some cases, but it is not permitted in the kernel in general. Additionally, many of the existing crates are unsound — they do not implement their unsafe components correctly, and it is possible to write seemingly safe code using them that breaks Rust's language guarantees.
So, Guo decided to figure out a solution himself. With his patch set, it is now possible to write Nova's driver structure like this:
#[pin_data]
struct NovaCore<'bound> {
reg: auxiliary::Registration<
'gpu, ForLt!(NovaCoreApi<'_>)
>,
gpu: Gpu<'bar>,
bar: Bar<'bound, BAR_SIZE>,
}
And to initialize the resulting structure using a normal pin_init!() call. He is fairly certain that his solution is sound, although the latter half of the talk was dedicated to explaining the great lengths necessary to achieve that. The key syntactical change is that now the #[pin_data] macro allows using the names of members of the structure as lifetimes. Therefore, the code can accurately record the fact that gpu keeps a reference to bar or that reg references gpu. Using this information, in turn, it generates code for constructing and deconstructing the self-referential structure correctly.
Actually accessing the self-referential fields is a little different, because the language doesn't really support accessing self-referential fields. Instead, the #[pin_data] macro generates helper functions. A field named foo will generate a method called foo() (for covariant fields) or with_foo() (for invariant fields). Writing to the structure can be done using the with_project() helper function. That syntax could potentially be improved a bit if the Beyond the & initiative makes progress.
The long, hard road to soundness
Writing a basic macro that allows that syntax to work was not really the hard part, however, Guo explained. The part that took up most of his time was making sure that the resulting interface was completely sound. To illustrate why, he put up the simplest possible example, and then walked through a number of potential macro implementations and why they were wrong.
#[pin_data]
struct MyStruct {
borrow: &'owner String,
owner: String,
}
The easiest way to expand this would be to convert the &'owner String type to &'static String and then check accesses to the field. This doesn't work because user code could just access the borrow field directly, without the check, and do something that violates the 'owner lifetime.
Preventing that is not particularly difficult. The pin_init crate can define a private wrapper type, Erase, and use it to wrap the value of the field. That way other code cannot directly access the value of the field. Except that is not sound either, because auto traits can still observe the wrapped type, and therefore make incorrect inferences based on the 'static lifetime. That is not observable with the example because String is thread-safe (Sync), but it could come up with other types. If the given example were expanded to use 'static, the compiler would infer that it should implement Send, which allows sending the structure to another thread, and that is not necessarily permitted.
So, to prevent that, it is once again necessary to turn to higher-rank polymorphism. The pin_init crate defines a much fancier wrapper type, and this allows the compiler to infer auto trait implementations correctly. The most complex part of the fancy wrapper type is the fact that it needs to be written recursively, to deal with cases where a field references the lifetime of multiple other fields. In the code below, the implementations of traits for (T,) are the base case of the recursion, where the one-item tuple type (_,) is used as a marker that it is time to stop. The recursive case uses function types as wrappers to introduce lifetimes, since function types are allowed to be written with higher-rank polymorphism.
trait EraseLifetime {
type Erased;
}
impl<T> EraseLifetime for (T,) {
type Erased = T;
}
impl<T> EraseLifetime for T where
T: for<'a> FnOnce<(&'a (),), Output: EraseLifetime>,
{
type Erased = <
<T as FnOnce<(&'static (),)>>::Output
as EraseLifetime
>::Erased;
}
#[repr(transparent)]
pub struct Erase<F: EraseLifetime>(F::Erased);
unsafe impl<T: Send> Send for Erase<(T,)> {}
unsafe impl<F: EraseLifetime> Send for Erase<F>
where
F: for<'a> FnOnce<(&'a (),), Output::EraseLifetime>,
for<'a> Erase<<F as FnOnce<(&'a (),)>>::Output>: Send,
{}
The result is a way for the macro to encode a type that essentially acts as for<'a> Foo<'a> even though Rust does not yet permit that for non-function types. The minimal example can be expanded to:
struct MyStruct {
borrow: Erase<
for<'owner> fn(&'owner ()) -> (&'owner String,)
>,
owner: String,
}
That way code outside of pin_init cannot directly access the data inside borrow, but it also isn't given an incorrect lifetime such as 'static, so the compiler is happy. There is an unstable Rust feature, unsafe binders, which would let the entire wrapper type be done away with, in favor of writing:
struct MyStruct {
borrow: unsafe<'owner> &'owner String,
owner: String,
}
Until that feature is stabilized, however, the wrapper-based workaround allows pin_init to restrict access to the underlying field just as well, and users will not need to care much about the implementation since it is internal to pin_init. Guo did warn that, if the kernel ever changed the semantics of pinning to be per-byte, the above implementation would become unsound and would need to be updated.
Stop, drop, and roll
There is some work still needed, however: the above allows self-referential structures to be
safely constructed, but it is still possible to cause problems when
freeing them. "This is one of the parts of the
language [that] I hate most. Of many,
" Guo said.
In Rust, the compiler will
drop fields of a
structure in order. If the owner field is listed first, then it will be
dropped first, which will make borrow into a dangling reference, which
is not permitted.
It is fairly easy to check that fields are declared in the right order by making sure that fields can only refer to later fields. Except that check alone is not enough. Consider this pathological example:
#[pin_data]
struct MyStruct {
what_the_heck: &'later_owner &'owner (),
borrow: &'owner String,
owner: String,
later_borrow: &'later_owner String,
later_owner: String,
}
The existence of a &'later_owner &'owner () makes the compiler assume that 'owner must be a longer lifetime than 'later_owner, which isn't true, because owner is dropped first. This makes it possible to convert a &'owner String into an &'later_owner String, so user code could take the value in borrow, move it to later_borrow and access owner after it has already been dropped.
This is because the compiler assumes that references in structure definitions are well-formed — an assumption that is generally safe in the absence of macros doing strange things with lifetimes. Luckily, there is a separate context where well-formedness is checked rather than assumed: inside a function body. The solution, therefore, is to have #[pin_data] generate a new function, which will never be called, that declares local variables with the same types in the order that they will be dropped. Even though it won't be called, the compiler will still type-check it, which makes the example above emit a compiler error.
Access
With creation and destruction handled, Guo turned his attention to accessing fields. Direct access is blocked by the opaque wrapper, but developers still need to access those values somehow. For covariant fields, it's easy to generate a method that takes a reference to the overall structure and returns a reference to a specific field. Non-covariant fields are more complicated, because the code needs to ensure that the involved lifetimes are not inadvertently extended. Guo accomplishes this by introducing a callback-based API that uses a higher-ranked polymorphic function trait bound to ensure that the provided callback is able to comply with the requirements imposed by the self-referential type.
This technically lets users access the fields of the structure, but it's not easy to access multiple non-covariant fields at the same time. Therefore, the macro also generates a project() method that produces a new type that downgrades borrowed fields to shared references. Invariant fields are removed, since they can't be safely downgraded in this way. The result is a new type that provides convenient read-only access to most fields of the structure at the same time.
But sometimes code needs mutable access to multiple fields simultaneously, or to invariant fields. To handle that, Guo's code generates a final method, with_project(), that uses the same callback-based interface to provide access to a projected type holding mutable references to the self-referential type's fields.
"This is perhaps one of the most thorough defenses ever done by a
self-referential library,
" Guo said. Despite the complicated code
generation, he believed that the resulting design was sound, and as ergonomic as
it could be given the kernel's constraints. Since every property relied on for
soundness was checked by generating code that used Rust's type system to perform
the check, he was convinced that the design was good.
The next problem
At least, he was convinced until Danilo Krummrich tried to use the new design in Nova, and ended up producing an example that should have worked, but instead resulted in a difficult compilation error. The core part of his example looks like this:
#[pin_data]
pub(crate) struct CommandQueue<'a> {
#[pin]
#[not_covariant]
inner: Mutex<CommandQueueInner<'a>>,
}
Nvidia GPUs have a command queue that is used to communicate with the GPU system processor (GSP). Access is protected by a mutex, so that the command queue structure can be shared between threads. In practice, the code never actually puts new data with a lifetime inside the inner structure, but the compiler has no way to know that. Therefore, introducing the mutex makes the field invariant over 'a. That would not be a problem if that invariance did not propagate to other structures that contain a reference to the command queue, eventually reaching the top level NovaCore structure.
That leads to problems when constructing an auxiliary device. The auxiliary registration field in NovaCore uses the ForLt!() macro discussed above. That macro only allows a structure to be generic over a single lifetime, which is the lifetime of the overall driver in this case. Since the propagated lifetime from the command queue ends up being fixed by the command queue's invariance, the auxiliary registration must be given two incompatible lifetimes.
Guo was eventually able to discover a workaround: keep a reference to the overall device in the command queue structure, so that the data inside the mutex can refer to its lifetime directly. Due to well-formedness constraints, this lets the compiler see that the two syntactically different lifetimes are compatible, and eliminates the problem.
#[pin_data]
pub(crate) struct CommandQueue<'a> {
#[pin]
#[not_covariant]
inner: Mutex<CommandQueueInner<'dev>>,
dev: &'a Device<Bound>,
}
But is this workaround really sound? As it turns out, no, and it reveals a problem in the implementation of #[pin_data]. To explain why this workaround is invalid, Guo needed to turn to the concept of an existential lifetime.
Existential lifetimes
At this point, Guo switched to a slide showing formal type-theory inference rules, which produced some general disbelieving laughter. Guo insisted that this really was the best way to understand. The code examples he had shown so far had included higher-ranked universal quantification: for<'a> &'a Foo is a type that is valid for any choice of 'a. Existential lifetimes are the opposite (or, more specifically, the categorical dual): a type that is valid for some lifetime 'a, but the programmer is not required to name which specific lifetime they are talking about. Rust mostly does not support them, but if it did, a syntax such as exists<'a> Foo<'a> might be taken to mean that there is some choice of lifetime that makes Foo<'a> a valid type, but the specific choice is not being named.
If such a type existed, then it would be possible to write self-referential structures using it, with the exists clause serving to introduce the lifetimes of individual fields:
struct MyStruct {
borrow: exists<'owner> &'owner String,
owner: String,
}
This is helpful because it would remove the need for a generic lifetime parameter to be passed to self-referential structures, which would make the types themselves lifetime-free. And there is a way to write this in Rust, even though it doesn't support existential types directly. The Church encoding of existential types allows them to be expressed in terms of universally quantified higher-ranked polymorphic types. The existential type:
type X = exists<'a> Foo<'a>;
becomes:
trait ExistsFoo {
fn with<R>(
self,
f: impl for<'a> FnOnce(Foo<'a>) -> R
) -> R;
}
type X = dyn ExistsFoo;
This is exactly the encoding that the generated with_*() methods
produce. Guo called this approach
"basically ForLt!() turned inside out,
" although the
correspondence was not particularly obvious.
That correspondence did show that the problematic command-queue type could be rewritten in terms of exists. That produces a type that is structurally similar to the below:
type X<'a> = exists<'b> (&'b &'a String, Mutex<&'b String>);
Treating that type as covariant over 'a would be unsound. The presence of the first reference implies that 'a outlives 'b. That's not true under that assumption in general, because 'a could be covariantly shortened, leading to a use-after-free bug. This is strange because the corresponding structure type that does not use existential types is sound:
type X<'a, 'b> = (&'b &'a String, Mutex<&'b String>);
In this case, the compiler has enough information to say that 'b forms a lower-bound on 'a. Therefore, it forbids shortening 'a in such a way that it would no longer outlive 'b. The compiler couldn't make that determination in the hypothetical existential-type version because the lifetime 'b was effectively erased by the exists binding.
So, this suggests a more restrictive subtyping rule for existential lifetimes: in order to be able to say that an expression involving existential types is covariant over a free lifetime 'a, that lifetime must occur in covariant position and no erased non-covariant lifetime may be a lower bound for it, as implied by the well-formedness conditions. It is acceptable for erased non-covariant lifetimes to be upper bounds for 'a, however. This alternate rule would make the problematic existential type invariant over 'a, which would be safe.
Existential lifetimes do not exist in Rust today, but if they were ever implemented they would need to follow this rule to be sound, Guo said.
Back through the mirror
With that insight in hand, it is possible to transform the problematic type back to the format that the command queue structure was written in. This adds an additional check to the generated code, and correctly causes the compiler to determine that CommandQueue<'a> is invariant over 'a.
That closes the soundness hole, but it still leaves a problem: the whole motivation of adopting the workaround in the command-queue structure was to ensure that the type would be covariant over 'a, so that its invariant nature does not propagate up to the root driver and cause problems for the auxiliary binder. Therefore, it would be pleasant to have a way to write that correctly.
The solution is a slight extension to the #[pin_data] macro, allowing it to introduce new lifetimes that are used as upper bounds for lifetime parameters (lifetimes that must live longer than the lifetime parameter). Since that is an exception to the more restrictive subtyping rule for existential lifetimes, it allows introducing an existential lifetime that cannot be misused to cause a use-after-free bug. But because the Church encoding of an existential type would be complex to write, the macro adopts some custom syntax to allow writing exists bindings, even though Rust does not normally support those. The result is that the command-queue type can be written like this:
#[pin_data]
pub(crate) struct CommandQueue<'a>
where
exists<'cmdq>: 'a,
{
#[pin]
#[not_covariant]
inner: Mutex<CommandQueueInner<'cmdq>>,
}
With this, all lifetime-related unsafe code in Nova can be removed, Guo said, apart from the debugfs code which needs an additional interface change. In terms of the implementation, it adds surprisingly little code to pin_init, since much of the implementation can be shared with covariant self-referential fields.
Next steps
Guo is pretty sure this time that the final implementation of #[pin_data] is correct. It also should not require users to understand most of the details that he went over in his talk. For the most part, users should be able to write self-referential structures just by using field names as lifetimes:
#[pin_data]
struct Example {
borrower: &'owner Foo,
owner: Foo,
}
If they do something invalid, such as writing borrower after owner, the macro will say so with an explanatory message. Similarly, it infers the use of helper annotations like #[not_covariant] as far as possible. Guo isn't completely happy with the quality of the error messages; originally, he hoped to get a limited form upstream in this kernel cycle, so that he had time to work on improving the error messages and documentation for the rest of the work. Discussions after the conference convinced him to post all of the work as one series.
Still, despite Guo's commendable dedication to ensuring that the solution is simple for users, the solution is not particularly simple for reviewers of pin_init. By the end of Guo's talk, many of the kernel developers in attendance seemed somewhat shell-shocked. Whether Guo is able to get reasonable reviews of his patch set remains to be seen.
[ Thanks to the Linux Foundation, LWN's travel sponsor, for their assistance in traveling to Kangrejos. ]
| Index entries for this article | |
|---|---|
| Conference | Kangrejos/2026 |
The LWN site is currently under high scraper load, so comment display has been suppressed for anonymous users. If you are a human, you may read the comments by clicking the button below:
Note: you can avoid this step in the future by logging into your LWN account.
