Re: [PATCH v10 1/5] rust: types: Add Ownable/Owned types

From: Benno Lossin
Date: Wed Jun 18 2025 - 17:23:25 EST


On Tue Jun 17, 2025 at 11:58 AM CEST, Oliver Mangold wrote:
> On 250514 1132, Benno Lossin wrote:
>> On Fri May 2, 2025 at 11:02 AM CEST, Oliver Mangold wrote:
>> > +///
>> > +/// # Safety
>> > +///
>> > +/// Implementers must ensure that:
>> > +/// - Any objects owned by Rust as [`Owned<T>`] stay alive while that owned reference exists (i.e.
>> > +/// until the [`release()`](Ownable::release) trait method is called).
>>
>> I don't immediately understand what this means. How about "Any value of
>> type `Self` needs to be stored as [`Owned<Self>`]."?
>
> Let me think. The safety requirements here talk about safety of
> implementing the trait. But if you have a `Self` which is not wrapped, you
> still cannot create an `Owned<Self>` in safe code. It's different from an
> `AlwaysRefCounted`, where an `ARef<Self>` can be created from a `&Self`.

That might be true, but AFAIK this trait is designed to be used for
stuff that has a `create_foo` and `destroy_foo` function in C returning
and taking a raw pointer to `foo` respectively. So creating it on the
stack doesn't make sense.

If we do want to make this trait more general, then we can do so, but
this is my current understanding.

>> And then ask in
>> `Owned::from_raw` for a pointer that is valid indefinitely (or at least
>> until `release` is called).
>
> So, hmm, I think one could even move this safety requirement to `Owned::from_raw()`.
>
>> > +/// - That the C code follows the usual mutable reference requirements. That is, the kernel will
>> > +/// never mutate the [`Ownable`] (excluding internal mutability that follows the usual rules)
>> > +/// while Rust owns it.
>>
>> I feel like this requirement is better put on the `Owned::from_raw`
>> function.
>
> Together with the above, this would leave to safety requirements for `Ownable.
> Make `Ownable` a safe trait, then? Instead of safety requirements just add an invariant:
>
> # Invariant
>
> An `Owned<Self>` represents a unique reference to a `Self`, thus holding
> an `Owned<Self>` or `&mut Owned<Self>` allows one to assume that the object
> is not accessed concurrently from elsewhere.
>
> Not sure what is best. Would that make sense?

Making it safe makes sense, when we can move all requirements to
`Owned::from_raw`. I don't think the invariants section makes sense, how
would the trait have any influence in that when `Owned::from_raw`
already guarantees it?

---
Cheers,
Benno