Re: [PATCH v3 3/3] srcu: Remove check from srcu_dereference_check()

From: Bart Van Assche

Date: Tue Nov 17 2026 - 13:20:40 EST


On 11/17/26 9:53 AM, Paul E. McKenney wrote:
> Would __builtin_constant_p() help here?
>
> If we don't have a build-time constant, don't check.
>
> If we do have a build-time constant, check only if that constant has
> the value zero, that is, there is no update-side protection.

Hi Paul,

Yes, that helps. I had missed this option. Something like the
following does what you describe:

#define srcu_dereference_check(p, ssp, c) \
({ \
if (__builtin_constant_p(c) && !(c)) \
__srcu_read_lock_must_hold(ssp); \
__acquire_shared_ctx_lock(RCU); \
...

This also fixes the runtime problem I mentioned: the argument of
__builtin_constant_p() is never evaluated, and '!(c)' is only
evaluated if 'c' is a constant.

I tested this with clang -Wthread-safety at -O0 and -O2:

c == 0 -> checked (warns without
the SRCU read lock)
c == 1 -> not checked
c == lockdep_is_held(&m) -> not checked
c == ({ (void)(&m); 1; }) -> not checked
(lockdep_is_held() with CONFIG_LOCKDEP=n)

There is one limitation. If 'c' is a plain variable, function
argument or structure member, e.g. srcu_dereference_check(p, ssp,
foo->flag), Clang does not resolve __builtin_constant_p() in the
front end. It leaves that to the optimizer, which may still find a
constant later. The context analysis then treats the call to
__srcu_read_lock_must_hold() as reachable and reports a false
positive. Clang does resolve __builtin_constant_p() to 0 when 'c'
contains a function call, and that covers lockdep_is_held(),
srcu_read_lock_held() and refcount_read(). In the current tree,
every srcu_dereference_check() caller passes either a constant or
an expression built from such calls, so this limitation doesn't
affect any existing caller.

So in v4 I plan to:
- call __srcu_read_lock_must_hold() from srcu_dereference_check()
only if 'c' is the constant 0, as shown above;
- keep srcu_dereference() defined as
srcu_dereference_check((p), (ssp), 0), which now gets the check
automatically;
- keep the explicit __srcu_read_lock_must_hold() call in
srcu_dereference_notrace(), because it passes 1 for 'c';
- update the comment above __srcu_read_lock_must_hold() and the
patch description to match.

Does that sound good to you?

Thanks,

Bart.