Skip to contentSkip to conversation

locking/local_lock: Don't evaluate the per-CPU lock pointer if unused

PATCH In review Ard Biesheuvel 3 participants 6 messages Nov 22 – Nov 23 Locking primitives

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 locking/local_lock: Don't evaluate the per-CPU lock pointer if unused

From: Ard Biesheuvel <[email protected]>

When lock debugging is disabled, local_lock_acquire() and friends are empty, and so the per-CPU lock pointer that is passed to them, which is usually computed using this_cpu_ptr(), is not used at all.

However, on x86, when the compiler does not support named address spaces (i.e., Clang), this_cpu_ptr() is based on inline asm with a memory operand, and Clang does not discard such inline asm even if its result is unused. So the computation of the per-CPU address of the lock is emitted regardless, e.g., on every local_lock_nested_bh() in process_backlog() and on every local_lock() in the folio batching code.

This was addressed before by commit

9983a9d577db ("locking/local_lock: Make the empty local_lock_*() function a macro.")

but that change was reverted by commit

2d2f8f083ef2 ("Revert "locking/local_lock: Make the empty local_lock_*() function a macro."")

once commit

1c1e7e3c23dd ("x86/percpu: Remove volatile from arch_raw_cpu_ptr().")

had dropped the volatile qualifier from the inline asm, on the basis that the compiler no longer emits the unused per-CPU reference in that case. This is true for GCC, but not for Clang.

So implement the !CONFIG_DEBUG_LOCK_ALLOC versions of these helpers as macros that only reference their argument in dead code, so that it is type checked but never evaluated. Referencing it only in an unevaluated context instead, as the typecheck() in the original macros did, makes Clang complain about per-CPU locks that are only used via these helpers (-Wunneeded-internal-declaration), which is what commit

a4812d47deff ("mm/page_alloc: mark pagesets as __maybe_unused")

had to work around at the time.

Also, only evaluate the lock pointer in __local_lock_acquire() and __local_lock_release() when it is actually needed, i.e., for local_trylock_t.

Cc Sebastian Andrzej Siewior <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Will Deacon <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Waiman Long <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Nick Desaulniers <[email protected]>
Cc Bill Wendling <[email protected]>
Cc Justin Stitt <[email protected]>
Fixes 2d2f8f083ef2 ("Revert "locking/local_lock: Make the empty local_lock_*() function a macro."")
---
 include/linux/local_lock_internal.h | 47 +++++++++++++-------
 1 file changed, 30 insertions(+), 17 deletions(-)
include/linux/local_lock_internal.h +30 -17
index 234be7f12c15..7c3191438c90 100644
@@ -69,10 +69,21 @@ static inline void local_lock_debug_init(local_lock_t *l)
 #else /* CONFIG_DEBUG_LOCK_ALLOC */
 # define LOCAL_LOCK_DEBUG_INIT(lockname)
 # define LOCAL_TRYLOCK_DEBUG_INIT(lockname)
-static inline void local_lock_acquire(local_lock_t *l) { }
-static inline void local_trylock_acquire(local_lock_t *l) { }
-static inline void local_lock_release(local_lock_t *l) { }
 static inline void local_lock_debug_init(local_lock_t *l) { }
+
+/*
+ * The argument passed to these is usually a this_cpu_ptr() expression, which
+ * is implemented using inline asm when the compiler lacks support for named
+ * address spaces (e.g., Clang). Clang may fail to discard such inline asm
+ * even if its result is never used, so only reference the argument in dead
+ * code, which type checks it without evaluating it. (Referencing it only in an
+ * unevaluated context such as sizeof() would make Clang complain about per-CPU
+ * locks that are only used via these helpers being unneeded.)
+ */
+static inline void __local_lock_typecheck(local_lock_t *l) { }
+# define local_lock_acquire(l)		({ if (0) __local_lock_typecheck(l); })
+# define local_trylock_acquire(l)	({ if (0) __local_lock_typecheck(l); })
+# define local_lock_release(l)		({ if (0) __local_lock_typecheck(l); })
 #endif /* !CONFIG_DEBUG_LOCK_ALLOC */
 
 #define INIT_LOCAL_LOCK(lockname)	{ LOCAL_LOCK_DEBUG_INIT(lockname) }
@@ -105,20 +116,23 @@ do {								\
 	local_lock_debug_init(lock);				\
 } while (0)
 
+/*
+ * Only evaluate @lock if it is actually used, i.e., for local_trylock_t, or
+ * when lock debugging is enabled (see local_lock_acquire() above).
+ */
 #define __local_lock_acquire(lock)					\
 	do {								\
-		local_trylock_t *__tl;					\
-		local_lock_t *__l;					\
-									\
-		__l = (local_lock_t *)(lock);				\
-		__tl = (local_trylock_t *)__l;				\
 		_Generic((lock),					\
 			local_trylock_t *: ({				\
+				local_trylock_t *__tl = (local_trylock_t *)(lock); \
+									\
 				lockdep_assert(__tl->acquired == 0);	\
 				WRITE_ONCE(__tl->acquired, 1);		\
+				local_lock_acquire((local_lock_t *)__tl); \
 			}),						\
-			local_lock_t *: (void)0);			\
-		local_lock_acquire(__l);				\
+			local_lock_t *: ({				\
+				local_lock_acquire((local_lock_t *)(lock)); \
+			}));						\
 	} while (0)
 
 #define __local_lock(lock)					\
@@ -181,18 +195,17 @@ do {								\
 
 #define __local_lock_release(lock)					\
 	do {								\
-		local_trylock_t *__tl;					\
-		local_lock_t *__l;					\
-									\
-		__l = (local_lock_t *)(lock);				\
-		__tl = (local_trylock_t *)__l;				\
-		local_lock_release(__l);				\
 		_Generic((lock),					\
 			local_trylock_t *: ({				\
+				local_trylock_t *__tl = (local_trylock_t *)(lock); \
+									\
+				local_lock_release((local_lock_t *)__tl); \
 				lockdep_assert(__tl->acquired == 1);	\
 				WRITE_ONCE(__tl->acquired, 0);		\
 			}),						\
-			local_lock_t *: (void)0);			\
+			local_lock_t *: ({				\
+				local_lock_release((local_lock_t *)(lock)); \
+			}));						\
 	} while (0)
 
 #define __local_unlock(lock)					\
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#1 lore raw
Quoted 9 lines · Ard Biesheuvel

From: Ard Biesheuvel <[email protected]>

When lock debugging is disabled, local_lock_acquire() and friends are empty, and so the per-CPU lock pointer that is passed to them, which is usually computed using this_cpu_ptr(), is not used at all.

However, on x86, when the compiler does not support named address spaces (i.e., Clang), this_cpu_ptr() is based on inline asm with a memory

I had to look this one up ("named address spaces").

https://gcc.gnu.org/onlinedocs/gcc/Named-Address-Spaces.html#x86-Named-Address-Spaces

So __seg_fs / __seg_gs ?

CC_HAS_NAMED_AS : arch/x86/Kconfig#2331

Weird, clang _does_ seem to support these, since clang-11 (clang-17 is the current minimum supported default).
https://godbolt.org/z/cfhj8r69E

commit 47ff30cc1be7 ("x86/percpu: Enable named address spaces for all capable GCC versions")
added a

depends on CC_IS_GCC

What happens if you turn that off?

Ah, a week after that commit was authored, the same author filed
https://github.com/llvm/llvm-project/issues/93449

(currently assigned to Bill; Bill, can you PTAL?)

They also filed
https://github.com/llvm/llvm-project/issues/93449

https://github.com/llvm/llvm-project/issues/187893 looks like possible a dup of one of the above. Bill, can you please take a look at those 3?

Quoted 4 lines

operand, and Clang does not discard such inline asm even if its result is unused. So the computation of the per-CPU address of the lock is emitted regardless, e.g., on every local_lock_nested_bh() in process_backlog() and on every local_lock() in the folio batching code.

I'm more so curious how you even noticed this problem? Was there a thread? Were you looking at some assembler and wondering what was going on here? Or was there another thread about this?

Very detailed commit message, but you kind of bury the lede here on what the actual problem this patch is fixing *is*.

Quoted 87 lines

This was addressed before by commit

9983a9d577db ("locking/local_lock: Make the empty local_lock_*() function a macro.")

but that change was reverted by commit

2d2f8f083ef2 ("Revert "locking/local_lock: Make the empty local_lock_*() function a macro."")

once commit

1c1e7e3c23dd ("x86/percpu: Remove volatile from arch_raw_cpu_ptr().")

had dropped the volatile qualifier from the inline asm, on the basis that the compiler no longer emits the unused per-CPU reference in that case. This is true for GCC, but not for Clang.

So implement the !CONFIG_DEBUG_LOCK_ALLOC versions of these helpers as macros that only reference their argument in dead code, so that it is type checked but never evaluated. Referencing it only in an unevaluated context instead, as the typecheck() in the original macros did, makes Clang complain about per-CPU locks that are only used via these helpers (-Wunneeded-internal-declaration), which is what commit

a4812d47deff ("mm/page_alloc: mark pagesets as __maybe_unused")

had to work around at the time.

Also, only evaluate the lock pointer in __local_lock_acquire() and __local_lock_release() when it is actually needed, i.e., for local_trylock_t.

Cc Sebastian Andrzej Siewior <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Will Deacon <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Waiman Long <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Nick Desaulniers <[email protected]>
Cc Bill Wendling <[email protected]>
Cc Justin Stitt <[email protected]>
Fixes 2d2f8f083ef2 ("Revert "locking/local_lock: Make the empty local_lock_*() function a macro."")
---
 include/linux/local_lock_internal.h | 47 +++++++++++++-------
 1 file changed, 30 insertions(+), 17 deletions(-)
include/linux/local_lock_internal.h +18 -3
index 234be7f12c15..7c3191438c90 100644
@@ -69,10 +69,21 @@ static inline void local_lock_debug_init(local_lock_t *l)
 #else /* CONFIG_DEBUG_LOCK_ALLOC */
 # define LOCAL_LOCK_DEBUG_INIT(lockname)
 # define LOCAL_TRYLOCK_DEBUG_INIT(lockname)
-static inline void local_lock_acquire(local_lock_t *l) { }
-static inline void local_trylock_acquire(local_lock_t *l) { }
-static inline void local_lock_release(local_lock_t *l) { }
 static inline void local_lock_debug_init(local_lock_t *l) { }
+
+/*
+ * The argument passed to these is usually a this_cpu_ptr() expression, which
+ * is implemented using inline asm when the compiler lacks support for named
+ * address spaces (e.g., Clang). Clang may fail to discard such inline asm
+ * even if its result is never used, so only reference the argument in dead
+ * code, which type checks it without evaluating it. (Referencing it only in an
+ * unevaluated context such as sizeof() would make Clang complain about per-CPU
+ * locks that are only used via these helpers being unneeded.)
+ */
+static inline void __local_lock_typecheck(local_lock_t *l) { }
+# define local_lock_acquire(l)         ({ if (0) __local_lock_typecheck(l); })
+# define local_trylock_acquire(l)      ({ if (0) __local_lock_typecheck(l); })
+# define local_lock_release(l)         ({ if (0) __local_lock_typecheck(l); })
 #endif /* !CONFIG_DEBUG_LOCK_ALLOC */
 
 #define INIT_LOCAL_LOCK(lockname)      { LOCAL_LOCK_DEBUG_INIT(lockname) }
@@ -105,20 +116,23 @@ do {                                                              \
        local_lock_debug_init(lock);                            \
 } while (0)
 
+/*
+ * Only evaluate @lock if it is actually used, i.e., for local_trylock_t, or
+ * when lock debugging is enabled (see local_lock_acquire() above).
+ */
 #define __local_lock_acquire(lock)                                     \

include/linux/local_lock_internal.h do { \ · line 128

Quoted 10 lines
include/linux/local_lock_internal.h +2 -5
        do {                                                            \
-               local_trylock_t *__tl;                                  \
-               local_lock_t *__l;                                      \
-                                                                       \
-               __l = (local_lock_t *)(lock);                           \
-               __tl = (local_trylock_t *)__l;                          \
                _Generic((lock),                                        \
                        local_trylock_t *: ({                           \
+                               local_trylock_t *__tl = (local_trylock_t *)(lock); \
+                                                                       \

Why do we need the temporary?

include/linux/local_lock_internal.h do { \ · line 134

Quoted 8 lines
include/linux/local_lock_internal.h +3 -2
                                lockdep_assert(__tl->acquired == 0);    \
                                WRITE_ONCE(__tl->acquired, 1);          \
+                               local_lock_acquire((local_lock_t *)__tl); \
                        }),                                             \
-                       local_lock_t *: (void)0);                       \
-               local_lock_acquire(__l);                                \
+                       local_lock_t *: ({                              \
+                               local_lock_acquire((local_lock_t *)(lock)); \

Is this cast necessary?

Quoted 32 lines
include/linux/local_lock_internal.h +7 -8
+                       }));                                            \
        } while (0)
 
 #define __local_lock(lock)                                     \
@@ -181,18 +195,17 @@ do {                                                              \
 
 #define __local_lock_release(lock)                                     \
        do {                                                            \
-               local_trylock_t *__tl;                                  \
-               local_lock_t *__l;                                      \
-                                                                       \
-               __l = (local_lock_t *)(lock);                           \
-               __tl = (local_trylock_t *)__l;                          \
-               local_lock_release(__l);                                \
                _Generic((lock),                                        \
                        local_trylock_t *: ({                           \
+                               local_trylock_t *__tl = (local_trylock_t *)(lock); \
+                                                                       \
+                               local_lock_release((local_lock_t *)__tl); \
                                lockdep_assert(__tl->acquired == 1);    \
                                WRITE_ONCE(__tl->acquired, 0);          \
                        }),                                             \
-                       local_lock_t *: (void)0);                       \
+                       local_lock_t *: ({                              \
+                               local_lock_release((local_lock_t *)(lock)); \
+                       }));                                            \
        } while (0)
 
 #define __local_unlock(lock)                                   \
--

2.56.1.750.gf70dc682cf-goog

Signature · 2 lines
Thanks,
~Nick Desaulniers
#2 lore raw
Quoted 4 lines · Nick Desaulniers

Ah, a week after that commit was authored, the same author filed
https://github.com/llvm/llvm-project/issues/93449

Quoted 8 lines

(currently assigned to Bill; Bill, can you PTAL?)

They also filed
https://github.com/llvm/llvm-project/issues/93449

https://github.com/llvm/llvm-project/issues/187893 looks like possible a dup of one of the above. Bill, can you please take a look at those 3?

2! 2 bugs. I was up until 2am with a screaming 2yo who has an ear infection. I think I'm seeing double...

Signature · 2 lines
Thanks,
~Nick Desaulniers
#3 lore raw
In reply to Nick Desaulniers
Quoted 43 lines · Nick Desaulniers
Quoted 9 lines · Ard Biesheuvel

From: Ard Biesheuvel <[email protected]>

When lock debugging is disabled, local_lock_acquire() and friends are empty, and so the per-CPU lock pointer that is passed to them, which is usually computed using this_cpu_ptr(), is not used at all.

However, on x86, when the compiler does not support named address spaces (i.e., Clang), this_cpu_ptr() is based on inline asm with a memory

I had to look this one up ("named address spaces").

https://gcc.gnu.org/onlinedocs/gcc/Named-Address-Spaces.html#x86-Named-Address-Spaces

So __seg_fs / __seg_gs ?

CC_HAS_NAMED_AS : arch/x86/Kconfig#2331

Weird, clang _does_ seem to support these, since clang-11 (clang-17 is the current minimum supported default).
https://godbolt.org/z/cfhj8r69E

commit 47ff30cc1be7 ("x86/percpu: Enable named address spaces for all capable GCC versions")
added a

depends on CC_IS_GCC

What happens if you turn that off?

Ah, a week after that commit was authored, the same author filed
https://github.com/llvm/llvm-project/issues/93449

(currently assigned to Bill; Bill, can you PTAL?)

They also filed
https://github.com/llvm/llvm-project/issues/93449

https://github.com/llvm/llvm-project/issues/187893 looks like possible a dup of one of the above. Bill, can you please take a look at those 3?

Quoted 9 lines
Quoted 4 lines

operand, and Clang does not discard such inline asm even if its result is unused. So the computation of the per-CPU address of the lock is emitted regardless, e.g., on every local_lock_nested_bh() in process_backlog() and on every local_lock() in the folio batching code.

I'm more so curious how you even noticed this problem? Was there a thread? Were you looking at some assembler and wondering what was going on here? Or was there another thread about this?

No it manifested in local testing of my fgkaslr implementation.

I'm doing some very detailed profiling to ensure it does not regress performance.

Quoted 3 lines

Very detailed commit message, but you kind of bury the lede here on what the actual problem this patch is fixing *is*.

Apologies. I'll trim it down,

The TL;DR is that non-volatile asm() statements with memory input operands are not elided by Clang if their output is never used.

#4 lore raw
Quoted 11 lines · Ard Biesheuvel
Quoted 3 lines · Nick Desaulniers

Very detailed commit message, but you kind of bury the lede here on what the actual problem this patch is fixing *is*.

Apologies. I'll trim it down,

The TL;DR is that non-volatile asm() statements with memory input operands are not elided by Clang if their output is never used.

That's not a bug; both Clang and GCC behave that way.
https://godbolt.org/z/sEhec4oae

(perhaps there is a clang bug somewhere, just trying to suss out if there's something we need to fix here; forgive me for being pedantic here)

Signature · 2 lines
Thanks,
~Nick Desaulniers
#5 lore raw
Quoted 8 lines · Nick Desaulniers
Quoted 7 lines · Ard Biesheuvel
Quoted 3 lines · Nick Desaulniers

Very detailed commit message, but you kind of bury the lede here on what the actual problem this patch is fixing *is*.

Quoted 8 lines
Quoted 4 lines

Apologies. I'll trim it down,

The TL;DR is that non-volatile asm() statements with memory input operands are not elided by Clang if their output is never used.

That's not a bug; both Clang and GCC behave that way.
https://godbolt.org/z/sEhec4oae

Try changing that to

asm("# hello world %0": "=r"(x) :"m"(x));

(and don't touch x afterwards)