Re: C aggregate passing (Rust kernel policy)

Linus Torvalds
2025-02-26T22:28:15Z

On Wed, 26 Feb 2025 at 14:12, Steven Rostedt <rostedt@goodmis.org> wrote:
>
> I take this is what you meant by following what the code does.
>
> r = global;
> if (r > 1000)
> goto out;
> x = r;
>
> Is the code saying to read "global" once. But today the compiler may not do
> that and we have to use READ_ONCE() to prevent it.

Exactly.

And as mentioned, as far as I actually know, neither clang nor gcc
will actually screw it up.

But the C standard *allows* the compiler to basically turn the above into:

> But if I used:
>
> if (global > 1000)
> goto out;
> x = global;

which can have the TUCTOU issue because 'global' is read twice.

> I guess this is where you say "volatile" is too strong, as this isn't an
> issue and is an optimization the compiler can do.

Yes. 'volatile' is horrendous. It was designed for MMIO, not for
memory, and it shows.

Now, in the kernel we obviously use volatile for MMIO too, and in the
context of that (ie 'readl()' and 'writel()') it's doing pretty much
exactly what it should do.

But in the kernel, when we use 'READ_ONCE()', we basically almost
always actually mean "READ_AT_MOST_ONCE()". It's not that we
necessarily need *exactly* once, but we require that we get one single
stable value).

(And same for WRITE_ONCE()).

We also have worried about access tearing issues, so
READ_ONCE/WRITE_ONCE also check that it's an atomic type etc, so it's
not *purely* about the "no rematerialization" kinds of issues. Again,
those aren't actually necessarily things compilers get wrong, but they
are things that the standard is silent on.

Linus