Re: Thread Safety Analysis and the Linux kernel

Bart Van Assche
2025-03-06T16:18:48Z

On 3/6/25 1:47 AM, Peter Zijlstra wrote:
> That no longer works for the case of:
>
> DEFINE_GUARD_COND(mutex, _try, mutex_trylock(_T))
>
> which expands to have a constructor like:
>
> static inline struct mutex * class_mutex_try_constructor(struct mutex *_T)
> {
> struct mutex * t = ({ void *_t = _T; if (_T && !(mutex_trylock(_T))) _t = NULL; _t; });
> return t;
> }

Hi Peter,

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;
}

Thanks,

Bart.