Skip to content

experiment with relaxing the orphan rule #136979

Closed

Description

@BennoLossin

View all comments

In Rust-for-Linux, we wish to split our single kernel crate into many smaller crates. There are various reasons for this:

  • the ability to individually turn some crates off when they are not needed (for example in configurations that don't build drivers depending on that crate)
  • splitting the code out of the rust/ directory and into their respective subsystems. Then every subsystem should have their own crate(s).
  • refactoring core APIs into their own crate in order to publish them to crates.io

While I was splitting off the pin-init crate from the kernel crate in order to keep it in sync with the user-space version, I ran into a problem with the orphan rule. We also had previously anticipated that issues with the orphan rule would pop up if we were to split our kernel crate. The issue that I am facing currently is not that bad, as I can solve it with an additional trait. But in the long run, it won't be feasible to always create a workaround for orphan rule conflicts.
Note that in the kernel crate, we don't need to be protected by the orphan rule, as all 1 dependents (and dependencies except core) of the kernel crate are under our control directly in-tree. So we would like to have some way to relax the orphan rule for our kernel crates.

Here is the error that I am currently running into.

I have this trait in pin-init (or the kernel crate before splitting):

/// Marker trait for types that can be initialized by writing just zeroes.
///
/// # Safety
///
/// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
/// this is not UB:
///
/// ```rust,ignore
/// let val: Self = unsafe { core::mem::zeroed() };
/// ```
pub unsafe trait Zeroable {}

And an impl in the kernel crate for our own Box type:

// SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
//
// In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant and there
// is no problem with a VTABLE pointer being null.
unsafe impl<T: ?Sized, A: Allocator> Zeroable for Option<Box<T, A>> {}

The error that I get is expected, as neither Zeroable nor Option<T> are declared by the kernel crate:

error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
   --> rust/kernel/alloc/kbox.rs:107:1
    |
107 | unsafe impl<T: ?Sized, A: Allocator> Zeroable for Option<Box<T, A>> {}
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------
    | |                                                 |
    | |                                                 `Option` is not defined in the current crate
    | impl doesn't use only types from inside the current crate
    |
    = note: define and implement a trait or new type instead

error: aborting due to 1 previous error

In the latest RfL sync meeting, I brought this up and @ojeda had a good way of highlighting the problem: it's a chicken-and-egg situation, until we can relax the orphan rule, we're not able to split our crate due to these errors. And in order to know how the orphan rule should be relaxed, we have to split our crate. For this reason, it was suggested in the latest RfL sync meeting to use the following approach: introduce a nightly flag that disables the orphan rule wholesale (edit: for binary crates) and add a lint that warns on the orphan rule being violated. This way, we can split the kernel crate and see what types of orphan rule violations we would like to use without actually stabilizing anything. Miguel also added that you do not even need to ship it into nightly, you can just give us a modified compiler repository and we can test locally with that.

So essentially, this issue is for getting the ball rolling and having some nightly-only/custom-compiler-only flag to disable the orphan rule and see what types of violations we would like to have relaxed. Figuring out a stabilizable solution should come later, when we have an overview over all of the different kinds of relaxations we would like to have.

There also has been a zulip discussion about this topic.

cc @rust-lang/lang

Footnotes

  1. while there are out-of-tree modules, they are always built for a pinned kernel version. When updating, they face the same issue on the C side, so it's OK to break them. ↩

Activity

  1. added
    needs-triage
    on Feb 13, 2025
  2. BennoLossin commented on Feb 13, 2025

    @BennoLossin
    ContributorAuthor

    @rustbot label +I-lang-nominated +I-types-nominated +A-rust-for-linux

  3. added
    A-rust-for-linux
    I-lang-nominated
    I-types-nominated
    on Feb 13, 2025
  4. added
    A-coherence
    and removed
    needs-triage
    on Feb 13, 2025
  5. added
    T-lang
    T-compiler
    T-types
    C-discussion
    needs-mcp
    and removed
    needs-mcp
    on Feb 13, 2025
  6. workingjubilee commented on Feb 13, 2025

    @workingjubilee
    Member

    Note that the Linux kernel would, if it shipped anything with this variant of the compiler, lock us into supporting this code for its LTS lifecycle, no matter how unsound it was. This problem has already occurred with other flags that were proposed for addition "until a better solution was found".

    Thus this proposed plan, and especially "just provide a modified compiler repo", is in conflict with our proposed project goal for stabilizing tooling for the kernel. A project I support, because then the kernel has less special asks "just for them" in our repository and inflicts less additional maintenance burdens.

  7. workingjubilee commented on Feb 13, 2025

    @workingjubilee
    Member

    and this was without needing to worrying about language issues, including an upstream language community which refuses to make any kind of backwards compatibility guarantees, and which is actively hostile to a second Rust compiler implementation (I suspect because it might limit their ability to make arbitrary backwards-incompatble language changes).

    This is the reputation we are getting in the kernel because Ted Ts'o thinks it's okay to bag on us because R4L uses unstable features. And this would be the most unstable of them all, because the flag would be inherently unsound, in this proposed form. I do not think it is a good idea to embark on a project to deliberately increase the amount of libelous accusations directed at our community.

  8. 17 remaining items

  9. joshtriplett commented on Feb 14, 2025

    @joshtriplett
    Member

    I think we're broadly in agreement. It is definitely not a "needed for RfL to be on stable" issue, and as such it also isn't part of that project goal.

    It's something I would advocate prioritizing in lang on the basis of "many people want this, and it's a multi-year arc we should embark upon because the sooner we start the sooner we finish".

    In any case, 👍 for embarking upon the experiment rather than spending more time evaluating rationale and prioritization. :)

  10. ojeda commented on Feb 14, 2025

    @ojeda
    Contributor

    This is not what is going to make RfL any less likely to succeed

    It is true that it is not important because we have kept a lot of the code in a single crate. However, we will really need to split it soon in many crates, and thus this may become more important soon, i.e. it could become a common pain point mentioned by kernel maintainers. We don't know how bad it will be yet, though.

    I think we all agree that it is not in the scope of the flagship project goal. Nevertheless, it is something that has been in our radar for a couple years.

  11. steffahn commented on Feb 15, 2025

    @steffahn
    Member

    The issue that I am facing currently is not that bad, as I can solve it with an additional trait. But in the long run, it won't be feasible to always create a workaround for orphan rule conflicts.

    I would love to see some actual examples of such cases.


    Note that in the kernel crate, we don't need to be protected by the orphan rule, as all dependents (and dependencies except core) of the kernel crate are under our control directly in-tree.

    I’m not sure I follow this argument… well it lacks explicit arguments anyway. I can only assume this argues from a perspective of “orphan rules protect semver-stable interfaces” and “orphan rules protect you from unexpected downstream breakage/overlaps”. But that’s an incomplete picture. I’ve recently written down some of my intuitions of a larger picture here (given this is mostly written from a user’s perspective, I’m not sure every point I’m making is actually correct… but I’m pretty certain with the challenges around vtables). I’m happy to hear any corrections or clarifications if I’m too pessimistic on any aspects.


    To re-iterate the high-level: The important difficulty with breaking orphan rules is two main aspects:

    • without orphan rules, a downstream crate might implement some impl Bar for Foo when Foo and Bar are already available together further upstream: thus there can some compilation (specifically monomorphization) of code involving thee concrete type&trait Foo and Bar where the impl Bar for Foo relation isn’t visible yet.
      • in many places around monomorphization, the compiler makes the assumption that for any known, concrete type Foo and Bar, it is already known whether or not Foo: Bar and this can’t change. Specialization uses this; vtable creation uses this.
      • this limitation is not all that relevant to your use-case as there’s usually some (at least 1) proper choice for the “crate that a trait implementation can be placed into”, anyway. (Sometimes this might mean cross-dependencies across otherwise “leaf” crates; or factoring out a trait-defining crate into its own thing, but if you control the whole code base, it shouldn’t really be an issue.)
    • the existence of orphan rules can be depended on by the trait solver itself. Sometimes it’s just really useful to be able to determining “this type can’t implement this trait”, especially for overlap checking, and this negative reasoning logic is defined on the assumption of orphan rules
      • this is an aspect of orphan rules & implementation details I’m less familiar with, so I don’t know how hard it would be to “fix” this, e.g. with some mechanism that turns a “upstream crate saw no possible overlap based on orphan rules, then downstream crate created an overlap anyways because it broke orphan rules” into a guaranteed compilation error downstream. Which turns the soundness issue back into a “semver” issue, i.e. the kind of thing you had in mind to begin with when arguing that “we don't need to be protected by the orphan rule”
      • your use case of Zeroable for Option<Box<T, A>> is interesting and only matches this second case
        • since Box is only defined in kernel (I assume… right?) there is no possibility for this Zeroable for Option<Box<T, A>> impl to be missing in any other crate’s compilation – in fact you could argue that of Option was a #[fundamental] type, then this impl would be legal here
          • I wonder if the right thing to discuss is a “mechanism to mark type constructors as #[fundamental] only for one particular trait” – I’m not sure whether or not the current trait solver needs to make the assumption anywhere that the set of #[fundamental] types is consistent across different traits
        • the workaround (I assume you’re using) of making a helper trait, e.g. ZeroableInOption and a blanket impl Zeroable for Option<T> where T: ZeroableInOption are good in that they also explicitly opt out of the – alternative – ability of local negative reasoning. Without it, you’d be able – inside of the crate defining Zeroable – to negatively reason that no Option<T>: Zeroable bound is ever true; allowing the overlap checker to depend on it, etc…
          • this workaround is essentially simulating the “opt out of #[fundamental]” ability. Perhaps simulating it quite effectively, actually. Of course it might seem more convenient to be able to write the Zeroable for Option<Box<T, A>> directly, but I’d be curious if there really are any actual practical use-cases (of this form where you’d believe “if this type was #[fundamental] I wouldn’t have any problems”) where the workaround doesn’t work.

    Now… I’ll come back again to the original point: I’m very curious to see more examples. Examples of that “it won't be feasible to always create a workaround for orphan rule conflicts”.

    For instance, in my original (linked) internals thread reply I already hadn’t actually thought up the example here at all, with Option covering a type parameter that should be filled with a concrete type downstream. The intuition that disabling orphan rules would always need to work analogously to sending trait implementations [and sometimes corresponding additional dependencies on a crate defining the trait or type in question] to upstream traits apparently was wrong, since the Zeroable for Option<Box<T, A>> wasn’t directly expressible anywhere.

    But with this example solved via a ZeroableInOption helper trait, I’m once again at a point where I’m having a hard time imagining what a use-case can look like that couldn’t be addressed by some combination of these mechanisms.

    Of course a 3rd possible use-case is when you actually want to somehow be like Foo: Bar can’t be defined here, but I’ll worry about it later, downstream. I can’t imagine that’s what this request to “relax the orphan rules” is about, because it’s clearly not just about orphan rules when you do need to write use-cases for the Foo: Bar upstream already; but still it’s also clear that an upstream API can be annoying to refactor by introducing some generic argument <T: SomeTrait>1 everywhere when you already know that there’s exactly one downstream implementation that’ll provide it.

    This general pattern can come up with orphan-rules considerations though, because I can imagine applying a “moving the otherwise-orphaned impl somewhere upstream” workaround can be hard when the implementation details use a lot of other stuff only available downstream.

    Footnotes

    1. In relation to Foo: Bar this would be understood that e.g. Foo: Bar is first refactored into some Dummy: Bar<Foo>-style trait, then Dummy is the downstream type that takes the role of T; and SomeTrait is the Bar<Foo>. ↩

  12. ojeda commented on Feb 15, 2025

    @ojeda
    Contributor

    Thanks @steffahn for all the context and explanations. Quick note...

    I’m very curious to see more examples. Examples of that “it won't be feasible to always create a workaround for orphan rule conflicts”.

    Even if there happen to be always workarounds (which would already be a nice result), part of the motivation here is to avoid those workarounds, i.e. to improve the language (if possible) so that they are not needed to begin with, thus improving ergonomics and making the crate boundary less special (for projects that may want/need that).

  13. oli-obk commented on Feb 15, 2025

    @oli-obk
    Contributor

    What steffahn is trying to say is that you're having us poke in the dark. We don't know what you are asking us to experiment with. For that matter, I'm not even sure all the problems being grouped under orphan rules are actually orphan rules.

    Please provide examples of the different kinds of workarounds you are considering.

    There are proposals I can think of that can be considered if someone writes a thorough enough analysis of the problems with said proposal (what Jack asks for in https://rust-lang.zulipchat.com/#narrow/channel/326866-t-types.2Fnominated/topic/.23136979.3A.20experiment.20with.20relaxing.20the.20orphan.20rule/near/499848638).

    And then there are proposals (that have frequently employed workarounds) that to the best of my knowledge have been hard rejected by every lang or compiler dev as long as I've been around rustc.

  14. ojeda commented on Feb 16, 2025

    @ojeda
    Contributor

    What steffahn is trying to say is that you're having us poke in the dark.

    I understood -- my reply was just a note on a particular point.

    We don't know what you are asking us to experiment with.

    We are not asking Rust to experiment with anything in particular. I think @y86-dev's initial message is quite clear on that. @joshtriplett also framed it well: "The question is more, how might we start figuring out a path to a feature we could feel confident in and stabilize? If it's going to take a while, taking a first step seems like a good idea."

    We are stating a problem we are facing and we had a suggestion that could perhaps allow us to experiment around how the kernel could potentially look like if some current restrictions (or their workarounds) were not there. The goal of that suggestion is to give you more information about what kind of code we would like to be able to write if possible. The overall goal is to learn more about the problem by using Linux as an example use case where we already collaborate.

    For that matter, I'm not even sure all the problems being grouped under orphan rules are actually orKhan rules.

    Definitely, that is a possibility. What we care about is the problem and whether there is anything that could potentially be done about it to improve how kernel code is written.

    There are proposals (...)

    That is good to know, thank you. However, to be clear, we are not trying to propose any particular solution.

  15. oli-obk commented on Feb 16, 2025

    @oli-obk
    Contributor

    how might we start figuring out a path to a feature we could feel confident in and stabilize?

    By splitting your crates the with the "workarounds" (I disagree they are really workarounds. They make reasoning about what happens where very simple) and reporting actual end user pain points.

  16. oli-obk commented on Feb 28, 2025

    @oli-obk
    Contributor

    I chatted with @compiler-errors about this a bit. As we talked about during the RfL meeting, what you actually need for this specific issue is the ability to define fundamental types. Now, this is not something we can expose on stable for the foreseeable future because it's a semver hazard, but

    • it's completely sound
    • will never be removed
    • unlikely to change any time soon and when it will the cost of keeping it around for years while you migrate to a stable version seems low

    So, my recommendation is that you try out this feature in your experiment. No new flags needed. If you decide it would be useful and solve most or all of your problems with crate splitting, let's discuss how to get it to you on stable. Old compilers can then just use the current overly permissive attribute

  17. ojeda commented on Feb 28, 2025

    @ojeda
    Contributor

    We can definitely give that a try, thanks a lot!

  18. added
    I-lang-radar
    and removed
    I-lang-nominated
    on May 7, 2025
  19. Houtamelo commented on Aug 11, 2025

    @Houtamelo
    Contributor

    I sadly do not have the bandwidth to hack on the rust compiler. We also need to go through the proper procedure on the Rust side to get it implemented, so I brought this topic up in the RfL sync meeting. TC suggested that I create this issue and so I did.

    Someone else has already done this.

  20. jackh726 commented on Jun 2, 2026

    @jackh726
    Member

    Good discussion here, but it's played its course. I'm going to close this. Future discussion or work here should probably just be discussed on Zulip or proposed as a Project goal.

    Nomination thread: https://rust-lang.zulipchat.com/#narrow/channel/326866-t-types.2Fnominated/topic/.23136979.3A.20experiment.20with.20relaxing.20the.20orphan.20rule/near/499526947

  21. removed
    I-types-nominated
    on Jun 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coherenceA-rust-for-linuxC-discussionI-lang-radarT-compilerT-langT-types

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions