Re: [TECH TOPIC] Rust for Linux

Laurent Pinchart
2021-07-07T21:47:47Z

On Wed, Jul 07, 2021 at 10:58:44PM +0200, Miguel Ojeda wrote:
> On Wed, Jul 7, 2021 at 7:20 PM Greg KH <greg@kroah.com> wrote:
> >
> > That's not what I meant by bringing up a kref. I was trying to ask
> > where the "real" lock here is. It has to be somewhere...
>
> Given this sentence, I think I understand where the confusion comes
> from. The key is that `Ref` (`Arc`) is not adding any thread-safety to
> the `T` it wraps -- it is only concerned about providing
> reference-counting semantics.
>
> For that it only needs to keep a thread-safe refcount for a given `T`.
> But the `T` might be (or not!) thread-safe. Since the refcount is an
> atomic, that is enough for implementing `Ref<T>`, no locks are needed.
>
> Now, if you need mutable access to the content of an `Ref<T>` that is
> shared by several threads at the same time, you need something extra
> -- that is where you would need a lock. For instance, in normal Rust
> code you may see a `Arc<Mutex<T>>` being used.
>
> The big thing is that if you get any of this wrong, you get a
> compile-time error. For instance, if you create a `Ref<T>` out of a
> `T` that is not marked as safe to be sent across threads, you get an
> error when you try to send the `Ref`. Or if you create a `Ref<T>` and
> try to call a method that mutates the `T` across threads, you will
> also get a compile-time error. Thus you cannot forget to have a lock
> if it is needed.

Out of curiosity: we have in the kernel objects shared between multiple
threads that require locking, but in some contexts taking the lock isn't
required. I'm thinking in particular about initialization time when you
create the object, before it is made visible to other users, or
destruction time, when you nobody else can have a reference to the
object anymore. Avoiding lock operations in those cases can be an
optimization. Cn rust handle that ?

--
Regards,

Laurent Pinchart