Re: [TECH TOPIC] Rust for Linux

Miguel Ojeda
2021-07-08T18:00:27Z

On Thu, Jul 8, 2021 at 4:58 PM Greg KH <greg@kroah.com> wrote:
>
> Ok, great, then how would you handle the kref issue where you need an
> external lock to properly handle the reference counting logic in Rust?
> Why is C so "bad" here that we require a lock but Rust would not?

That's the thing: neither C nor Rust need a lock to handle the
refcount itself, i.e. `kref` does not contain a lock, neither `Ref<T>`
does.

A lock is needed when you actually interact with the contents that are
refcounted (see my previous message about `Ref<T>`) -- and this
applies the same way to Rust and C.

What Rust is buying is, though, and this is the critical point, is
that we cannot make a mistake forgetting that we need to have some
form of lock to concurrently mutate things nor forgetting we need to
actually lock it.

Thus, in a way, you could think that the rules in `Doc/kref.txt` would
be now enforced statically -- that is the difference.

> Ok, what "model" would be better? We need a "base object" that has
> solid lifecycle rules. Right now we do have that, but it's just not the
> easiest to use for complex objects where we have multiple objects with
> different lifecycles that all interact together. The v4l example is the
> best, but the input layer also has this type of issue.

The model can be very similar conceptually, but if we can take the
freedom to manage the objects in the Rust side instead of forcing
ourselves to go through C APIs (e.g. `devm_*`, dealing with
self-referential structs, etc.), then things can be way simpler.

Which is why I am asking: so far we have tried hard to reuse the C
APIs and types, but if we can relax that constraint and come up with
our own model (where the Rust side keeps ownership of objects), then
we will likely end up with something better (for the Rust side).

Basically, the idea is doing things in a way that is amenable to
Rust's strengths, so that modules written in Rust are easier to write
and so that we minimize even further the need for `unsafe`.

To be extra clear: it is not that Rust cannot use/express/wrap those C
patterns -- the key is that some of those C patterns cannot be
statically proven to be correct by the Rust compiler (and thus require
trusting ourselves to get them right, like in C).

Cheers,
Miguel