RE: Thread Safety Analysis and the Linux kernel

Puchert, Aaron
2025-03-07T21:50:35Z

> From: Bart Van Assche <bvanassche@acm.org>
> Would it be acceptable to introduce variants of the conditional locking
> functions that return the mutex pointer instead of a boolean to indicate
> whether or not locking succeeded? Would that be sufficient to change the
> type of 't' above from 'struct mutex *' into 'struct mutex *const'? Two
> examples of what such functions could look like:
>
> struct mutex *mutex_trylock_ptr(struct mutex *mutex)
> __cond_acquires(nonnull, mutex)
> {
> return mutex_trylock(mutex) ? mutex : NULL;
> }
>
> struct mutex *mutex_lock_interruptible_ptr(struct mutex *mutex, int *res)
> __cond_acquires(nonnull, mutex)
> {
> int ret = mutex_lock_interruptible(mutex);
>
> if (res)
> *res = ret;
>
> return ret == 0 ? mutex : NULL;
> }

Assuming that __cond_acquires is your macro for __attribute__((try_acquire_capability)), this shouldn't be an issue. We don't look into try-acquire annotated function bodies, and we can't because they're probably doing conditional locking internally, which we don't support. (Yet somehow we support try-acquire... but we do so by delaying acquisition to a branch on the return value.)

But even if we did, adding no_thread_safety_analysis to some internal functions should not be an issue. The value of the warning comes from analyzing large parts of the code base. If you exclude some locking internals you're not losing much.

Just in case this isn't clear: the attribute doesn't affect callers, and we don't do inlining. It simply turns off the analysis for this one function body.

Aaron