Re: Thread Safety Analysis and the Linux kernel

Marco Elver <[email protected]> Mon, 5 May 2025 15:44:02 +0200
Newsgroups org.kernel.vger.linux-toolchains,dev.linux.lists.llvm
Message-ID <CANpmjNPRgUz9oX0H8kza2sB847Bai4rLtqfOnUSLmqt2Zm_pqA@mail.gmail.com>
On Wed, 5 Mar 2025 at 12:47, Marco Elver <[email protected]> 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.

Thanks,
-- Marco

> 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/[email protected]/
> -- quote: "Fix the analyzer instead."]
>
> 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.
>
> More complex requests:
>
> 4. The ability to deal with conditional locking with return values
> that are not just true/non-zero and false/zero. A concrete case here
> is that a lot of functions return error codes, and if the error code
> is < 0, no lock is taken. If the error code is >= 0, the lock is
> taken. [ Source:
> https://lore.kernel.org/all/[email protected]/
> ]
>
> 5. Better control-flow handling. Basic understanding of conditional
> locking, which is explicitly ruled out in:
> https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#conditional-locks
> - however, if there's some way to even get basic support, would vastly
> improve things for the kernel.
[...]