Re: Thread Safety Analysis and the Linux kernel

Marco Elver
2025-09-18T10:37:53Z

On Thu, 5 Jun 2025 at 14:44, Marco Elver <elver@google.com> wrote:
> On Mon, 5 May 2025 at 15:44, Marco Elver <elver@google.com> wrote:
> > On Wed, 5 Mar 2025 at 12:47, Marco Elver <elver@google.com> wrote:
> > [...]
> > > 1. Re-entrant acquires: rcu_read_lock(), preempt_disable(), etc. are
> > > all re-entrant locks. My proposal is to introduce an attribute that
> > > can be added to "ACQUIRE(..)" annotated functions to indicate they are
> > > re-entrant. Release-count needs to then match acquire-count to fully
> > > release a capability.
> >
> > FTR, reentrant locking support is taken care of:
> > https://github.com/llvm/llvm-project/pull/137133 (should land soon).
> >
> > But I think we need at least #2 (basic alias analysis) as well for
> > things to become tolerable for the kernel side. And that one looks a
> > bit harder to implement in Clang, so it'll be a while.
> [..]
> > > 2. Basic alias analysis, e.g. when storing a pointer to a lock in a
> > > function-local variable. [Complaint in:
> > > https://lore.kernel.org/all/569186c5-8663-43df-a01c-d543f57ce5ca@kernel.org/
> > > -- quote: "Fix the analyzer instead."]
>
> There is hope: https://github.com/llvm/llvm-project/pull/142955 - but
> it turned out to be "too easy to be true", so who knows if that'll
> stick.

This got merged and it seems to stick.
Intel test robot's bleeding-edge Clang version also picked it up
already, and if I expose it to this tree here:

https://git.kernel.org/pub/scm/linux/kernel/git/melver/linux.git/log/?h=cap-analysis/dev

It seems happy.

> > > 3. Ability to refer to locks in returned reference/pointer. For example:
> > > struct foo *ret_lock_struct(void) ACQUIRE(return->somelock);
> > > struct foo *try_ret_lock_struct(void) TRY_ACQUIRE(1, return->somelock); // locked if non-NULL
> > > I expect this also requires basic alias analysis to work so that
> > > assigning the returned pointer to a function-local variable and then
> > > later use in an unlock function works as expected.

I don't think this is going to happen, but with alias analysis we can
emulate this with a macro (see __acquire_ret helper).

So all in all, this might be as good as it gets for now from the Clang side.

Patch bomb away?