Re: [PATCH v9 12/27] rust: add `kernel` crate

From: Wedson Almeida Filho
Date: Mon Sep 19 2022 - 14:05:39 EST


On Mon, Sep 19, 2022 at 10:20:52AM -0700, Linus Torvalds wrote:
> On Mon, Sep 19, 2022 at 9:09 AM Linus Torvalds
> <torvalds@xxxxxxxxxxxxxxxxxxxx> wrote:
> >
> > The whole "really know what context this code is running within" is
> > really important. You may want to write very explicit comments about
> > it.
>
> Side note: a corollary of this is that people should avoid "dynamic
> context" things like the plague, because it makes for such pain when
> the context isn't statically obvious.

As you know, we're trying to guarantee the absence of undefined
behaviour for code written in Rust. And the context is _really_
important, so important that leaving it up to comments isn't enough.

I don't care as much about allocation flags as I do about sleeping in an
rcu read-side critical region. When CONFIG_PREEMPT=n, if some CPU makes
the mistake of sleeping between rcu_read_lock()/rcu_read_unlock(), RCU
will take that as a quiescent state, which may cause unsuspecting code
waiting for a grace period to wake up too early and potentially free
memory that is still in use, which is obviously undefined behaviour.

We generally have two routes to avoid undefined behaviour: detect at
compile time (and fail compilation) or at runtime (and stop things
before they go too far). The former, while feasible, would require some
static analysi or passing tokens as arguments to guarantee that we're in
sleepable context when sleeping (all ellided at compile time, so
zero-cost in terms of run-time performance), but likely painful to
program use.

Always having preempt_count would allow us to detect such issues in RCU
at runtime (for both C and Rust) and prevent user-after-frees.

Do you have an opinion on the above?

Cheers,
-Wedson