Compiler-Based Context- and Locking-Analysis
Subsystems (33)
Marco Elver
maintainerv5 cover Compiler-Based Context- and Locking-Analysis
Context Analysis is a language extension, which enables statically checking that required contexts are active (or inactive) by acquiring and releasing user-definable "context locks". An obvious application is lock-safety checking for the kernel's various synchronization primitives (each of which represents a "context lock"), and checking that locking rules are not violated.
The feature requires Clang 22 (unreleased) or later. Clang originally called the feature "Thread Safety Analysis" [1]. This was later changed and the feature became more flexible, gaining the ability to define custom "capabilities". Its foundations can be found in "Capability Systems" [2], used to specify the permissibility of operations to depend on some "capability" being held (or not held).
Because the feature is not just able to express "capabilities" related to synchronization primitives, and "capability" is already overloaded in the kernel, the naming chosen for the kernel departs from Clang's "Thread Safety" and "capability" nomenclature; we refer to the feature as "Context Analysis" to avoid confusion. The internal implementation still makes references to Clang's terminology in a few places, such as -Wthread-safety being the warning option that also still appears in diagnostic messages.
Additional details can be found in the added kernel-doc documentation. An LWN article covered v2 of the series: https://lwn.net/Articles/1012990/
[1] https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
[2] https://www.cs.cornell.edu/talc/papers/capabilities.pdf
=== Design ===
Prior art exists in the form of Sparse's Context Tracking. Locking annotations on functions already exist sparsely, so the concept of analyzing locking rules is not foreign to the kernel's codebase.
However, Clang's analysis is more complete vs. Sparse's, with the typical trade-offs in static analysis: improved completeness is sacrificed for more possible false positives or additional annotations required by the programmer. Numerous options exist to disable or opt out certain code from analysis.
This series initially aimed to retain compatibility with Sparse, which can provide tree-wide analysis of a subset of the context analysis introduced, but it was later decided to drop Sparse compatibility. For the most part, the new (and old) keywords used for annotations remain the same, and many of the pre-existing annotations remain valid.
One big question is how to enable this feature, given we end up with a new dialect of C; two approaches have been considered:
A. Tree-wide all-or-nothing approach. This approach requires tree-wide
changes, adding annotations or selective opt-outs. Making more primitives context-analysis aware increases churn where maintainers are unfamiliar with the feature and the analysis is unable to deal with complex code patterns as-is.
Because we can't change the programming language (even if from one C dialect to another) of the kernel overnight, a different approach might cause less friction.
B. A selective, incremental, and much less intrusive approach.
Maintainers of subsystems opt in their modules or directories into context analysis (via Makefile):
CONTEXT_ANALYSIS_foo.o := y # foo.o only
CONTEXT_ANALYSIS := y # all TUs
Most (eventually all) synchronization primitives, and more context locks including ones that track "irq disabled", "preemption" disabled, etc. could be supported.
The approach taken by this series is B. This ensures that only subsystems where maintainers are willing to deal with any warnings are opted-in. Introducing the feature can be done incrementally, without large tree-wide changes and adding numerous opt-outs and annotations to the majority of code.
Note: Bart Van Assche concurrently worked on enabling -Wthread-safety:
https://lore.kernel.org/all/[email protected]/
Bart's work has shown what it might take to go with approach A (tree-wide, restricted to 'mutex' usage). This has shown that the analysis finds real issues when applied to enough subsystems! We hope this serves as motivation to eventually enable the analysis in as many subsystems as possible, particularly subsystems that are not as easily tested by CI systems and test robots.
=== Initial Uses ===
With this initial series, the following synchronization primitives are
supported: raw_spinlock_t, spinlock_t, rwlock_t, mutex, seqlock_t, bit_spinlock, RCU, SRCU (srcu_struct), rw_semaphore, local_lock_t, ww_mutex.
To demonstrate use of the feature on real kernel code, the series also enables context analysis for the following subsystems:
* kernel/kcov
* kernel/kcsan
* kernel/sched/
* lib/rhashtable
* lib/stackdepot
* mm/kfence
* security/tomoyo
* crypto/
The initial benefits are static detection of violations of locking rules. As more context locks are supported, we would see more static checking beyond what regular C can provide, all while remaining easy (and quick) to use via the Clang compiler.
Note: The kernel already provides dynamic analysis tools Lockdep and KCSAN for lock-safety checking and data-race detection respectively. Unlike those, Clang's context analysis is a compile-time static analysis with no runtime impact. The static analysis complements existing dynamic analysis tools, as it may catch some issues before even getting into a running kernel, but is *not* a replacement for whole-kernel testing with the dynamic analysis tools enabled!
=== Appendix ===
A Clang version that supports -Wthread-safety-pointer and the new alias-analysis of context lock pointers is required (from this version onwards):
https://github.com/llvm/llvm-project/commit/7ccb5c08f0685d4787f12c3224a72f0650c5865e
The minimum required release version will be Clang 22.
This series is also available at this Git tree:
https://git.kernel.org/pub/scm/linux/kernel/git/melver/linux.git/log/?h=ctx-analysis/dev
The feature itself is usable when all patches up to the "MAINTAINERS" patch are applied; the subsequent "enablement" patches are optional and could be applied by the respective maintainers to their own tree after the context analysis infrastructure is available.
=== Changelog ===
v5:
- Rename "context guard" -> "context lock".
- Rework cleanup.h support to properly release at scope guard end.
- Use new cleanup.h helpers to properly support scoped lock guards.
- Support new scoped_seqlock_read().
- Also remove include/linux/lockref.h's deprecated use of __cond_lock().
- Fix invalid __releases/__acquires in um skas/mm_id.h header (transitively included through mm_types.h which is included by subsystems that may want to enable context analysis).
- Better document Clang's assert_capability attribute.
- Rebase on v6.19-rc1.
v4: https://lore.kernel.org/all/[email protected]/
- Rename capability -> context analysis, per Linus's suggestion:
https://lore.kernel.org/all/CAHk-=wgd-Wcp0GpYaQnU7S9ci+FvFmaNw1gm75mzf0ZWdNLxvw@mail.gmail.com/
- Minor fixes.
v3: https://lore.kernel.org/all/[email protected]/
- Bump min. Clang version to 22+ (unreleased), which now supports:
* re-entrancy via __attribute__((reentrant_capability));
* basic form of capability alias analysis - which is the biggest improvement since v2.
This was the result of conclusions from this discussion:
https://lore.kernel.org/all/CANpmjNPquO=W1JAh1FNQb8pMQjgeZAKCPQUAd7qUg=5pjJ6x=Q@mail.gmail.com/
- Rename __asserts_cap/__assert_cap to __assumes_cap/__assume_cap.
- Switch to DECLARE_LOCK_GUARD_1_ATTRS().
- Add __acquire_ret and __acquire_shared_ret helper macros - can be used to define function-like macros that return objects which contains a held capabilities. Works now because of capability alias analysis.
- Add capability_unsafe_alias() helper, where the analysis rightfully points out we're doing strange things with aliases but we don't care.
- Support multi-argument attributes.
- Enable for kernel/sched/{core,fair}.c, kernel/kcsan.
- Drop drivers/tty changes (revisit later).
v2: https://lore.kernel.org/all/[email protected]/
- Remove Sparse context tracking support - after the introduction of Clang support, so that backports can skip removal of Sparse support.
- Remove __cond_lock() function-like helper.
- ww_mutex support.
- -Wthread-safety-addressof was reworked and committed in upstream Clang as -Wthread-safety-pointer.
- Make __cond_acquires() and __cond_acquires_shared() take abstract value, since compiler only cares about zero and non-zero.
- Rename __var_guarded_by to simply __guarded_by. Initially the idea was to be explicit about if the variable itself or the pointed-to data is guarded, but in the long-term, making this shorter might be better.
- Likewise rename __ref_guarded_by to __pt_guarded_by.
- Introduce common header warning suppressions - this is a better solution than guarding header inclusions with disable_ + enable_capability_analysis(). Header suppressions are disabled when selecting CONFIG_WARN_CAPABILITY_ANALYSIS_ALL=y. This bumps the minimum Clang version required to 20+.
- Make the data_race() macro imply disabled capability analysis. Writing capability_unsafe(data_race(..)) is unnecessarily verbose and data_race() on its own already indicates something subtly unsafe is happening. This change was made after analysis of a finding in security/tomoyo.
- Enable analysis in the following subsystems as additional examples of larger subsystem. Where it was obvious, the __guarded_by attribute was added to lock-guarded variables to improve coverage.
* drivers/tty
* security/tomoyo
* crypto/
RFC v1: https://lore.kernel.org/lkml/[email protected]
Marco Elver (36):
compiler_types: Move lock checking attributes to
compiler-context-analysis.h
compiler-context-analysis: Add infrastructure for Context Analysis
with Clang
compiler-context-analysis: Add test stub
Documentation: Add documentation for Compiler-Based Context Analysis
checkpatch: Warn about context_unsafe() without comment
cleanup: Basic compatibility with context analysis
lockdep: Annotate lockdep assertions for context analysis locking/rwlock, spinlock: Support Clang's context analysis
compiler-context-analysis: Change __cond_acquires to take return value locking/mutex: Support Clang's context analysis locking/seqlock: Support Clang's context analysis
bit_spinlock: Include missing <asm/processor.h>
bit_spinlock: Support Clang's context analysis
rcu: Support Clang's context analysis
srcu: Support Clang's context analysis
kref: Add context-analysis annotations
locking/rwsem: Support Clang's context analysis locking/local_lock: Include missing headers locking/local_lock: Support Clang's context analysis locking/ww_mutex: Support Clang's context analysis
debugfs: Make debugfs_cancellation a context lock struct
um: Fix incorrect __acquires/__releases annotations
compiler-context-analysis: Remove Sparse support
compiler-context-analysis: Remove __cond_lock() function-like helper
compiler-context-analysis: Introduce header suppressions
compiler: Let data_race() imply disabled context analysis
MAINTAINERS: Add entry for Context Analysis
kfence: Enable context analysis
kcov: Enable context analysis
kcsan: Enable context analysis
stackdepot: Enable context analysis
rhashtable: Enable context analysis
printk: Move locking annotation to printk.c security/tomoyo: Enable context analysis
crypto: Enable context analysis
sched: Enable context analysis for core.c and fair.c
Documentation/dev-tools/context-analysis.rst | 145 +++++ Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/sparse.rst | 19 - Documentation/mm/process_addrs.rst | 6 +- MAINTAINERS | 11 + Makefile | 1 + arch/um/include/shared/skas/mm_id.h | 5 +- arch/um/kernel/skas/mmu.c | 13 +- crypto/Makefile | 2 + crypto/acompress.c | 6 +- crypto/algapi.c | 2 + crypto/api.c | 1 + crypto/crypto_engine.c | 2 +- crypto/drbg.c | 5 + crypto/internal.h | 2 +- crypto/proc.c | 3 + crypto/scompress.c | 24 +- .../net/wireless/intel/iwlwifi/iwl-trans.c | 4 +- .../net/wireless/intel/iwlwifi/iwl-trans.h | 6 +- .../intel/iwlwifi/pcie/gen1_2/internal.h | 5 +- .../intel/iwlwifi/pcie/gen1_2/trans.c | 4 +- fs/dlm/lock.c | 2 +- include/crypto/internal/acompress.h | 7 +- include/crypto/internal/engine.h | 2 +- include/linux/bit_spinlock.h | 24 +- include/linux/cleanup.h | 50 ++ include/linux/compiler-context-analysis.h | 441 +++++++++++++ include/linux/compiler.h | 2 + include/linux/compiler_types.h | 18 +- include/linux/console.h | 4 +- include/linux/debugfs.h | 12 +- include/linux/kref.h | 2 + include/linux/list_bl.h | 2 + include/linux/local_lock.h | 51 +- include/linux/local_lock_internal.h | 73 ++- include/linux/lockdep.h | 12 +- include/linux/lockref.h | 4 +- include/linux/mm.h | 33 +- include/linux/mutex.h | 38 +- include/linux/mutex_types.h | 4 +- include/linux/rcupdate.h | 90 +-- include/linux/refcount.h | 6 +- include/linux/rhashtable.h | 16 +- include/linux/rwlock.h | 22 +- include/linux/rwlock_api_smp.h | 43 +- include/linux/rwlock_rt.h | 44 +- include/linux/rwlock_types.h | 10 +- include/linux/rwsem.h | 76 ++- include/linux/sched.h | 6 +- include/linux/sched/signal.h | 16 +- include/linux/sched/task.h | 6 +- include/linux/sched/wake_q.h | 3 + include/linux/seqlock.h | 38 +- include/linux/seqlock_types.h | 5 +- include/linux/spinlock.h | 112 +++- include/linux/spinlock_api_smp.h | 34 +- include/linux/spinlock_api_up.h | 112 +++- include/linux/spinlock_rt.h | 37 +- include/linux/spinlock_types.h | 10 +- include/linux/spinlock_types_raw.h | 5 +- include/linux/srcu.h | 73 ++- include/linux/srcutiny.h | 6 + include/linux/srcutree.h | 10 +- include/linux/ww_mutex.h | 22 +- kernel/Makefile | 2 + kernel/kcov.c | 36 +- kernel/kcsan/Makefile | 2 + kernel/kcsan/report.c | 11 +- kernel/printk/printk.c | 2 + kernel/sched/Makefile | 3 + kernel/sched/core.c | 89 ++- kernel/sched/fair.c | 7 +- kernel/sched/sched.h | 126 +++- kernel/signal.c | 4 +- kernel/time/posix-timers.c | 13 +- lib/Kconfig.debug | 44 ++ lib/Makefile | 6 + lib/dec_and_lock.c | 8 +- lib/lockref.c | 1 - lib/rhashtable.c | 5 +- lib/stackdepot.c | 20 +- lib/test_context-analysis.c | 604 ++++++++++++++++++ mm/kfence/Makefile | 2 + mm/kfence/core.c | 20 +- mm/kfence/kfence.h | 14 +- mm/kfence/report.c | 4 +- mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +- net/ipv4/tcp_sigpool.c | 2 +- scripts/Makefile.context-analysis | 11 + scripts/Makefile.lib | 10 + scripts/checkpatch.pl | 7 + scripts/context-analysis-suppression.txt | 33 + security/tomoyo/Makefile | 2 + security/tomoyo/common.c | 52 +- security/tomoyo/common.h | 77 +-- security/tomoyo/domain.c | 1 + security/tomoyo/environ.c | 1 + security/tomoyo/file.c | 5 + security/tomoyo/gc.c | 28 +- security/tomoyo/mount.c | 2 + security/tomoyo/network.c | 3 + tools/include/linux/compiler_types.h | 2 - 103 files changed, 2523 insertions(+), 609 deletions(-) create mode 100644 Documentation/dev-tools/context-analysis.rst create mode 100644 include/linux/compiler-context-analysis.h create mode 100644 lib/test_context-analysis.c create mode 100644 scripts/Makefile.context-analysis create mode 100644 scripts/context-analysis-suppression.txt
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Marco Elver
maintainerPATCH v5 1/36 compiler_types: Move lock checking attributes to compiler-context-analysis.h
The conditional definition of lock checking macros and attributes is about to become more complex. Factor them out into their own header for better readability, and to make it obvious which features are supported by which mode (currently only Sparse). This is the first step towards generalizing towards "context analysis".
No functional change intended.
---
v4:
* Rename capability -> context analysis.
--- include/linux/compiler-context-analysis.h | 32 +++++++++++++++++++++++ include/linux/compiler_types.h | 18 ++----------- 2 files changed, 34 insertions(+), 16 deletions(-) create mode 100644 include/linux/compiler-context-analysis.h
include/linux/compiler-context-analysis.h new file +32 -0
@@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Macros and attributes for compiler-based static context analysis. +*/ + +#ifndef _LINUX_COMPILER_CONTEXT_ANALYSIS_H +#define _LINUX_COMPILER_CONTEXT_ANALYSIS_H + +#ifdef __CHECKER__ + +/* Sparse context/lock checking support. */ +# define __must_hold (x) __attribute__((context(x,1,1))) +# define __acquires (x) __attribute__((context(x,0,1))) +# define __cond_acquires (x) __attribute__((context(x,0,-1))) +# define __releases (x) __attribute__((context(x,1,0))) +# define __acquire (x) __context__(x,1) +# define __release (x) __context__(x,-1) +# define __cond_lock (x, c) ((c) ? ({ __acquire(x); 1; }) : 0) + +#else /* !__CHECKER__ */ + +# define __must_hold (x) +# define __acquires (x) +# define __cond_acquires (x) +# define __releases (x) +# define __acquire (x) (void)0 +# define __release (x) (void)0 +# define __cond_lock (x, c) (c) + +#endif /* __CHECKER__ */ + +#endif /* _LINUX_COMPILER_CONTEXT_ANALYSIS_H */
include/linux/compiler_types.h +2 -16
@@ -41,6 +41,8 @@# define BTF_TYPE_TAG (value)/* nothing */ #endif +#include <linux/compiler-context-analysis.h> +/* sparse defines __CHECKER__; see Documentation/dev-tools/sparse.rst */ #ifdef __CHECKER__/* address spaces */
@@ -51,14 +53,6 @@# define __rcu __attribute__((noderef, address_space(__rcu)))static inline void __chk_user_ptr (const volatile void __user *ptr) { }static inline void __chk_io_ptr (const volatile void __iomem *ptr) { } -/* context/locking */ -# define __must_hold (x) __attribute__((context(x,1,1))) -# define __acquires (x) __attribute__((context(x,0,1))) -# define __cond_acquires (x) __attribute__((context(x,0,-1))) -# define __releases (x) __attribute__((context(x,1,0))) -# define __acquire (x) __context__(x,1) -# define __release (x) __context__(x,-1) -# define __cond_lock (x,c) ((c) ? ({ __acquire(x); 1; }) : 0)/* other */ # define __force __attribute__((force))# define __nocast __attribute__((nocast))
@@ -79,14 +73,6 @@ static inline void __chk_io_ptr(const volatile void __iomem *ptr) { }# define __chk_user_ptr (x) (void)0# define __chk_io_ptr (x) (void)0 -/* context/locking */ -# define __must_hold (x) -# define __acquires (x) -# define __cond_acquires (x) -# define __releases (x) -# define __acquire (x) (void)0 -# define __release (x) (void)0 -# define __cond_lock (x,c) (c)/* other */ # define __force# define __nocast
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] compiler_types: Move lock checking attributes to compiler-context-analysis.h
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: de15fecae44df8254fa597bad7eb3680a8b1c10c Gitweb: https://git.kernel.org/tip/de15fecae44df8254fa597bad7eb3680a8b1c10c Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:50 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:26 +01:00
compiler_types: Move lock checking attributes to compiler-context-analysis.h
The conditional definition of lock checking macros and attributes is about to become more complex. Factor them out into their own header for better readability, and to make it obvious which features are supported by which mode (currently only Sparse). This is the first step towards generalizing towards "context analysis".
No functional change intended.
--- include/linux/compiler-context-analysis.h | 32 ++++++++++++++++++++++- include/linux/compiler_types.h | 18 +----------- 2 files changed, 34 insertions(+), 16 deletions(-) create mode 100644 include/linux/compiler-context-analysis.h
include/linux/compiler-context-analysis.h new file +32 -0
@@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Macros and attributes for compiler-based static context analysis. +*/ + +#ifndef _LINUX_COMPILER_CONTEXT_ANALYSIS_H +#define _LINUX_COMPILER_CONTEXT_ANALYSIS_H + +#ifdef __CHECKER__ + +/* Sparse context/lock checking support. */ +# define __must_hold (x) __attribute__((context(x,1,1))) +# define __acquires (x) __attribute__((context(x,0,1))) +# define __cond_acquires (x) __attribute__((context(x,0,-1))) +# define __releases (x) __attribute__((context(x,1,0))) +# define __acquire (x) __context__(x,1) +# define __release (x) __context__(x,-1) +# define __cond_lock (x, c) ((c) ? ({ __acquire(x); 1; }) : 0) + +#else /* !__CHECKER__ */ + +# define __must_hold (x) +# define __acquires (x) +# define __cond_acquires (x) +# define __releases (x) +# define __acquire (x) (void)0 +# define __release (x) (void)0 +# define __cond_lock (x, c) (c) + +#endif /* __CHECKER__ */ + +#endif /* _LINUX_COMPILER_CONTEXT_ANALYSIS_H */
include/linux/compiler_types.h +2 -16
@@ -41,6 +41,8 @@# define BTF_TYPE_TAG (value)/* nothing */ #endif +#include <linux/compiler-context-analysis.h> +/* sparse defines __CHECKER__; see Documentation/dev-tools/sparse.rst */ #ifdef __CHECKER__/* address spaces */
@@ -51,14 +53,6 @@# define __rcu __attribute__((noderef, address_space(__rcu)))static inline void __chk_user_ptr (const volatile void __user *ptr) { }static inline void __chk_io_ptr (const volatile void __iomem *ptr) { } -/* context/locking */ -# define __must_hold (x) __attribute__((context(x,1,1))) -# define __acquires (x) __attribute__((context(x,0,1))) -# define __cond_acquires (x) __attribute__((context(x,0,-1))) -# define __releases (x) __attribute__((context(x,1,0))) -# define __acquire (x) __context__(x,1) -# define __release (x) __context__(x,-1) -# define __cond_lock (x,c) ((c) ? ({ __acquire(x); 1; }) : 0)/* other */ # define __force __attribute__((force))# define __nocast __attribute__((nocast))
@@ -79,14 +73,6 @@ static inline void __chk_io_ptr(const volatile void __iomem *ptr) { }# define __chk_user_ptr (x) (void)0# define __chk_io_ptr (x) (void)0 -/* context/locking */ -# define __must_hold (x) -# define __acquires (x) -# define __cond_acquires (x) -# define __releases (x) -# define __acquire (x) (void)0 -# define __release (x) (void)0 -# define __cond_lock (x,c) (c)/* other */ # define __force# define __nocast
Marco Elver
maintainerPATCH v5 2/36 compiler-context-analysis: Add infrastructure for Context Analysis with Clang
In reply to Marco ElverContext Analysis is a language extension, which enables statically checking that required contexts are active (or inactive), by acquiring and releasing user-definable "context locks". An obvious application is lock-safety checking for the kernel's various synchronization primitives (each of which represents a "context lock"), and checking that locking rules are not violated.
Clang originally called the feature "Thread Safety Analysis" [1]. This was later changed and the feature became more flexible, gaining the ability to define custom "capabilities". Its foundations can be found in "Capability Systems" [2], used to specify the permissibility of operations to depend on some "capability" being held (or not held).
Because the feature is not just able to express "capabilities" related to synchronization primitives, and "capability" is already overloaded in the kernel, the naming chosen for the kernel departs from Clang's "Thread Safety" and "capability" nomenclature; we refer to the feature as "Context Analysis" to avoid confusion. The internal implementation still makes references to Clang's terminology in a few places, such as -Wthread-safety being the warning option that also still appears in diagnostic messages.
[1] https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
[2] https://www.cs.cornell.edu/talc/papers/capabilities.pdf
See more details in the kernel-doc documentation added in this and subsequent changes.
Clang version 22+ is required.
---
v5:
* Rename "context guard" -> "context lock".
* Better document Clang's assert_capability attribute.
v4:
* Rename capability -> context analysis.
v3:
* Require Clang 22 or later (reentrant capabilities, basic alias analysis).
* Rename __assert_cap/__asserts_cap -> __assume_cap/__assumes_cap (suggested by Peter).
* Add __acquire_ret and __acquire_shared_ret helper macros - can be used to define function-like macros that return objects which contains a held capabilities. Works now because of capability alias analysis.
* Add capability_unsafe_alias() helper, where the analysis rightfully points out we're doing strange things with aliases but we don't care.
* Support multi-argument attributes.
v2:
* New -Wthread-safety feature rename to -Wthread-safety-pointer (was -Wthread-safety-addressof).
* Introduce __capability_unsafe() function attribute.
* Rename __var_guarded_by to simply __guarded_by. The initial idea was to be explicit if the variable or pointed-to data is guarded by, but having a shorter attribute name is likely better long-term.
* Rename __ref_guarded_by to __pt_guarded_by (pointed-to guarded by).
--- Makefile | 1 + include/linux/compiler-context-analysis.h | 464 +++++++++++++++++++++- lib/Kconfig.debug | 30 ++ scripts/Makefile.context-analysis | 7 + scripts/Makefile.lib | 10 + 5 files changed, 505 insertions(+), 7 deletions(-) create mode 100644 scripts/Makefile.context-analysis
Makefile +1 -0
@@ -1118,6 +1118,7 @@ include-$(CONFIG_RANDSTRUCT) += scripts/Makefile.randstruct include-$(CONFIG_KSTACK_ERASE) += scripts/Makefile.kstack_erase include-$(CONFIG_AUTOFDO_CLANG) += scripts/Makefile.autofdo include-$(CONFIG_PROPELLER_CLANG) += scripts/Makefile.propeller +include-$(CONFIG_WARN_CONTEXT_ANALYSIS) += scripts/Makefile.context-analysis include-$(CONFIG_GCC_PLUGINS) += scripts/Makefile.gcc-plugins include $(addprefix $(srctree)/, $(include-y))
include/linux/compiler-context-analysis.h +457 -7
484 lines not on this page · raw message
lib/Kconfig.debug +30 -0
@@ -621,6 +621,36 @@ config DEBUG_FORCE_WEAK_PER_CPU To ensure that generic code follows the above rules, this option forces all percpu variables to be defined as weak. +config WARN_CONTEXT_ANALYSIS + bool "Compiler context-analysis warnings" + depends on CC_IS_CLANG && CLANG_VERSION >= 220000 + # Branch profiling re-defines "if", which messes with the compiler's + # ability to analyze __cond_acquires(..), resulting in false positives. + depends on !TRACE_BRANCH_PROFILING + default y + help + Context Analysis is a language extension, which enables statically + checking that required contexts are active (or inactive) by acquiring + and releasing user-definable "context locks". + + Clang's name of the feature is "Thread Safety Analysis". Requires + Clang 22 or later. + + Produces warnings by default. Select CONFIG_WERROR if you wish to + turn these warnings into errors. + + For more details, see Documentation/dev-tools/context-analysis.rst. + +config WARN_CONTEXT_ANALYSIS_ALL + bool "Enable context analysis for all source files" + depends on WARN_CONTEXT_ANALYSIS + depends on EXPERT && !COMPILE_TEST + help + Enable tree-wide context analysis. This is likely to produce a + large number of false positives - enable at your own risk. + + If unsure, say N. + endmenu # "Compiler options" menu "Generic Kernel Debugging Instruments"
scripts/Makefile.context-analysis new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 + +context-analysis-cflags := -DWARN_CONTEXT_ANALYSIS \ + -fexperimental-late-parse-attributes -Wthread-safety \ + -Wthread-safety-pointer -Wthread-safety-beta + +export CFLAGS_CONTEXT_ANALYSIS := $(context-analysis-cflags)
scripts/Makefile.lib +10 -0
@@ -105,6 +105,16 @@ _c_flags += $(if $(patsubst n%,, \ -D__KCSAN_INSTRUMENT_BARRIERS__) endif +# +# Enable context analysis flags only where explicitly opted in. +# (depends on variables CONTEXT_ANALYSIS_obj.o, CONTEXT_ANALYSIS) +# +ifeq ($(CONFIG_WARN_CONTEXT_ANALYSIS),y) +_c_flags += $(if $(patsubst n%,, \ + $(CONTEXT_ANALYSIS_$(target-stem).o)$(CONTEXT_ANALYSIS)$(if $(is-kernel-object),$(CONFIG_WARN_CONTEXT_ANALYSIS_ALL))), \ + $(CFLAGS_CONTEXT_ANALYSIS)) +endif + # # Enable AutoFDO build flags except some files or directories we don't want to # enable (depends on variables AUTOFDO_PROFILE_obj.o and AUTOFDO_PROFILE).
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 02/36] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
include/linux/compiler-context-analysis.h line 14
Quoted 6 lines · Marco Elver
include/linux/compiler-context-analysis.h +6
-0+#if defined(WARN_CONTEXT_ANALYSIS ) + +/* +* These attributes define new context lock (Clang: capability) types. +* Internal only. +*/
How can macros be "internal only" that are defined in a header file that will be included by almost all kernel code? Please consider changing "internal only" into something that is more clear, e.g. "should only be used in the macro definitions in this header file".
Quoted 3 lines
+/*
+ * The below are used to annotate code being checked. Internal only.
+ */
Same comment here about "internal only".
Quoted 33 lines
include/linux/compiler-context-analysis.h +33
-0+/** +* context_lock_struct() - declare or define a context lock struct +* @name: struct name +* +* Helper to declare or define a struct type that is also a context lock. +* +* .. code-block:: c +* +* context_lock_struct(my_handle) { +* int foo; +* long bar; +* }; +* +* struct some_state { +* ... +* }; +* // ... declared elsewhere ... +* context_lock_struct(some_state); +* +* Note: The implementation defines several helper functions that can acquire +* and release the context lock. +*/ +# define context_lock_struct (name, ...) \ + struct __ctx_lock_type(name) __VA_ARGS__ name; \ + static __always_inline void __acquire_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis __acquires_ctx_lock(var) { } \ + static __always_inline void __acquire_shared_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis __acquires_shared_ctx_lock(var) { } \ + static __always_inline bool __try_acquire_ctx_lock(const struct name *var, bool ret) \ + __attribute__((overloadable)) __no_context_analysis __try_acquires_ctx_lock(1, var) \ + { return ret; } \ + static __always_inline bool __try_acquire_shared_ctx_lock(const struct name *var, bool ret) \ + __attribute__((overloadable)) __no_context_analysis __try_acquires_shared_ctx_lock(1, var) \
include/linux/compiler-context-analysis.h line 123
Quoted 10 lines
include/linux/compiler-context-analysis.h +10
-0+ {return ret; } \ + static __always_inline void __release_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis__releases_ctx_lock (var) { } \ + static __always_inline void __release_shared_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis__releases_shared_ctx_lock (var) { } \ + static __always_inline void __assume_ctx_lock(const struct name *var) \ + __attribute__((overloadable))__assumes_ctx_lock (var) { } \ + static __always_inline void __assume_shared_ctx_lock(const struct name *var) \ + __attribute__((overloadable))__assumes_shared_ctx_lock (var) { } \ +struct name
I'm concerned that the context_lock_struct() macro will make code harder to read. Anyone who encounters the context_lock_struct() macro will have to look up its definition to learn what it does. I propose to split this macro into two macros:
* One macro that expands into "__ctx_lock_type(name)".
* A second macro that expands into the rest of the above macro.
In other words, instead of having to write context_lock_struct(struct_name, { ... }); developers will have to write
struct context_lock_type struct_name {
...;
};context_struct_helper_functions(struct_name);
My opinion is that the alternative that I'm proposing is easier to read. Additionally, it doesn't break existing tools that support jumping from the name of a struct to its definition, e.g. ctags and etags.
lib/Kconfig.debug config DEBUG_FORCE_WEAK_PER_CPU · line 652
Quoted 9 lines
lib/Kconfig.debug +9
-0+config WARN_CONTEXT_ANALYSIS_ALL + bool "Enable context analysis for all source files" + depends on WARN_CONTEXT_ANALYSIS + depends on EXPERT && !COMPILE_TEST + help + Enable tree-wide context analysis. This is likely to produce a + large number of false positives - enable at your own risk. + + If unsure, say N.
Why !COMPILE_TEST?
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 02/36] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
Quoted 12 lines · Bart Van Assche' via kasan-dev
include/linux/compiler-context-analysis.h line 14
Quoted 6 lines · Marco Elver
include/linux/compiler-context-analysis.h +6
-0+#if defined(WARN_CONTEXT_ANALYSIS ) + +/* +* These attributes define new context lock (Clang: capability) types. +* Internal only. +*/ How can macros be "internal only" that are defined in a header file that will be included by almost all kernel code? Please consider changing "internal only" into something that is more clear, e.g. "should only be used in the macro definitions in this header file".
Sure, comment could be improved.
Let's say they aren't for general use by normal code that just enables the analysis for checking; for that we define the shorter (retaining previous names already in use) ones below. But some of these attributes can and are used by implementing support for some of the synchronization primitives.
Quoted 5 lines
Quoted 3 lines
+/*
+ * The below are used to annotate code being checked. Internal only.
+ */Same comment here about "internal only".
Sure, can be clarified.
Quoted 51 lines
Quoted 33 lines
include/linux/compiler-context-analysis.h +33
-0+/** +* context_lock_struct() - declare or define a context lock struct +* @name: struct name +* +* Helper to declare or define a struct type that is also a context lock. +* +* .. code-block:: c +* +* context_lock_struct(my_handle) { +* int foo; +* long bar; +* }; +* +* struct some_state { +* ... +* }; +* // ... declared elsewhere ... +* context_lock_struct(some_state); +* +* Note: The implementation defines several helper functions that can acquire +* and release the context lock. +*/ +# define context_lock_struct (name, ...) \ + struct __ctx_lock_type(name) __VA_ARGS__ name; \ + static __always_inline void __acquire_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis __acquires_ctx_lock(var) { } \ + static __always_inline void __acquire_shared_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis __acquires_shared_ctx_lock(var) { } \ + static __always_inline bool __try_acquire_ctx_lock(const struct name *var, bool ret) \ + __attribute__((overloadable)) __no_context_analysis __try_acquires_ctx_lock(1, var) \ + { return ret; } \ + static __always_inline bool __try_acquire_shared_ctx_lock(const struct name *var, bool ret) \ + __attribute__((overloadable)) __no_context_analysis __try_acquires_shared_ctx_lock(1, var) \include/linux/compiler-context-analysis.h line 123
Quoted 10 lines
include/linux/compiler-context-analysis.h +10
-0+ {return ret; } \ + static __always_inline void __release_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis__releases_ctx_lock (var) { } \ + static __always_inline void __release_shared_ctx_lock(const struct name *var) \ + __attribute__((overloadable)) __no_context_analysis__releases_shared_ctx_lock (var) { } \ + static __always_inline void __assume_ctx_lock(const struct name *var) \ + __attribute__((overloadable))__assumes_ctx_lock (var) { } \ + static __always_inline void __assume_shared_ctx_lock(const struct name *var) \ + __attribute__((overloadable))__assumes_shared_ctx_lock (var) { } \ +struct name I'm concerned that the
context_lock_struct()macro will make code harder to read. Anyone who encounters thecontext_lock_struct()macro will have to look up its definition to learn what it does. I propose to split this macro into two macros:
* One macro that expands into "__ctx_lock_type(name)".
* A second macro that expands into the rest of the above macro.
Quoted 7 lines
In other words, instead of having to write context_lock_struct(struct_name, { ... }); developers will have to write
struct context_lock_type struct_name { ...; };
context_struct_helper_functions(struct_name);
This doesn't necessarily help with not having to look up its definition to learn what it does.
If this is the common pattern, it will blindly be repeated, and this adds 1 more line and makes this a bit more verbose. Maybe the helper functions aren't always needed, but I also think that context lock types should remain relatively few. For all synchronization primitives that were enabled in this series, the helpers are required.
The current usage is simply:
context_lock_struct(name) {
... struct goes here ...
}; // note no awkward ) brace
I don't know which way the current kernel style is leaning towards, but if we take <linux/cleanup.h> as an example, a simple programming model / API is actually preferred.
Quoted 4 lines
My opinion is that the alternative that I'm proposing is easier to read. Additionally, it doesn't break existing tools that support jumping from the name of a struct to its definition, e.g. ctags and etags.
Quoted 11 lines
lib/Kconfig.debug config DEBUG_FORCE_WEAK_PER_CPU · line 652
Quoted 9 lines
lib/Kconfig.debug +9
-0+config WARN_CONTEXT_ANALYSIS_ALL + bool "Enable context analysis for all source files" + depends on WARN_CONTEXT_ANALYSIS + depends on EXPERT && !COMPILE_TEST + help + Enable tree-wide context analysis. This is likely to produce a + large number of false positives - enable at your own risk. + + If unsure, say N.Why !COMPILE_TEST?
That's the idiomatic way to prevent this being enabled in allyesconfig builds, and other compile-only random configs enabling this and then stumbling over 1000s of warnings.
Thanks,
-- Marco
Bart Van Assche
reviewerRe: [PATCH v5 02/36] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
Quoted 28 lines · Marco Elver
Quoted 7 lines · Bart Van Assche' via kasan-dev
I'm concerned that the
context_lock_struct()macro will make code harder to read. Anyone who encounters thecontext_lock_struct()macro will have to look up its definition to learn what it does. I propose to split this macro into two macros:
* One macro that expands into "__ctx_lock_type(name)".
* A second macro that expands into the rest of the above macro.Quoted 7 lines
In other words, instead of having to write context_lock_struct(struct_name, { ... }); developers will have to write
struct context_lock_type struct_name { ...; };
context_struct_helper_functions(struct_name);This doesn't necessarily help with not having to look up its definition to learn what it does.
If this is the common pattern, it will blindly be repeated, and this adds 1 more line and makes this a bit more verbose. Maybe the helper functions aren't always needed, but I also think that context lock types should remain relatively few. For all synchronization primitives that were enabled in this series, the helpers are required.
The current usage is simply:
Quoted 7 lines
context_lock_struct(name){
... struct goes here ...
}; // note no awkward ) braceI don't know which way the current kernel style is leaning towards, but if we take <
linux/cleanup.h> as an example, a simple programming model / API is actually preferred.
Many kernel developers are used to look up the definition of a data structure either by using ctags, etags or a similar tool or by using grep and a pattern like "${struct_name} {\$". Breaking the tools kernel developer use today to look up data structure definitions might cause considerable frustration and hence shouldn't be done lightly.
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 02/36] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
Quoted 33 lines · Bart Van Assche' via kasan-dev
Quoted 32 lines · Marco Elver
Quoted 7 lines · Bart Van Assche' via kasan-dev
I'm concerned that the
context_lock_struct()macro will make code harder to read. Anyone who encounters thecontext_lock_struct()macro will have to look up its definition to learn what it does. I propose to split this macro into two macros:
* One macro that expands into "__ctx_lock_type(name)".
* A second macro that expands into the rest of the above macro.Quoted 7 lines
In other words, instead of having to write context_lock_struct(struct_name, { ... }); developers will have to write
struct context_lock_type struct_name { ...; };
context_struct_helper_functions(struct_name);This doesn't necessarily help with not having to look up its definition to learn what it does.
If this is the common pattern, it will blindly be repeated, and this adds 1 more line and makes this a bit more verbose. Maybe the helper functions aren't always needed, but I also think that context lock types should remain relatively few. For all synchronization primitives that were enabled in this series, the helpers are required.
The current usage is simply:
context_lock_struct(name){
... struct goes here ...
}; // note no awkward ) brace
Quoted 8 lines
Quoted 3 lines
I don't know which way the current kernel style is leaning towards, but if we take <
linux/cleanup.h> as an example, a simple programming model / API is actually preferred.Many kernel developers are used to look up the definition of a data structure either by using ctags, etags or a similar tool or by using grep and a pattern like "${struct_name} {\$". Breaking the tools kernel developer use today to look up data structure definitions might cause considerable frustration and hence shouldn't be done lightly.
Fair point. In fact, it's as simple as e.g. (just tested with mutex) as this:
include/linux/mutex_types.h +4 -2
@@ -38,7 +38,8 @@* - detects multi-task circular deadlocks and prints out all affected * locks and tasks (and only those tasks) */ -context_lock_struct (mutex) { +context_lock_struct (mutex); +struct mutex {atomic_long_t owner;raw_spinlock_t wait_lock;#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
@@ -59,7 +60,8 @@ context_lock_struct(mutex) {*/ #include <linux/rtmutex.h> -context_lock_struct (mutex) { +context_lock_struct (mutex); +struct mutex {struct rt_mutex_base rtmutex;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;
So the existing macro does support both use-cases as-is. I suppose we could force the above use pattern.
The reason it works, is because it forward-declares the struct anyway to define the helper functions.
Peter Zijlstra
maintainerRe: [PATCH v5 02/36] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
Quoted 5 lines · Marco Elver
Quoted 5 lines
Many kernel developers are used to look up the definition of a data structure either by using ctags, etags or a similar tool or by using grep and a pattern like "${struct_name} {\$". Breaking the tools kernel developer use today to look up data structure definitions might cause considerable frustration and hence shouldn't be done lightly.
Its a simple matter of adding a regex to scripts/tags.sh :-) Also clangd language server sees right through it as is. So all 'modern' stuff using that will have no problems.
[tip: locking/core] tags: Add regex for context_lock_struct
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: c10d860e0baae0853773dc90a94b26adc5687380 Gitweb: https://git.kernel.org/tip/c10d860e0baae0853773dc90a94b26adc5687380 Author: Peter Zijlstra <[email protected]> AuthorDate: Mon, 05 Jan 2026 16:24:05 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:37 +01:00
tags: Add regex for context_lock_struct
With the introduction of compiler context analysis (LLVM ThreadSafetyAnalysis) the struct definition of various locks get wrapped in a macro. This hides them from tags based navigation, although clangd/LSP sees right through it and works as expected.
Add a regex to the tags script to help it along.
--- scripts/tags.sh | 1 + 1 file changed, 1 insertion(+)
scripts/tags.sh +1 -0
@@ -221,6 +221,7 @@ regex_c=( '/^\<DEFINE_GUARD_COND(\([[:alnum:]_]\+\),[[:space:]]*\([[:alnum:]_]\+\)/class_\1\2/' '/^\<DEFINE_LOCK_GUARD_[[:digit:]](\([[:alnum:]_]\+\)/class_\1/' '/^\<DEFINE_LOCK_GUARD_[[:digit:]]_COND(\([[:alnum:]_]\+\),[[:space:]]*\([[:alnum:]_]\+\)/class_\1\2/' + '/^context_lock_struct(\([^,)]*\)[^)]*)/struct \1/' ) regex_kconfig=( '/^[[:blank:]]*\(menu\|\)config[[:blank:]]\+\([[:alnum:]_]\+\)/\2/'
[tip: locking/core] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 3269701cb25662ae8a9771a864201116626adb50 Gitweb: https://git.kernel.org/tip/3269701cb25662ae8a9771a864201116626adb50 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:51 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:26 +01:00
compiler-context-analysis: Add infrastructure for Context Analysis with Clang
Context Analysis is a language extension, which enables statically checking that required contexts are active (or inactive), by acquiring and releasing user-definable "context locks". An obvious application is lock-safety checking for the kernel's various synchronization primitives (each of which represents a "context lock"), and checking that locking rules are not violated.
Clang originally called the feature "Thread Safety Analysis" [1]. This was later changed and the feature became more flexible, gaining the ability to define custom "capabilities". Its foundations can be found in "Capability Systems" [2], used to specify the permissibility of operations to depend on some "capability" being held (or not held).
Because the feature is not just able to express "capabilities" related to synchronization primitives, and "capability" is already overloaded in the kernel, the naming chosen for the kernel departs from Clang's "Thread Safety" and "capability" nomenclature; we refer to the feature as "Context Analysis" to avoid confusion. The internal implementation still makes references to Clang's terminology in a few places, such as -Wthread-safety being the warning option that also still appears in diagnostic messages.
[1] https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
[2] https://www.cs.cornell.edu/talc/papers/capabilities.pdf
See more details in the kernel-doc documentation added in this and subsequent changes.
Clang version 22+ is required.
--- Makefile | 1 +- include/linux/compiler-context-analysis.h | 464 ++++++++++++++++++++- lib/Kconfig.debug | 30 +- scripts/Makefile.context-analysis | 7 +- scripts/Makefile.lib | 10 +- 5 files changed, 505 insertions(+), 7 deletions(-) create mode 100644 scripts/Makefile.context-analysis
Makefile +1 -0
@@ -1118,6 +1118,7 @@ include-$(CONFIG_RANDSTRUCT) += scripts/Makefile.randstruct include-$(CONFIG_KSTACK_ERASE) += scripts/Makefile.kstack_erase include-$(CONFIG_AUTOFDO_CLANG) += scripts/Makefile.autofdo include-$(CONFIG_PROPELLER_CLANG) += scripts/Makefile.propeller +include-$(CONFIG_WARN_CONTEXT_ANALYSIS) += scripts/Makefile.context-analysis include-$(CONFIG_GCC_PLUGINS) += scripts/Makefile.gcc-plugins include $(addprefix $(srctree)/, $(include-y))
include/linux/compiler-context-analysis.h +457 -7
484 lines not on this page · raw message
lib/Kconfig.debug +30 -0
@@ -621,6 +621,36 @@ config DEBUG_FORCE_WEAK_PER_CPU To ensure that generic code follows the above rules, this option forces all percpu variables to be defined as weak. +config WARN_CONTEXT_ANALYSIS + bool "Compiler context-analysis warnings" + depends on CC_IS_CLANG && CLANG_VERSION >= 220000 + # Branch profiling re-defines "if", which messes with the compiler's + # ability to analyze __cond_acquires(..), resulting in false positives. + depends on !TRACE_BRANCH_PROFILING + default y + help + Context Analysis is a language extension, which enables statically + checking that required contexts are active (or inactive) by acquiring + and releasing user-definable "context locks". + + Clang's name of the feature is "Thread Safety Analysis". Requires + Clang 22 or later. + + Produces warnings by default. Select CONFIG_WERROR if you wish to + turn these warnings into errors. + + For more details, see Documentation/dev-tools/context-analysis.rst. + +config WARN_CONTEXT_ANALYSIS_ALL + bool "Enable context analysis for all source files" + depends on WARN_CONTEXT_ANALYSIS + depends on EXPERT && !COMPILE_TEST + help + Enable tree-wide context analysis. This is likely to produce a + large number of false positives - enable at your own risk. + + If unsure, say N. + endmenu # "Compiler options" menu "Generic Kernel Debugging Instruments"
scripts/Makefile.context-analysis new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 + +context-analysis-cflags := -DWARN_CONTEXT_ANALYSIS \ + -fexperimental-late-parse-attributes -Wthread-safety \ + -Wthread-safety-pointer -Wthread-safety-beta + +export CFLAGS_CONTEXT_ANALYSIS := $(context-analysis-cflags)
scripts/Makefile.lib +10 -0
@@ -106,6 +106,16 @@ _c_flags += $(if $(patsubst n%,, \ endif # +# Enable context analysis flags only where explicitly opted in. +# (depends on variables CONTEXT_ANALYSIS_obj.o, CONTEXT_ANALYSIS) +# +ifeq ($(CONFIG_WARN_CONTEXT_ANALYSIS),y) +_c_flags += $(if $(patsubst n%,, \ + $(CONTEXT_ANALYSIS_$(target-stem).o)$(CONTEXT_ANALYSIS)$(if $(is-kernel-object),$(CONFIG_WARN_CONTEXT_ANALYSIS_ALL))), \ + $(CFLAGS_CONTEXT_ANALYSIS)) +endif + +# # Enable AutoFDO build flags except some files or directories we don't want to # enable (depends on variables AUTOFDO_PROFILE_obj.o and AUTOFDO_PROFILE). #
Marco Elver
maintainerPATCH v5 3/36 compiler-context-analysis: Add test stub
In reply to Marco ElverAdd a simple test stub where we will add common supported patterns that should not generate false positives for each new supported context lock.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
--- lib/Kconfig.debug | 14 ++++++++++++++ lib/Makefile | 3 +++ lib/test_context-analysis.c | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 lib/test_context-analysis.c
lib/Kconfig.debug +14 -0
@@ -2835,6 +2835,20 @@ config LINEAR_RANGES_TEST If unsure, say N. +config CONTEXT_ANALYSIS_TEST + bool "Compiler context-analysis warnings test" + depends on EXPERT + help + This builds the test for compiler-based context analysis. The test + does not add executable code to the kernel, but is meant to test that + common patterns supported by the analysis do not result in false + positive warnings. + + When adding support for new context locks, it is strongly recommended + to add supported patterns to this test. + + If unsure, say N. + config CMDLINE_KUNIT_TEST tristate "KUnit test for cmdline API" if !KUNIT_ALL_TESTS depends on KUNIT
lib/Makefile +3 -0
@@ -331,4 +331,7 @@ obj-$(CONFIG_GENERIC_LIB_DEVMEM_IS_ALLOWED) += devmem_is_allowed.o obj-$(CONFIG_FIRMWARE_TABLE) += fw_table.o +CONTEXT_ANALYSIS_test_context-analysis.o := y +obj-$(CONFIG_CONTEXT_ANALYSIS_TEST) += test_context-analysis.o + subdir-$(CONFIG_FORTIFY_SOURCE) += test_fortify
lib/test_context-analysis.c new file +18 -0
@@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Compile-only tests for common patterns that should not generate false +* positive errors when compiled with Clang's context analysis. +*/ + +#include <linux/build_bug.h> + +/* +* Test that helper macros work as expected. +*/ +static void __used test_common_helpers (void ) +{ +BUILD_BUG_ON (context_unsafe (3 ) !=3 );/* plain expression */ + BUILD_BUG_ON(context_unsafe((void)2; 3) != 3); /* does not swallow semi-colon */ +BUILD_BUG_ON (context_unsafe ((void )2 ,3 ) !=3 );/* does not swallow commas */ + context_unsafe(do { } while (0)); /* works with void statements */ +}
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] compiler-context-analysis: Add test stub
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 9b00c1609deeb7d6f68a61f3ec6988ab7e6f4535 Gitweb: https://git.kernel.org/tip/9b00c1609deeb7d6f68a61f3ec6988ab7e6f4535 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:52 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:27 +01:00
compiler-context-analysis: Add test stub
Add a simple test stub where we will add common supported patterns that should not generate false positives for each new supported context lock.
--- lib/Kconfig.debug | 14 ++++++++++++++ lib/Makefile | 3 +++ lib/test_context-analysis.c | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 lib/test_context-analysis.c
lib/Kconfig.debug +14 -0
@@ -2835,6 +2835,20 @@ config LINEAR_RANGES_TEST If unsure, say N. +config CONTEXT_ANALYSIS_TEST + bool "Compiler context-analysis warnings test" + depends on EXPERT + help + This builds the test for compiler-based context analysis. The test + does not add executable code to the kernel, but is meant to test that + common patterns supported by the analysis do not result in false + positive warnings. + + When adding support for new context locks, it is strongly recommended + to add supported patterns to this test. + + If unsure, say N. + config CMDLINE_KUNIT_TEST tristate "KUnit test for cmdline API" if !KUNIT_ALL_TESTS depends on KUNIT
lib/Makefile +3 -0
@@ -331,4 +331,7 @@ obj-$(CONFIG_GENERIC_LIB_DEVMEM_IS_ALLOWED) += devmem_is_allowed.o obj-$(CONFIG_FIRMWARE_TABLE) += fw_table.o +CONTEXT_ANALYSIS_test_context-analysis.o := y +obj-$(CONFIG_CONTEXT_ANALYSIS_TEST) += test_context-analysis.o + subdir-$(CONFIG_FORTIFY_SOURCE) += test_fortify
lib/test_context-analysis.c new file +18 -0
@@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Compile-only tests for common patterns that should not generate false +* positive errors when compiled with Clang's context analysis. +*/ + +#include <linux/build_bug.h> + +/* +* Test that helper macros work as expected. +*/ +static void __used test_common_helpers (void ) +{ +BUILD_BUG_ON (context_unsafe (3 ) !=3 );/* plain expression */ + BUILD_BUG_ON(context_unsafe((void)2; 3) != 3); /* does not swallow semi-colon */ +BUILD_BUG_ON (context_unsafe ((void )2 ,3 ) !=3 );/* does not swallow commas */ + context_unsafe(do { } while (0)); /* works with void statements */ +}
Marco Elver
maintainerPATCH v5 4/36 Documentation: Add documentation for Compiler-Based Context Analysis
In reply to Marco ElverAdds documentation in Documentation/dev-tools/context-analysis.rst, and adds it to the index.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
v2:
* Remove cross-reference to Sparse, since we plan to remove Sparse support anyway.
* Mention __no_context_analysis should be avoided.
--- Documentation/dev-tools/context-analysis.rst | 144 +++++++++++++++++++ Documentation/dev-tools/index.rst | 1 + 2 files changed, 145 insertions(+) create mode 100644 Documentation/dev-tools/context-analysis.rst
Documentation/dev-tools/context-analysis.rst new file +144 -0
@@ -0,0 +1,144 @@ +.. SPDX-License-Identifier: GPL-2.0 +.. Copyright (C) 2025, Google LLC. + +.. _context-analysis: + +Compiler-Based Context Analysis +=============================== + +Context Analysis is a language extension, which enables statically checking +that required contexts are active (or inactive) by acquiring and releasing +user-definable "context locks". An obvious application is lock-safety checking +for the kernel's various synchronization primitives (each of which represents a +"context lock"), and checking that locking rules are not violated. + +The Clang compiler currently supports the full set of context analysis +features. To enable for Clang, configure the kernel with:: + + CONFIG_WARN_CONTEXT_ANALYSIS=y + +The feature requires Clang 22 or later. + +The analysis is *opt-in by default*, and requires declaring which modules and +subsystems should be analyzed in the respective `Makefile`:: + + CONTEXT_ANALYSIS_mymodule.o := y + +Or for all translation units in the directory:: + + CONTEXT_ANALYSIS := y + +It is possible to enable the analysis tree-wide, however, which will result in +numerous false positive warnings currently and is *not* generally recommended:: + + CONFIG_WARN_CONTEXT_ANALYSIS_ALL=y + +Programming Model +----------------- + +The below describes the programming model around using context lock types. + +.. note:: + Enabling context analysis can be seen as enabling a dialect of Linux C with + a Context System. Some valid patterns involving complex control-flow are + constrained (such as conditional acquisition and later conditional release + in the same function). + +Context analysis is a way to specify permissibility of operations to depend on +context locks being held (or not held). Typically we are interested in +protecting data and code in a critical section by requiring a specific context +to be active, for example by holding a specific lock. The analysis ensures that +callers cannot perform an operation without the required context being active. + +Context locks are associated with named structs, along with functions that +operate on struct instances to acquire and release the associated context lock. + +Context locks can be held either exclusively or shared. This mechanism allows +assigning more precise privileges when a context is active, typically to +distinguish where a thread may only read (shared) or also write (exclusive) to +data guarded within a context. + +The set of contexts that are actually active in a given thread at a given point +in program execution is a run-time concept. The static analysis works by +calculating an approximation of that set, called the context environment. The +context environment is calculated for every program point, and describes the +set of contexts that are statically known to be active, or inactive, at that +particular point. This environment is a conservative approximation of the full +set of contexts that will actually be active in a thread at run-time. + +More details are also documented `here +<https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_. + +.. note:: + Clang's analysis explicitly does not infer context locks acquired or + released by inline functions. It requires explicit annotations to (a) assert + that it's not a bug if a context lock is released or acquired, and (b) to + retain consistency between inline and non-inline function declarations. + +Supported Kernel Primitives +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. Currently the following synchronization primitives are supported: + +For context locks with an initialization function (e.g., `spin_lock_init()`), +calling this function before initializing any guarded members or globals +prevents the compiler from issuing warnings about unguarded initialization. + +Lockdep assertions, such as `lockdep_assert_held()`, inform the compiler's +context analysis that the associated synchronization primitive is held after +the assertion. This avoids false positives in complex control-flow scenarios +and encourages the use of Lockdep where static analysis is limited. For +example, this is useful when a function doesn't *always* require a lock, making +`__must_hold()` inappropriate. + +Keywords +~~~~~~~~ + +.. kernel-doc:: include/linux/compiler-context-analysis.h + :identifiers: context_lock_struct + token_context_lock token_context_lock_instance + __guarded_by __pt_guarded_by + __must_hold + __must_not_hold + __acquires + __cond_acquires + __releases + __must_hold_shared + __acquires_shared + __cond_acquires_shared + __releases_shared + __acquire + __release + __cond_lock + __acquire_shared + __release_shared + __cond_lock_shared + __acquire_ret + __acquire_shared_ret + context_unsafe + __context_unsafe + disable_context_analysis enable_context_analysis + +.. note:: + The function attribute `__no_context_analysis` is reserved for internal + implementation of context lock types, and should be avoided in normal code. + +Background +---------- + +Clang originally called the feature `Thread Safety Analysis +<https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_, with some keywords +and documentation still using the thread-safety-analysis-only terminology. This +was later changed and the feature became more flexible, gaining the ability to +define custom "capabilities". Its foundations can be found in `Capability +Systems <https://www.cs.cornell.edu/talc/papers/capabilities.pdf>`_, used to +specify the permissibility of operations to depend on some "capability" being +held (or not held). + +Because the feature is not just able to express capabilities related to +synchronization primitives, and "capability" is already overloaded in the +kernel, the naming chosen for the kernel departs from Clang's initial "Thread +Safety" and "capability" nomenclature; we refer to the feature as "Context +Analysis" to avoid confusion. The internal implementation still makes +references to Clang's terminology in a few places, such as `-Wthread-safety` +being the warning option that also still appears in diagnostic messages.
Documentation/dev-tools/index.rst +1 -0
@@ -21,6 +21,7 @@ Documentation/process/debugging/index.rst checkpatch clang-format coccinelle + context-analysis sparse kcov gcov
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 04/36] Documentation: Add documentation for Compiler-Based Context Analysis
Quoted 1 line · Marco Elver
+Context Analysis is a language extension, which enables statically checking
^
My grammar checker tells me that there shouldn't be a comma here. However, I'm not sure whether the software that I'm using got this right.
Documentation/dev-tools/context-analysis.rst line 11
Quoted 2 lines
Documentation/dev-tools/context-analysis.rst new file +2
-0+that required contexts are active (or inactive) by acquiring and releasing +user-definable "context locks". An obvious application is lock-safety checking
Please improve clarity of this text by adding a definition for "context
lock", e.g. the following: "Each context lock has a name. A state is associated with each context lock. Supported states are locked, unlocked, shared locked and exclusive locked. Functions can be annotated to declare what lock state is expected upon entry and what the lock state will be upon return. Members of data structures can be annotated to indicate what context locks should be held upon access."
Thanks,
Bart.
[tip: locking/core] Documentation: Add documentation for Compiler-Based Context Analysis
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 8f32441d7a532804a8d9e2ae36f9b13c353934d7 Gitweb: https://git.kernel.org/tip/8f32441d7a532804a8d9e2ae36f9b13c353934d7 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:53 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:27 +01:00
Documentation: Add documentation for Compiler-Based Context Analysis
Adds documentation in Documentation/dev-tools/context-analysis.rst, and adds it to the index.
--- Documentation/dev-tools/context-analysis.rst | 144 ++++++++++++++++++- Documentation/dev-tools/index.rst | 1 +- 2 files changed, 145 insertions(+) create mode 100644 Documentation/dev-tools/context-analysis.rst
Documentation/dev-tools/context-analysis.rst new file +144 -0
@@ -0,0 +1,144 @@ +.. SPDX-License-Identifier: GPL-2.0 +.. Copyright (C) 2025, Google LLC. + +.. _context-analysis: + +Compiler-Based Context Analysis +=============================== + +Context Analysis is a language extension, which enables statically checking +that required contexts are active (or inactive) by acquiring and releasing +user-definable "context locks". An obvious application is lock-safety checking +for the kernel's various synchronization primitives (each of which represents a +"context lock"), and checking that locking rules are not violated. + +The Clang compiler currently supports the full set of context analysis +features. To enable for Clang, configure the kernel with:: + + CONFIG_WARN_CONTEXT_ANALYSIS=y + +The feature requires Clang 22 or later. + +The analysis is *opt-in by default*, and requires declaring which modules and +subsystems should be analyzed in the respective `Makefile`:: + + CONTEXT_ANALYSIS_mymodule.o := y + +Or for all translation units in the directory:: + + CONTEXT_ANALYSIS := y + +It is possible to enable the analysis tree-wide, however, which will result in +numerous false positive warnings currently and is *not* generally recommended:: + + CONFIG_WARN_CONTEXT_ANALYSIS_ALL=y + +Programming Model +----------------- + +The below describes the programming model around using context lock types. + +.. note:: + Enabling context analysis can be seen as enabling a dialect of Linux C with + a Context System. Some valid patterns involving complex control-flow are + constrained (such as conditional acquisition and later conditional release + in the same function). + +Context analysis is a way to specify permissibility of operations to depend on +context locks being held (or not held). Typically we are interested in +protecting data and code in a critical section by requiring a specific context +to be active, for example by holding a specific lock. The analysis ensures that +callers cannot perform an operation without the required context being active. + +Context locks are associated with named structs, along with functions that +operate on struct instances to acquire and release the associated context lock. + +Context locks can be held either exclusively or shared. This mechanism allows +assigning more precise privileges when a context is active, typically to +distinguish where a thread may only read (shared) or also write (exclusive) to +data guarded within a context. + +The set of contexts that are actually active in a given thread at a given point +in program execution is a run-time concept. The static analysis works by +calculating an approximation of that set, called the context environment. The +context environment is calculated for every program point, and describes the +set of contexts that are statically known to be active, or inactive, at that +particular point. This environment is a conservative approximation of the full +set of contexts that will actually be active in a thread at run-time. + +More details are also documented `here +<https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_. + +.. note:: + Clang's analysis explicitly does not infer context locks acquired or + released by inline functions. It requires explicit annotations to (a) assert + that it's not a bug if a context lock is released or acquired, and (b) to + retain consistency between inline and non-inline function declarations. + +Supported Kernel Primitives +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. Currently the following synchronization primitives are supported: + +For context locks with an initialization function (e.g., `spin_lock_init()`), +calling this function before initializing any guarded members or globals +prevents the compiler from issuing warnings about unguarded initialization. + +Lockdep assertions, such as `lockdep_assert_held()`, inform the compiler's +context analysis that the associated synchronization primitive is held after +the assertion. This avoids false positives in complex control-flow scenarios +and encourages the use of Lockdep where static analysis is limited. For +example, this is useful when a function doesn't *always* require a lock, making +`__must_hold()` inappropriate. + +Keywords +~~~~~~~~ + +.. kernel-doc:: include/linux/compiler-context-analysis.h + :identifiers: context_lock_struct + token_context_lock token_context_lock_instance + __guarded_by __pt_guarded_by + __must_hold + __must_not_hold + __acquires + __cond_acquires + __releases + __must_hold_shared + __acquires_shared + __cond_acquires_shared + __releases_shared + __acquire + __release + __cond_lock + __acquire_shared + __release_shared + __cond_lock_shared + __acquire_ret + __acquire_shared_ret + context_unsafe + __context_unsafe + disable_context_analysis enable_context_analysis + +.. note:: + The function attribute `__no_context_analysis` is reserved for internal + implementation of context lock types, and should be avoided in normal code. + +Background +---------- + +Clang originally called the feature `Thread Safety Analysis +<https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_, with some keywords +and documentation still using the thread-safety-analysis-only terminology. This +was later changed and the feature became more flexible, gaining the ability to +define custom "capabilities". Its foundations can be found in `Capability +Systems <https://www.cs.cornell.edu/talc/papers/capabilities.pdf>`_, used to +specify the permissibility of operations to depend on some "capability" being +held (or not held). + +Because the feature is not just able to express capabilities related to +synchronization primitives, and "capability" is already overloaded in the +kernel, the naming chosen for the kernel departs from Clang's initial "Thread +Safety" and "capability" nomenclature; we refer to the feature as "Context +Analysis" to avoid confusion. The internal implementation still makes +references to Clang's terminology in a few places, such as `-Wthread-safety` +being the warning option that also still appears in diagnostic messages.
Documentation/dev-tools/index.rst +1 -0
@@ -21,6 +21,7 @@ Documentation/process/debugging/index.rst checkpatch clang-format coccinelle + context-analysis sparse kcov gcov
Marco Elver
maintainerPATCH v5 5/36 checkpatch: Warn about context_unsafe() without comment
In reply to Marco ElverWarn about applications of context_unsafe() without a comment, to encourage documenting the reasoning behind why it was deemed safe.
---
v4:
* Rename capability -> context analysis.
* Avoid nested if.
--- scripts/checkpatch.pl | 7 +++++++ 1 file changed, 7 insertions(+)
scripts/checkpatch.pl +7 -0
@@ -6733,6 +6733,13 @@ sub process { } } +# check for context_unsafe without a comment. + if ($line =~ /\bcontext_unsafe\b/ && + !ctx_has_comment($first_line, $linenr)) { + WARN("CONTEXT_UNSAFE", + "context_unsafe without comment\n" . $herecurr); + } + # check of hardware specific defines if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) { CHK("ARCH_DEFINES",
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] checkpatch: Warn about context_unsafe() without comment
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 25d3b21e1d41f7b58aeb62b97b05d86d43c91801 Gitweb: https://git.kernel.org/tip/25d3b21e1d41f7b58aeb62b97b05d86d43c91801 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:54 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:27 +01:00
checkpatch: Warn about context_unsafe() without comment
Warn about applications of context_unsafe() without a comment, to encourage documenting the reasoning behind why it was deemed safe.
--- scripts/checkpatch.pl | 7 +++++++ 1 file changed, 7 insertions(+)
scripts/checkpatch.pl +7 -0
@@ -6733,6 +6733,13 @@ sub process { } } +# check for context_unsafe without a comment. + if ($line =~ /\bcontext_unsafe\b/ && + !ctx_has_comment($first_line, $linenr)) { + WARN("CONTEXT_UNSAFE", + "context_unsafe without comment\n" . $herecurr); + } + # check of hardware specific defines if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) { CHK("ARCH_DEFINES",
Marco Elver
maintainerPATCH v5 6/36 cleanup: Basic compatibility with context analysis
In reply to Marco ElverIntroduce basic compatibility with cleanup.h infrastructure.
We need to allow the compiler to see the acquisition and release of the context lock at the start and end of a scope. However, the current "cleanup" helpers wrap the lock in a struct passed through separate helper functions, which hides the lock alias from the compiler (no inter-procedural analysis).
While Clang supports scoped guards in C++, it's not possible to apply in C code: https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#scoped-context
However, together with recent improvements to Clang's alias analysis abilities, idioms such as this work correctly now:
void spin_unlock_cleanup(spinlock_t **l) __releases(*l) { .. }
...
{
spinlock_t *lock_scope __cleanup(spin_unlock_cleanup) = &lock;
spin_lock(&lock); // lock through &lock
... critical section ...
} // unlock through lock_scope -[alias]-> &lock (no warnings)To generalize this pattern and make it work with existing lock guards, introduce DECLARE_LOCK_GUARD_1_ATTRS() and WITH_LOCK_GUARD_1_ATTRS().
These allow creating an explicit alias to the context lock instance that is "cleaned" up with a separate cleanup helper. This helper is a dummy function that does nothing at runtime, but has the release attributes to tell the compiler what happens at the end of the scope.
Example usage:
DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) #define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T)
Note: To support the for-loop based scoped helpers, the auxiliary variable must be a pointer to the "class" type because it is defined in the same statement as the guard variable. However, we initialize it with the lock pointer (despite the type mismatch, the compiler's alias analysis still works as expected). The "_unlock" attribute receives a pointer to the auxiliary variable (a double pointer to the class type), and must be cast and dereferenced appropriately.
---
v5:
* Rework infrastructure to properly release at scope end with reworked WITH_LOCK_GUARD_1_ATTRS() and WITH_LOCK_GUARD_1_ATTRS().
v4:
* Rename capability -> context analysis.
v3:
* Add *_ATTRS helpers instead of implicit __assumes_cap (suggested by Peter)
* __assert -> __assume rename
--- include/linux/cleanup.h | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+)
include/linux/cleanup.h +50 -0
@@ -278,16 +278,21 @@ const volatile void * __must_check_fn(const volatile void *val) #define DEFINE_CLASS(_name, _type, _exit, _init, _init_args...) \ typedef _type class_##_name##_t; \ +typedef _type lock_##_name##_t; \ static __always_inline void class_##_name##_destructor(_type *p) \ + __no_context_analysis \ { _type _T = *p; _exit; } \ static __always_inline _type class_##_name##_constructor(_init_args) \ + __no_context_analysis \ { _type t = _init; return t; } #define EXTEND_CLASS(_name, ext, _init, _init_args...) \ +typedef lock_##_name##_t lock_##_name##ext##_t; \ typedef class_##_name##_t class_##_name##ext##_t; \ static __always_inline void class_##_name##ext##_destructor(class_##_name##_t *p) \ { class_##_name##_destructor(p); } \ static __always_inline class_##_name##_t class_##_name##ext##_constructor(_init_args) \ + __no_context_analysis \ { class_##_name##_t t = _init; return t; }#define CLASS (_name, var) \
@@ -474,12 +479,14 @@ _label: \*/ #define __DEFINE_UNLOCK_GUARD (_name, _type, _unlock, ...) \ +typedef _type lock_##_name##_t; \ typedef struct { \ _type *lock; \ __VA_ARGS__; \ } class_##_name##_t; \ \ static __always_inline void class_##_name##_destructor(class_##_name##_t *_T) \ + __no_context_analysis \ { \ if (!__GUARD_IS_ERR(_T->lock)) { _unlock; } \ } \
@@ -488,6 +495,7 @@ __DEFINE_GUARD_LOCK_PTR(_name, &_T->lock)#define __DEFINE_LOCK_GUARD_1 (_name, _type, _lock) \ static __always_inline class_##_name##_t class_##_name##_constructor(_type *l) \ + __no_context_analysis \ { \ class_##_name##_t _t = { .lock = l }, *_T = &_t; \ _lock; \
@@ -496,6 +504,7 @@ static __always_inline class_##_name##_t class_##_name##_constructor(_type *l) \#define __DEFINE_LOCK_GUARD_0 (_name, _lock) \ static __always_inline class_##_name##_t class_##_name##_constructor(void) \ + __no_context_analysis \ { \ class_##_name##_t _t = { .lock = (void*)1 }, \ *_T __maybe_unused = &_t; \
@@ -503,6 +512,47 @@ static __always_inline class_##_name##_t class_##_name##_constructor(void) \return _t; \ } +#define DECLARE_LOCK_GUARD_0_ATTRS (_name, _lock, _unlock) \ +static inline class_##_name##_t class_##_name##_constructor(void) _lock;\ +static inline void class_##_name##_destructor(class_##_name##_t *_T) _unlock; + +/* +* To support Context Analysis, we need to allow the compiler to see the +* acquisition and release of the context lock. However, the "cleanup" helpers +* wrap the lock in a struct passed through separate helper functions, which +* hides the lock alias from the compiler (no inter-procedural analysis). +* +* To make it work, we introduce an explicit alias to the context lock instance +* that is "cleaned" up with a separate cleanup helper. This helper is a dummy +* function that does nothing at runtime, but has the "_unlock" attribute to +* tell the compiler what happens at the end of the scope. +* +* To generalize the pattern, the WITH_LOCK_GUARD_1_ATTRS() macro should be used +* to redefine the constructor, which then also creates the alias variable with +* the right "cleanup" attribute, *after* DECLARE_LOCK_GUARD_1_ATTRS() has been +* used. +* +* Example usage: +* +* DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) +* #define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T) +* +* Note: To support the for-loop based scoped helpers, the auxiliary variable +* must be a pointer to the "class" type because it is defined in the same +* statement as the guard variable. However, we initialize it with the lock +* pointer (despite the type mismatch, the compiler's alias analysis still works +* as expected). The "_unlock" attribute receives a pointer to the auxiliary +* variable (a double pointer to the class type), and must be cast and +* dereferenced appropriately. +*/ +#define DECLARE_LOCK_GUARD_1_ATTRS (_name, _lock, _unlock) \ +static inline class_##_name##_t class_##_name##_constructor(lock_##_name##_t *_T) _lock;\ +static __always_inline void __class_##_name##_cleanup_ctx(class_##_name##_t **_T) \ + __no_context_analysis _unlock { } +#define WITH_LOCK_GUARD_1_ATTRS (_name, _T) \ + class_##_name##_constructor(_T), \ + *__UNIQUE_ID(unlock) __cleanup(__class_##_name##_cleanup_ctx) = (void *)(unsigned long)(_T) +#define DEFINE_LOCK_GUARD_1 (_name, _type, _lock, _unlock, ...) \ __DEFINE_CLASS_IS_CONDITIONAL(_name, false); \ __DEFINE_UNLOCK_GUARD(_name, _type, _unlock, __VA_ARGS__) \
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 06/36] cleanup: Basic compatibility with context analysis
include/linux/cleanup.h static __always_inline class_##_name##_t class_##_name##_constructor(void) \ · line 551
Quoted 4 lines · Marco Elver
include/linux/cleanup.h +4
-0+#define DECLARE_LOCK_GUARD_1_ATTRS (_name, _lock, _unlock) \ +static inline class_##_name##_t class_##_name##_constructor(lock_##_name##_t *_T) _lock;\ +static __always_inline void __class_##_name##_cleanup_ctx(class_##_name##_t **_T) \ + __no_context_analysis _unlock { }
Elsewhere in the cleanup.h header arguments with the names "_lock" and "_unlock" hold executable code that perform "lock" and "unlock" operations respectively, e.g. mutex_lock() and mutex_unlock(). The DECLARE_LOCK_GUARD_1_ATTRS() "_lock" and "_unlock" arguments however are function annotations. Please prevent confusion and use other names for the _lock and _unlock arguments, e.g. _acquire_attr and _release_attr.
Thanks,
Bart.
[tip: locking/core] cleanup: Basic compatibility with context analysis
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 3931d4b980398012b66c8ff203bfa2ab3df71a71 Gitweb: https://git.kernel.org/tip/3931d4b980398012b66c8ff203bfa2ab3df71a71 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:55 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:28 +01:00
cleanup: Basic compatibility with context analysis
Introduce basic compatibility with cleanup.h infrastructure.
We need to allow the compiler to see the acquisition and release of the context lock at the start and end of a scope. However, the current "cleanup" helpers wrap the lock in a struct passed through separate helper functions, which hides the lock alias from the compiler (no inter-procedural analysis).
While Clang supports scoped guards in C++, it's not possible to apply in C code: https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#scoped-context
However, together with recent improvements to Clang's alias analysis abilities, idioms such as this work correctly now:
void spin_unlock_cleanup(spinlock_t **l) __releases(*l) { .. }
...
{
spinlock_t *lock_scope __cleanup(spin_unlock_cleanup) = &lock;
spin_lock(&lock); // lock through &lock
... critical section ...
} // unlock through lock_scope -[alias]-> &lock (no warnings)To generalize this pattern and make it work with existing lock guards, introduce DECLARE_LOCK_GUARD_1_ATTRS() and WITH_LOCK_GUARD_1_ATTRS().
These allow creating an explicit alias to the context lock instance that is "cleaned" up with a separate cleanup helper. This helper is a dummy function that does nothing at runtime, but has the release attributes to tell the compiler what happens at the end of the scope.
Example usage:
DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) #define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T)
Note: To support the for-loop based scoped helpers, the auxiliary variable must be a pointer to the "class" type because it is defined in the same statement as the guard variable. However, we initialize it with the lock pointer (despite the type mismatch, the compiler's alias analysis still works as expected). The "_unlock" attribute receives a pointer to the auxiliary variable (a double pointer to the class type), and must be cast and dereferenced appropriately.
--- include/linux/cleanup.h | 50 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+)
include/linux/cleanup.h +50 -0
@@ -278,16 +278,21 @@ const volatile void * __must_check_fn(const volatile void *val) #define DEFINE_CLASS(_name, _type, _exit, _init, _init_args...) \ typedef _type class_##_name##_t; \ +typedef _type lock_##_name##_t; \ static __always_inline void class_##_name##_destructor(_type *p) \ + __no_context_analysis \ { _type _T = *p; _exit; } \ static __always_inline _type class_##_name##_constructor(_init_args) \ + __no_context_analysis \ { _type t = _init; return t; } #define EXTEND_CLASS(_name, ext, _init, _init_args...) \ +typedef lock_##_name##_t lock_##_name##ext##_t; \ typedef class_##_name##_t class_##_name##ext##_t; \ static __always_inline void class_##_name##ext##_destructor(class_##_name##_t *p) \ { class_##_name##_destructor(p); } \ static __always_inline class_##_name##_t class_##_name##ext##_constructor(_init_args) \ + __no_context_analysis \ { class_##_name##_t t = _init; return t; }#define CLASS (_name, var) \
@@ -474,12 +479,14 @@ _label: \*/ #define __DEFINE_UNLOCK_GUARD (_name, _type, _unlock, ...) \ +typedef _type lock_##_name##_t; \ typedef struct { \ _type *lock; \ __VA_ARGS__; \ } class_##_name##_t; \ \ static __always_inline void class_##_name##_destructor(class_##_name##_t *_T) \ + __no_context_analysis \ { \ if (!__GUARD_IS_ERR(_T->lock)) { _unlock; } \ } \
@@ -488,6 +495,7 @@ __DEFINE_GUARD_LOCK_PTR(_name, &_T->lock)#define __DEFINE_LOCK_GUARD_1 (_name, _type, _lock) \ static __always_inline class_##_name##_t class_##_name##_constructor(_type *l) \ + __no_context_analysis \ { \ class_##_name##_t _t = { .lock = l }, *_T = &_t; \ _lock; \
@@ -496,6 +504,7 @@ static __always_inline class_##_name##_t class_##_name##_constructor(_type *l) \#define __DEFINE_LOCK_GUARD_0 (_name, _lock) \ static __always_inline class_##_name##_t class_##_name##_constructor(void) \ + __no_context_analysis \ { \ class_##_name##_t _t = { .lock = (void*)1 }, \ *_T __maybe_unused = &_t; \
@@ -503,6 +512,47 @@ static __always_inline class_##_name##_t class_##_name##_constructor(void) \return _t; \ } +#define DECLARE_LOCK_GUARD_0_ATTRS (_name, _lock, _unlock) \ +static inline class_##_name##_t class_##_name##_constructor(void) _lock;\ +static inline void class_##_name##_destructor(class_##_name##_t *_T) _unlock; + +/* +* To support Context Analysis, we need to allow the compiler to see the +* acquisition and release of the context lock. However, the "cleanup" helpers +* wrap the lock in a struct passed through separate helper functions, which +* hides the lock alias from the compiler (no inter-procedural analysis). +* +* To make it work, we introduce an explicit alias to the context lock instance +* that is "cleaned" up with a separate cleanup helper. This helper is a dummy +* function that does nothing at runtime, but has the "_unlock" attribute to +* tell the compiler what happens at the end of the scope. +* +* To generalize the pattern, the WITH_LOCK_GUARD_1_ATTRS() macro should be used +* to redefine the constructor, which then also creates the alias variable with +* the right "cleanup" attribute, *after* DECLARE_LOCK_GUARD_1_ATTRS() has been +* used. +* +* Example usage: +* +* DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) +* #define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T) +* +* Note: To support the for-loop based scoped helpers, the auxiliary variable +* must be a pointer to the "class" type because it is defined in the same +* statement as the guard variable. However, we initialize it with the lock +* pointer (despite the type mismatch, the compiler's alias analysis still works +* as expected). The "_unlock" attribute receives a pointer to the auxiliary +* variable (a double pointer to the class type), and must be cast and +* dereferenced appropriately. +*/ +#define DECLARE_LOCK_GUARD_1_ATTRS (_name, _lock, _unlock) \ +static inline class_##_name##_t class_##_name##_constructor(lock_##_name##_t *_T) _lock;\ +static __always_inline void __class_##_name##_cleanup_ctx(class_##_name##_t **_T) \ + __no_context_analysis _unlock { } +#define WITH_LOCK_GUARD_1_ATTRS (_name, _T) \ + class_##_name##_constructor(_T), \ + *__UNIQUE_ID(unlock) __cleanup(__class_##_name##_cleanup_ctx) = (void *)(unsigned long)(_T) +#define DEFINE_LOCK_GUARD_1 (_name, _type, _lock, _unlock, ...) \ __DEFINE_CLASS_IS_CONDITIONAL(_name, false); \ __DEFINE_UNLOCK_GUARD(_name, _type, _unlock, __VA_ARGS__) \
Tetsuo Handa
maintainerRe: [PATCH v5 06/36] cleanup: Basic compatibility with context analysis
In reply to Marco ElverQuoted 1 line · Marco Elver
Introduce basic compatibility with
cleanup.hinfrastructure.
Can Compiler-Based Context- and Locking-Analysis work with conditional guards (unlock only if lock succeeded) ?
I consider that replacing mutex_lock() with mutex_lock_killable() helps reducing frequency of hung tasks under heavy load where many processes are preempted waiting for the same mutex to become available (e.g.
https://syzkaller.appspot.com/bug?extid=8f41dccfb6c03cc36fd6 ).
But e.g. commit f49573f2f53e ("tty: use lock guard()s in tty_io") already replaced plain mutex_lock()/mutex_unlock() with plain guard(mutex). If I propose a patch for replacing mutex_lock() with mutex_lock_killable(), can I use conditional guards? (Would be yes if Compiler-Based Context- and Locking-Analysis can work, would be no
if Compiler-Based Context- and Locking-Analysis cannot work) ?
Marco Elver
maintainerRe: [PATCH v5 06/36] cleanup: Basic compatibility with context analysis
Quoted 11 lines · Tetsuo Handa
Quoted 1 line · Marco Elver
Introduce basic compatibility with
cleanup.hinfrastructure.Can Compiler-Based Context- and Locking-Analysis work with conditional guards (unlock only if lock succeeded) ?
I consider that replacing
mutex_lock()withmutex_lock_killable()helps reducing frequency of hung tasks under heavy load where many processes are preempted waiting for the same mutex to become available (e.g.
https://syzkaller.appspot.com/bug?extid=8f41dccfb6c03cc36fd6 ).
Quoted 5 lines
But e.g. commit
f49573f2f53e("tty: use lock guard()s intty_io") already replaced plain mutex_lock()/mutex_unlock() with plain guard(mutex). If I propose a patch for replacingmutex_lock()withmutex_lock_killable(), can I use conditional guards? (Would be yes if Compiler-Based Context- and Locking-Analysis can work, would be no
if Compiler-Based Context- and Locking-Analysis cannot work) ?
It works for cond guards, so yes. But, only if support for mutex_lock_killable() is added. At the moment mutex.h only has:
... DEFINE_LOCK_GUARD_1(mutex, struct mutex, mutex_lock(_T->lock), mutex_unlock(_T->lock)) DEFINE_LOCK_GUARD_1_COND(mutex, _try, mutex_trylock(_T->lock)) DEFINE_LOCK_GUARD_1_COND(mutex, _intr, mutex_lock_interruptible(_T->lock), _RET == 0) DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) #define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T) DECLARE_LOCK_GUARD_1_ATTRS(mutex_try, __acquires(_T), __releases(*(struct mutex **)_T)) #define class_mutex_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex_try, _T) DECLARE_LOCK_GUARD_1_ATTRS(mutex_intr, __acquires(_T), __releases(*(struct mutex **)_T)) #define class_mutex_intr_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex_intr, _T) ...
And we also have a test in lib/test_context-analysis.c checking it actually works:
...
scoped_cond_guard(mutex_try, return, &d->mtx) {
d->counter++;
}
scoped_cond_guard(mutex_intr, return, &d->mtx) {
d->counter++;
}
...What's missing is a variant for mutex_lock_killable(), but that should be similar to the mutex_lock_interruptible() variant.
Re: [PATCH v5 06/36] cleanup: Basic compatibility with context analysis
In reply to Marco Elver+cc Sid for awareness
Hi,
This patch breaks the radix tree and VMA userland tests. The next bots didn't catch it but it seems now they're building the userland VMA tests (e.g. https://lore.kernel.all/[email protected]/) but maybe not caught up to the issue this one caused (fails build in tools/testing/vma and tools/testing/radix-tree).
Anyway it's a really easy fix, just need to stub out __no_context_analysis in the tools/include copy of compiler_types.h, fix-patch provided below.
To avoid bisection hazard it'd be nice if it could be folded into this series before this patch, but if we're too late in the cycle for that I can submit a fix separately.
Thanks, Lorenzo
----8<----
From cc2390dbefed156757f001e8c3a500a6f8aa1244 Mon Sep 17 00:00:00 2001
From: Lorenzo Stoakes <[email protected]>
Date: Tue, 27 Jan 2026 10:10:55 +0000
Subject: [PATCH] fix
--- tools/include/linux/compiler_types.h | 2 ++ 1 file changed, 2 insertions(+)
tools/include/linux/compiler_types.h +2 -0
@@ -60,4 +60,6 @@ __scalar_type_to_expr_cases(long long), \ default: (x))) +#define __no_context_analysis +#endif /* __LINUX_COMPILER_TYPES_H */
--
2.52.0
Marco Elver
maintainerRe: [PATCH v5 06/36] cleanup: Basic compatibility with context analysis
Quoted 11 lines · Lorenzo Stoakes
+cc Sid for awareness
Hi,
This patch breaks the radix tree and VMA userland tests. The next bots didn't catch it but it seems now they're building the userland VMA tests (e.g. https://lore.kernel.all/[email protected]/) but maybe not caught up to the issue this one caused (fails build in
tools/testing/vmaandtools/testing/radix-tree).
Quoted 6 lines
Anyway it's a really easy fix, just need to stub out
__no_context_analysisin thetools/includecopy ofcompiler_types.h, fix-patch provided below.To avoid bisection hazard it'd be nice if it could be folded into this series before this patch, but if we're too late in the cycle for that I can submit a fix separately.
Thanks, I saw. I have a more complete fix I'm about to send.
Re: [PATCH v5 06/36] cleanup: Basic compatibility with context analysis
Quoted 13 lines · Marco Elver
Quoted 11 lines · Lorenzo Stoakes
+cc Sid for awareness
Hi,
This patch breaks the radix tree and VMA userland tests. The next bots didn't catch it but it seems now they're building the userland VMA tests (e.g. https://lore.kernel.all/[email protected]/) but maybe not caught up to the issue this one caused (fails build in
tools/testing/vmaandtools/testing/radix-tree).
Quoted 8 lines
Quoted 6 lines
Anyway it's a really easy fix, just need to stub out
__no_context_analysisin thetools/includecopy ofcompiler_types.h, fix-patch provided below.To avoid bisection hazard it'd be nice if it could be folded into this series before this patch, but if we're too late in the cycle for that I can submit a fix separately.
Thanks, I saw. I have a more complete fix I'm about to send.
Great, thanks!
Marco Elver
maintainerPATCH v5 7/36 lockdep: Annotate lockdep assertions for context analysis
In reply to Marco ElverClang's context analysis can be made aware of functions that assert that locks are held.
Presence of these annotations causes the analysis to assume the context lock is held after calls to the annotated function, and avoid false positives with complex control-flow; for example, where not all control-flow paths in a function require a held lock, and therefore marking the function with __must_hold(..) is inappropriate.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
v3:
* __assert -> __assume rename
--- include/linux/lockdep.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
include/linux/lockdep.h +6 -6
@@ -282,16 +282,16 @@ extern void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie); do { WARN_ON_ONCE(debug_locks && !(cond)); } while (0)#define lockdep_assert_held (l) \ - lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD) + do { lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD); __assume_ctx_lock(l); } while (0)#define lockdep_assert_not_held (l) \ lockdep_assert(lockdep_is_held(l) != LOCK_STATE_HELD)#define lockdep_assert_held_write (l) \ - lockdep_assert(lockdep_is_held_type(l, 0)) + do { lockdep_assert(lockdep_is_held_type(l, 0)); __assume_ctx_lock(l); } while (0)#define lockdep_assert_held_read (l) \ - lockdep_assert(lockdep_is_held_type(l, 1)) + do { lockdep_assert(lockdep_is_held_type(l, 1)); __assume_shared_ctx_lock(l); } while (0)#define lockdep_assert_held_once (l) \ lockdep_assert_once(lockdep_is_held(l) != LOCK_STATE_NOT_HELD)
@@ -389,10 +389,10 @@ extern int lockdep_is_held(const void *);#define lockdep_assert (c) do { } while (0)#define lockdep_assert_once (c) do { } while (0) -#define lockdep_assert_held (l) do { (void)(l); } while (0) +#define lockdep_assert_held (l) __assume_ctx_lock(l)#define lockdep_assert_not_held (l) do { (void)(l); } while (0) -#define lockdep_assert_held_write (l) do { (void)(l); } while (0) -#define lockdep_assert_held_read (l) do { (void)(l); } while (0) +#define lockdep_assert_held_write (l) __assume_ctx_lock(l) +#define lockdep_assert_held_read (l) __assume_shared_ctx_lock(l)#define lockdep_assert_held_once (l) do { (void)(l); } while (0)#define lockdep_assert_none_held_once () do { } while (0)
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 07/36] lockdep: Annotate lockdep assertions for context analysis
Quoted 27 lines · Marco Elver
include/linux/lockdep.h +3
-3@@ -282,16 +282,16 @@ extern void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie); do { WARN_ON_ONCE(debug_locks && !(cond)); } while (0)#define lockdep_assert_held (l) \ - lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD) + do { lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD); __assume_ctx_lock(l); } while (0)#define lockdep_assert_not_held (l) \ lockdep_assert(lockdep_is_held(l) != LOCK_STATE_HELD)#define lockdep_assert_held_write (l) \ - lockdep_assert(lockdep_is_held_type(l, 0)) + do { lockdep_assert(lockdep_is_held_type(l, 0)); __assume_ctx_lock(l); } while (0)#define lockdep_assert_held_read (l) \ - lockdep_assert(lockdep_is_held_type(l, 1)) + do { lockdep_assert(lockdep_is_held_type(l, 1)); __assume_shared_ctx_lock(l); } while (0)#define lockdep_assert_held_once (l) \ lockdep_assert_once(lockdep_is_held(l) != LOCK_STATE_NOT_HELD)@@ -389,10 +389,10 @@ extern int lockdep_is_held(const void *);#define lockdep_assert (c) do { } while (0)#define lockdep_assert_once (c) do { } while (0)
include/linux/lockdep.h extern int lockdep_is_held(const void *); · line 397
Quoted 10 lines
include/linux/lockdep.h +3
-3-#define lockdep_assert_held (l) do { (void)(l); } while (0) +#define lockdep_assert_held (l) __assume_ctx_lock(l)#define lockdep_assert_not_held (l) do { (void)(l); } while (0) -#define lockdep_assert_held_write (l) do { (void)(l); } while (0) -#define lockdep_assert_held_read (l) do { (void)(l); } while (0) +#define lockdep_assert_held_write (l) __assume_ctx_lock(l) +#define lockdep_assert_held_read (l) __assume_shared_ctx_lock(l)#define lockdep_assert_held_once (l) do { (void)(l); } while (0)#define lockdep_assert_none_held_once () do { } while (0)
I think these macros should use __must_hold() instead of __assume...(). lockdep_assert_held() emits a runtime warning if 'l' is not held. Hence, I think that code where lockdep_assert_held() is used should not compile if it cannot be verified at compile time that 'l' is held.
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 07/36] lockdep: Annotate lockdep assertions for context analysis
Quoted 30 lines · Bart Van Assche' via kasan-dev
Quoted 28 lines · Marco Elver
include/linux/lockdep.h +3
-3@@ -282,16 +282,16 @@ extern void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie); do { WARN_ON_ONCE(debug_locks && !(cond)); } while (0)#define lockdep_assert_held (l) \ - lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD) + do { lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD); __assume_ctx_lock(l); } while (0)#define lockdep_assert_not_held (l) \ lockdep_assert(lockdep_is_held(l) != LOCK_STATE_HELD)#define lockdep_assert_held_write (l) \ - lockdep_assert(lockdep_is_held_type(l, 0)) + do { lockdep_assert(lockdep_is_held_type(l, 0)); __assume_ctx_lock(l); } while (0)#define lockdep_assert_held_read (l) \ - lockdep_assert(lockdep_is_held_type(l, 1)) + do { lockdep_assert(lockdep_is_held_type(l, 1)); __assume_shared_ctx_lock(l); } while (0)#define lockdep_assert_held_once (l) \ lockdep_assert_once(lockdep_is_held(l) != LOCK_STATE_NOT_HELD)@@ -389,10 +389,10 @@ extern int lockdep_is_held(const void *);#define lockdep_assert (c) do { } while (0)#define lockdep_assert_once (c) do { } while (0)
Quoted 14 lines
include/linux/lockdep.h extern int lockdep_is_held(const void *); · line 397
Quoted 9 lines
include/linux/lockdep.h +3
-3-#define lockdep_assert_held (l) do { (void)(l); } while (0) +#define lockdep_assert_held (l) __assume_ctx_lock(l)#define lockdep_assert_not_held (l) do { (void)(l); } while (0) -#define lockdep_assert_held_write (l) do { (void)(l); } while (0) -#define lockdep_assert_held_read (l) do { (void)(l); } while (0) +#define lockdep_assert_held_write (l) __assume_ctx_lock(l) +#define lockdep_assert_held_read (l) __assume_shared_ctx_lock(l)#define lockdep_assert_held_once (l) do { (void)(l); } while (0)#define lockdep_assert_none_held_once () do { } while (0)I think these macros should use
__must_hold()instead of __assume...().lockdep_assert_held()emits a runtime warning if 'l' is not held. Hence, I think that code wherelockdep_assert_held()is used should not compile if it cannot be verified at compile time that 'l' is held.
That's not the purpose of this - if a function or variable should have a lock held, we mark them explicitly with __must_hold() or __guarded_by(), and we don't really need to use lockdep_assert, because the compiler helped us out. In an ideal world, every function or variable that requires a lock held is annotated, and we don't need to ever worry about explicitly checking if a lock is held (but we'll be far from that for a while).
The purpose is described in the commit message:
Quoted 3 lines
Presence of these annotations causes the analysis to assume the context lock is held after calls to the annotated function, and avoid false positives with complex control-flow; [...]
It's basically an escape hatch to defer to dynamic analysis where the limits of the static analysis are reached. This is also the original purpose of the "assert"/"assume" attributes:
https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#assert-capability-and-assert-shared-capability
Without this escape hatch, and deferral to dynamic analysis, we'd be stuck in some cases.
Re: [PATCH v5 07/36] lockdep: Annotate lockdep assertions for context analysis
Quoted 2 lines · Marco Elver
It's basically an escape hatch to defer to dynamic analysis where the limits of the static analysis are reached.
That's not how lockdep_assert_held() is used in the kernel. This macro is more often than not used to document assumptions that can be verified at compile time.
This patch seems like a step in the wrong direction to me because it *suppresses* compile time analysis compile-time analysis is useful. I think that this patch either should be dropped or that the __assume() annotations should be changed into __must_hold() annotations.
Bart.
Marco Elver
maintainerRe: [PATCH v5 07/36] lockdep: Annotate lockdep assertions for context analysis
Quoted 6 lines · Bart Van Assche
Quoted 2 lines · Marco Elver
It's basically an escape hatch to defer to dynamic analysis where the limits of the static analysis are reached.
That's not how
lockdep_assert_held()is used in the kernel.
Because there had not been any static analysis like this, and dynamic analysis is the only reasonable option.
Quoted 3 lines
This macro
is more often than not used to document assumptions that can be verified at compile time.
In that case the lockdep_assert can be dropped.
Quoted 4 lines
This patch seems like a step in the wrong direction to me because it *suppresses* compile time analysis compile-time analysis is useful. I think that this patch either should be dropped or that the
__assume()annotations should be changed into__must_hold()annotations.
If we drop this patch, e.g. the "sched: Enable context analysis for core.c and fair.c" will no longer compile.
It's a trade-off: more false positives vs. more complete analysis. For an analysis to be useful, these trade-offs make or break the analysis depending on the system they are applied to.
In the kernel, our experience with developer tooling has been that any efforts to reduce false positives will help a tool succeed at scale. Later you can claw back some completeness, but focusing on completeness first will kill the tool if false positives cannot reasonably be dealt with.
From the user space world we know that "assert lock held" [1] as this kind of escape hatch is valuable to deal with cases the static analysis just can't deal with. Sure, here we can make our own rules, but I'd argue we're in a worse position than most user space code, in that kernel code is significantly more complex (which is the reason I spent over half a year banging my head to make Clang's analysis significantly more capable).
[1] https://github.com/abseil/abseil-cpp/blob/a8960c053bf4adadac097c1101d0028742d8042f/absl/synchronization/mutex.h#L210
(ASSERT_EXCLUSIVE_LOCK() == __assume_ctx_lock())
[tip: locking/core] lockdep: Annotate lockdep assertions for context analysis
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 7c451541743c6c2ef1afc425191f18a23e311019 Gitweb: https://git.kernel.org/tip/7c451541743c6c2ef1afc425191f18a23e311019 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:56 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:28 +01:00
lockdep: Annotate lockdep assertions for context analysis
Clang's context analysis can be made aware of functions that assert that locks are held.
Presence of these annotations causes the analysis to assume the context lock is held after calls to the annotated function, and avoid false positives with complex control-flow; for example, where not all control-flow paths in a function require a held lock, and therefore marking the function with __must_hold(..) is inappropriate.
--- include/linux/lockdep.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
include/linux/lockdep.h +6 -6
@@ -282,16 +282,16 @@ extern void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie); do { WARN_ON_ONCE(debug_locks && !(cond)); } while (0)#define lockdep_assert_held (l) \ - lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD) + do { lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD); __assume_ctx_lock(l); } while (0)#define lockdep_assert_not_held (l) \ lockdep_assert(lockdep_is_held(l) != LOCK_STATE_HELD)#define lockdep_assert_held_write (l) \ - lockdep_assert(lockdep_is_held_type(l, 0)) + do { lockdep_assert(lockdep_is_held_type(l, 0)); __assume_ctx_lock(l); } while (0)#define lockdep_assert_held_read (l) \ - lockdep_assert(lockdep_is_held_type(l, 1)) + do { lockdep_assert(lockdep_is_held_type(l, 1)); __assume_shared_ctx_lock(l); } while (0)#define lockdep_assert_held_once (l) \ lockdep_assert_once(lockdep_is_held(l) != LOCK_STATE_NOT_HELD)
@@ -389,10 +389,10 @@ extern int lockdep_is_held(const void *);#define lockdep_assert (c) do { } while (0)#define lockdep_assert_once (c) do { } while (0) -#define lockdep_assert_held (l) do { (void)(l); } while (0) +#define lockdep_assert_held (l) __assume_ctx_lock(l)#define lockdep_assert_not_held (l) do { (void)(l); } while (0) -#define lockdep_assert_held_write (l) do { (void)(l); } while (0) -#define lockdep_assert_held_read (l) do { (void)(l); } while (0) +#define lockdep_assert_held_write (l) __assume_ctx_lock(l) +#define lockdep_assert_held_read (l) __assume_shared_ctx_lock(l)#define lockdep_assert_held_once (l) do { (void)(l); } while (0)#define lockdep_assert_none_held_once () do { } while (0)
Marco Elver
maintainerPATCH v5 8/36 locking/rwlock, spinlock: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for raw_spinlock_t, spinlock_t, and rwlock. This wholesale conversion is required because all three of them are interdependent.
To avoid warnings in constructors, the initialization functions mark a lock as acquired when initialized before guarded variables.
The test verifies that common patterns do not generate false positives.
---
v5:
* Rename "context guard" -> "context lock".
* Use new cleanup.h helpers to properly support scoped lock guards.
v4:
* Rename capability -> context analysis.
v3:
* Switch to DECLARE_LOCK_GUARD_1_ATTRS() (suggested by Peter)
* __assert -> __assume rename
--- Documentation/dev-tools/context-analysis.rst | 3 +- include/linux/rwlock.h | 25 ++-- include/linux/rwlock_api_smp.h | 29 ++++- include/linux/rwlock_rt.h | 35 +++-- include/linux/rwlock_types.h | 10 +- include/linux/spinlock.h | 93 +++++++++++--- include/linux/spinlock_api_smp.h | 14 +- include/linux/spinlock_api_up.h | 71 +++++----- include/linux/spinlock_rt.h | 21 +-- include/linux/spinlock_types.h | 10 +- include/linux/spinlock_types_raw.h | 5 +- lib/test_context-analysis.c | 128 +++++++++++++++++++ 12 files changed, 347 insertions(+), 97 deletions(-)
Documentation/dev-tools/context-analysis.rst +2 -1
@@ -78,7 +78,8 @@ More details are also documented `here Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. Currently the following synchronization primitives are supported: +Currently the following synchronization primitives are supported: +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/rwlock.h +13 -12
@@ -22,23 +22,24 @@ do { \static struct lock_class_key __key; \ \ __rwlock_init((lock), #lock, &__key); \ + __assume_ctx_lock(lock); \ } while (0)#else # define rwlock_init (lock) \ - do { *(lock) = __RW_LOCK_UNLOCKED(lock); } while (0) + do { *(lock) = __RW_LOCK_UNLOCKED(lock); __assume_ctx_lock(lock); } while (0)#endif #ifdef CONFIG_DEBUG_SPINLOCK - extern void do_raw_read_lock(rwlock_t *lock) __acquires(lock); + extern void do_raw_read_lock(rwlock_t *lock) __acquires_shared(lock);extern int do_raw_read_trylock (rwlock_t *lock); - extern void do_raw_read_unlock(rwlock_t *lock) __releases(lock); + extern void do_raw_read_unlock(rwlock_t *lock) __releases_shared(lock); extern void do_raw_write_lock(rwlock_t *lock) __acquires(lock);extern int do_raw_write_trylock (rwlock_t *lock); extern void do_raw_write_unlock(rwlock_t *lock) __releases(lock);#else -# define do_raw_read_lock (rwlock) do {__acquire(lock); arch_read_lock(&(rwlock)->raw_lock); } while (0) +# define do_raw_read_lock (rwlock) do {__acquire_shared(lock); arch_read_lock(&(rwlock)->raw_lock); } while (0)# define do_raw_read_trylock (rwlock) arch_read_trylock(&(rwlock)->raw_lock) -# define do_raw_read_unlock (rwlock) do {arch_read_unlock(&(rwlock)->raw_lock); __release(lock); } while (0) +# define do_raw_read_unlock (rwlock) do {arch_read_unlock(&(rwlock)->raw_lock); __release_shared(lock); } while (0)# define do_raw_write_lock (rwlock) do {__acquire(lock); arch_write_lock(&(rwlock)->raw_lock); } while (0)# define do_raw_write_trylock (rwlock) arch_write_trylock(&(rwlock)->raw_lock)# define do_raw_write_unlock (rwlock) do {arch_write_unlock(&(rwlock)->raw_lock); __release(lock); } while (0)
@@ -49,7 +50,7 @@ do { \* regardless of whether CONFIG_SMP or CONFIG_PREEMPT are set. The various * methods are defined as nops in the case they are not required. */ -#define read_trylock (lock) __cond_lock(lock, _raw_read_trylock(lock)) +#define read_trylock (lock) __cond_lock_shared(lock, _raw_read_trylock(lock))#define write_trylock (lock) __cond_lock(lock, _raw_write_trylock(lock))#define write_lock (lock) _raw_write_lock(lock)
@@ -112,12 +113,12 @@ do { \ } while (0)#define write_unlock_bh (lock) _raw_write_unlock_bh(lock) -#define write_trylock_irqsave (lock, flags) \ -({ \ - local_irq_save(flags); \ - write_trylock(lock) ? \ - 1 : ({ local_irq_restore(flags); 0; }); \ -}) +#define write_trylock_irqsave (lock, flags) \ + __cond_lock(lock, ({ \ + local_irq_save(flags); \ + _raw_write_trylock(lock) ? \ + 1 : ({ local_irq_restore(flags); 0; }); \ + }))#ifdef arch_rwlock_is_contended#define rwlock_is_contended (lock) \
include/linux/rwlock_api_smp.h +23 -6
@@ -15,12 +15,12 @@* Released under the General Public License (GPL). */ -void __lockfunc _raw_read_lock(rwlock_t *lock) __acquires(lock); +void __lockfunc _raw_read_lock(rwlock_t *lock) __acquires_shared(lock); void __lockfunc _raw_write_lock(rwlock_t *lock) __acquires(lock); void __lockfunc _raw_write_lock_nested(rwlock_t *lock, int subclass) __acquires(lock); -void __lockfunc _raw_read_lock_bh(rwlock_t *lock) __acquires(lock); +void __lockfunc _raw_read_lock_bh(rwlock_t *lock) __acquires_shared(lock); void __lockfunc _raw_write_lock_bh(rwlock_t *lock) __acquires(lock); -void __lockfunc _raw_read_lock_irq(rwlock_t *lock) __acquires(lock); +void __lockfunc _raw_read_lock_irq(rwlock_t *lock) __acquires_shared(lock); void __lockfunc _raw_write_lock_irq(rwlock_t *lock) __acquires(lock); unsigned long __lockfunc _raw_read_lock_irqsave(rwlock_t *lock) __acquires(lock);
@@ -28,11 +28,11 @@ unsigned long __lockfunc _raw_write_lock_irqsave(rwlock_t *lock)__acquires (lock); int __lockfunc _raw_read_trylock(rwlock_t *lock); int __lockfunc _raw_write_trylock(rwlock_t *lock); -void __lockfunc _raw_read_unlock(rwlock_t *lock) __releases(lock); +void __lockfunc _raw_read_unlock(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock(rwlock_t *lock) __releases(lock); -void __lockfunc _raw_read_unlock_bh(rwlock_t *lock) __releases(lock); +void __lockfunc _raw_read_unlock_bh(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock_bh(rwlock_t *lock) __releases(lock); -void __lockfunc _raw_read_unlock_irq(rwlock_t *lock) __releases(lock); +void __lockfunc _raw_read_unlock_irq(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock_irq(rwlock_t *lock) __releases(lock); void __lockfunc_raw_read_unlock_irqrestore (rwlock_t *lock,unsigned long flags)
@@ -145,6 +145,7 @@ static inline int __raw_write_trylock(rwlock_t *lock)#if !defined(CONFIG_GENERIC_LOCKBREAK ) || defined(CONFIG_DEBUG_LOCK_ALLOC )static inline void __raw_read_lock (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {preempt_disable ();rwlock_acquire_read (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -152,6 +153,7 @@ static inline void __raw_read_lock(rwlock_t *lock) }static inline unsigned long __raw_read_lock_irqsave (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {unsigned long flags;
@@ -163,6 +165,7 @@ static inline unsigned long __raw_read_lock_irqsave(rwlock_t *lock) }static inline void __raw_read_lock_irq (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {local_irq_disable ();preempt_disable ();
@@ -171,6 +174,7 @@ static inline void __raw_read_lock_irq(rwlock_t *lock) }static inline void __raw_read_lock_bh (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );rwlock_acquire_read (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -178,6 +182,7 @@ static inline void __raw_read_lock_bh(rwlock_t *lock) }static inline unsigned long __raw_write_lock_irqsave (rwlock_t *lock) +__acquires (lock) __no_context_analysis {unsigned long flags;
@@ -189,6 +194,7 @@ static inline unsigned long __raw_write_lock_irqsave(rwlock_t *lock) }static inline void __raw_write_lock_irq (rwlock_t *lock) +__acquires (lock) __no_context_analysis {local_irq_disable ();preempt_disable ();
@@ -197,6 +203,7 @@ static inline void __raw_write_lock_irq(rwlock_t *lock) }static inline void __raw_write_lock_bh (rwlock_t *lock) +__acquires (lock) __no_context_analysis {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );rwlock_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -204,6 +211,7 @@ static inline void __raw_write_lock_bh(rwlock_t *lock) }static inline void __raw_write_lock (rwlock_t *lock) +__acquires (lock) __no_context_analysis {preempt_disable ();rwlock_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -211,6 +219,7 @@ static inline void __raw_write_lock(rwlock_t *lock) }static inline void __raw_write_lock_nested (rwlock_t *lock,int subclass) +__acquires (lock) __no_context_analysis {preempt_disable ();rwlock_acquire (&lock->dep_map, subclass,0 , _RET_IP_);
@@ -220,6 +229,7 @@ static inline void __raw_write_lock_nested(rwlock_t *lock, int subclass)#endif /* !CONFIG_GENERIC_LOCKBREAK || CONFIG_DEBUG_LOCK_ALLOC */ static inline void __raw_write_unlock (rwlock_t *lock) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
@@ -227,6 +237,7 @@ static inline void __raw_write_unlock(rwlock_t *lock) }static inline void __raw_read_unlock (rwlock_t *lock) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -235,6 +246,7 @@ static inline void __raw_read_unlock(rwlock_t *lock)static inline void __raw_read_unlock_irqrestore (rwlock_t *lock,unsigned long flags) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -243,6 +255,7 @@ __raw_read_unlock_irqrestore(rwlock_t *lock, unsigned long flags) }static inline void __raw_read_unlock_irq (rwlock_t *lock) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -251,6 +264,7 @@ static inline void __raw_read_unlock_irq(rwlock_t *lock) }static inline void __raw_read_unlock_bh (rwlock_t *lock) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -259,6 +273,7 @@ static inline void __raw_read_unlock_bh(rwlock_t *lock)static inline void __raw_write_unlock_irqrestore (rwlock_t *lock,unsigned long flags) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
@@ -267,6 +282,7 @@ static inline void __raw_write_unlock_irqrestore(rwlock_t *lock, }static inline void __raw_write_unlock_irq (rwlock_t *lock) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
@@ -275,6 +291,7 @@ static inline void __raw_write_unlock_irq(rwlock_t *lock) }static inline void __raw_write_unlock_bh (rwlock_t *lock) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
include/linux/rwlock_rt.h +24 -11
@@ -22,28 +22,32 @@ do { \ \init_rwbase_rt (&(rwl)->rwbase); \ __rt_rwlock_init(rwl, #rwl, &__key); \ +__assume_ctx_lock (rwl); \ }while (0 ) -extern void rt_read_lock(rwlock_t *rwlock) __acquires(rwlock); +extern void rt_read_lock(rwlock_t *rwlock) __acquires_shared(rwlock);extern int rt_read_trylock (rwlock_t *rwlock); -extern void rt_read_unlock(rwlock_t *rwlock) __releases(rwlock); +extern void rt_read_unlock(rwlock_t *rwlock) __releases_shared(rwlock); extern void rt_write_lock(rwlock_t *rwlock) __acquires(rwlock); extern void rt_write_lock_nested(rwlock_t *rwlock, int subclass) __acquires(rwlock);extern int rt_write_trylock (rwlock_t *rwlock); extern void rt_write_unlock(rwlock_t *rwlock) __releases(rwlock); static __always_inline void read_lock(rwlock_t *rwlock) +__acquires_shared (rwlock) {rt_read_lock (rwlock); } static __always_inline void read_lock_bh(rwlock_t *rwlock) +__acquires_shared (rwlock) {local_bh_disable ();rt_read_lock (rwlock); } static __always_inline void read_lock_irq(rwlock_t *rwlock) +__acquires_shared (rwlock) {rt_read_lock (rwlock); }
@@ -55,37 +59,43 @@ static __always_inline void read_lock_irq(rwlock_t *rwlock) flags =0 ; \ } while (0) -#define read_trylock (lock) __cond_lock(lock, rt_read_trylock(lock)) +#define read_trylock (lock) __cond_lock_shared(lock, rt_read_trylock(lock)) static __always_inline void read_unlock(rwlock_t *rwlock) +__releases_shared (rwlock) {rt_read_unlock (rwlock); } static __always_inline void read_unlock_bh(rwlock_t *rwlock) +__releases_shared (rwlock) {rt_read_unlock (rwlock);local_bh_enable (); } static __always_inline void read_unlock_irq(rwlock_t *rwlock) +__releases_shared (rwlock) {rt_read_unlock (rwlock); } static __always_inline void read_unlock_irqrestore(rwlock_t *rwlock,unsigned long flags) +__releases_shared (rwlock) {rt_read_unlock (rwlock); } static __always_inline void write_lock(rwlock_t *rwlock) +__acquires (rwlock) {rt_write_lock (rwlock); }#ifdef CONFIG_DEBUG_LOCK_ALLOC static __always_inline void write_lock_nested(rwlock_t *rwlock, int subclass) +__acquires (rwlock) {rt_write_lock_nested (rwlock, subclass); }
@@ -94,12 +104,14 @@ static __always_inline void write_lock_nested(rwlock_t *rwlock, int subclass)#endif static __always_inline void write_lock_bh(rwlock_t *rwlock) +__acquires (rwlock) {local_bh_disable ();rt_write_lock (rwlock); } static __always_inline void write_lock_irq(rwlock_t *rwlock) +__acquires (rwlock) {rt_write_lock (rwlock); }
@@ -114,33 +126,34 @@ static __always_inline void write_lock_irq(rwlock_t *rwlock)#define write_trylock (lock) __cond_lock(lock, rt_write_trylock(lock))#define write_trylock_irqsave (lock, flags) \ -({ \ - int __locked; \ - \ - typecheck(unsigned long, flags); \ - flags = 0; \ - __locked = write_trylock(lock); \ - __locked; \ -}) + __cond_lock(lock, ({ \ + typecheck(unsigned long, flags); \ + flags = 0; \ + rt_write_trylock(lock); \ + })) static __always_inline void write_unlock(rwlock_t *rwlock) +__releases (rwlock) {rt_write_unlock (rwlock); } static __always_inline void write_unlock_bh(rwlock_t *rwlock) +__releases (rwlock) {rt_write_unlock (rwlock);local_bh_enable (); } static __always_inline void write_unlock_irq(rwlock_t *rwlock) +__releases (rwlock) {rt_write_unlock (rwlock); } static __always_inline void write_unlock_irqrestore(rwlock_t *rwlock,unsigned long flags) +__releases (rwlock) {rt_write_unlock (rwlock); }
include/linux/rwlock_types.h +6 -4
@@ -22,7 +22,7 @@* portions Copyright 2005, Red Hat, Inc., Ingo Molnar * Released under the General Public License (GPL). */ -typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;
@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;#define RWLOCK_MAGIC 0xdeaf1eed
@@ -54,13 +55,14 @@ typedef struct {#include <linux/rwbase_rt.h> -typedef struct { +context_lock_struct (rwlock) {struct rwbase_rt rwbase;atomic_t readers;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -}rwlock_t ; +}; +typedef struct rwlock rwlock_t ;#define __RWLOCK_RT_INITIALIZER (name) \ { \
include/linux/spinlock.h +77 -16
281 lines not on this page · raw message
include/linux/spinlock_api_smp.h +12 -2
@@ -34,8 +34,8 @@ unsigned long __lockfunc _raw_spin_lock_irqsave(raw_spinlock_t *lock) unsigned long __lockfunc _raw_spin_lock_irqsave_nested(raw_spinlock_t *lock, int subclass) __acquires(lock); -int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock); -int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock); +int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock) __cond_acquires(lock); +int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock) __cond_acquires(lock); void __lockfunc _raw_spin_unlock(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock) __releases(lock);
@@ -84,6 +84,7 @@ _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags)#endif static inline int __raw_spin_trylock (raw_spinlock_t *lock) +__cond_acquires (lock) {preempt_disable ();if (do_raw_spin_trylock (lock)) {
@@ -102,6 +103,7 @@ static inline int __raw_spin_trylock(raw_spinlock_t *lock)#if !defined(CONFIG_GENERIC_LOCKBREAK ) || defined(CONFIG_DEBUG_LOCK_ALLOC )static inline unsigned long __raw_spin_lock_irqsave (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {unsigned long flags;
@@ -113,6 +115,7 @@ static inline unsigned long __raw_spin_lock_irqsave(raw_spinlock_t *lock) }static inline void __raw_spin_lock_irq (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {local_irq_disable ();preempt_disable ();
@@ -121,6 +124,7 @@ static inline void __raw_spin_lock_irq(raw_spinlock_t *lock) }static inline void __raw_spin_lock_bh (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );spin_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -128,6 +132,7 @@ static inline void __raw_spin_lock_bh(raw_spinlock_t *lock) }static inline void __raw_spin_lock (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {preempt_disable ();spin_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -137,6 +142,7 @@ static inline void __raw_spin_lock(raw_spinlock_t *lock)#endif /* !CONFIG_GENERIC_LOCKBREAK || CONFIG_DEBUG_LOCK_ALLOC */ static inline void __raw_spin_unlock (raw_spinlock_t *lock) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -145,6 +151,7 @@ static inline void __raw_spin_unlock(raw_spinlock_t *lock)static inline void __raw_spin_unlock_irqrestore (raw_spinlock_t *lock,unsigned long flags) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -153,6 +160,7 @@ static inline void __raw_spin_unlock_irqrestore(raw_spinlock_t *lock, }static inline void __raw_spin_unlock_irq (raw_spinlock_t *lock) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -161,6 +169,7 @@ static inline void __raw_spin_unlock_irq(raw_spinlock_t *lock) }static inline void __raw_spin_unlock_bh (raw_spinlock_t *lock) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -168,6 +177,7 @@ static inline void __raw_spin_unlock_bh(raw_spinlock_t *lock) }static inline int __raw_spin_trylock_bh (raw_spinlock_t *lock) +__cond_acquires (lock) {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );if (do_raw_spin_trylock (lock)) {
include/linux/spinlock_api_up.h +40 -31
108 lines not on this page · raw message
include/linux/spinlock_rt.h +13 -8
@@ -20,6 +20,7 @@ static inline void __rt_spin_lock_init(spinlock_t *lock, const char *name,do { \rt_mutex_base_init (&(slock)->lock); \__rt_spin_lock_init (slock, name, key, percpu); \ +__assume_ctx_lock (slock); \ } while (0)#define _spin_lock_init (slock, percpu) \
@@ -40,6 +41,7 @@ extern int rt_spin_trylock_bh(spinlock_t *lock);extern int rt_spin_trylock (spinlock_t *lock); static __always_inline void spin_lock(spinlock_t *lock) +__acquires (lock) {rt_spin_lock (lock); }
@@ -82,6 +84,7 @@ static __always_inline void spin_lock(spinlock_t *lock) __spin_lock_irqsave_nested(lock, flags, subclass) static __always_inline void spin_lock_bh(spinlock_t *lock) +__acquires (lock) {/* Investigate: Drop bh when blocking ? */ local_bh_disable ();
@@ -89,6 +92,7 @@ static __always_inline void spin_lock_bh(spinlock_t *lock) } static __always_inline void spin_lock_irq(spinlock_t *lock) +__acquires (lock) {rt_spin_lock (lock); }
@@ -101,23 +105,27 @@ static __always_inline void spin_lock_irq(spinlock_t *lock) }while (0 ) static __always_inline void spin_unlock(spinlock_t *lock) +__releases (lock) {rt_spin_unlock (lock); } static __always_inline void spin_unlock_bh(spinlock_t *lock) +__releases (lock) {rt_spin_unlock (lock);local_bh_enable (); } static __always_inline void spin_unlock_irq(spinlock_t *lock) +__releases (lock) {rt_spin_unlock (lock); } static __always_inline void spin_unlock_irqrestore(spinlock_t *lock,unsigned long flags) +__releases (lock) {rt_spin_unlock (lock); }
@@ -132,14 +140,11 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, __cond_lock(lock, rt_spin_trylock(lock))#define spin_trylock_irqsave (lock, flags) \ -({ \ - int __locked; \ - \ - typecheck(unsigned long, flags); \ - flags = 0; \ - __locked = spin_trylock(lock); \ - __locked; \ -}) + __cond_lock(lock, ({ \ + typecheck(unsigned long, flags); \ + flags = 0; \ + rt_spin_trylock(lock); \ + }))#define spin_is_contended (lock) (((void)(lock), 0))
include/linux/spinlock_types.h +6 -4
@@ -14,7 +14,7 @@#ifndef CONFIG_PREEMPT_RT /* Non PREEMPT_RT kernels map spinlock to raw_spinlock */ -typedef struct spinlock { +context_lock_struct (spinlock) {union { struct raw_spinlock rlock;
@@ -26,7 +26,8 @@ typedef struct spinlock { };#endif }; -} spinlock_t; +}; +typedef struct spinlock spinlock_t ;#define ___SPIN_LOCK_INITIALIZER (lockname) \ { \
@@ -47,12 +48,13 @@ typedef struct spinlock {/* PREEMPT_RT kernels map spinlock to rt_mutex */ #include <linux/rtmutex.h> -typedef struct spinlock { +context_lock_struct (spinlock) {struct rt_mutex_base lock;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -}spinlock_t ; +}; +typedef struct spinlock spinlock_t ;#define __SPIN_LOCK_UNLOCKED (name) \ { \
include/linux/spinlock_types_raw.h +3 -2
@@ -11,7 +11,7 @@#include <linux/lockdep_types.h> -typedef struct raw_spinlock { +context_lock_struct (raw_spinlock) {arch_spinlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;
@@ -20,7 +20,8 @@ typedef struct raw_spinlock {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} raw_spinlock_t; +}; +typedef struct raw_spinlock raw_spinlock_t ;#define SPINLOCK_MAGIC 0xdead4ead
lib/test_context-analysis.c +128 -0
137 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 08/36] locking/rwlock, spinlock: Support Clang's context analysis
Quoted 2 lines · Marco Elver
- extern void
do_raw_read_lock(rwlock_t *lock)__acquires(lock);
+ extern voiddo_raw_read_lock(rwlock_t *lock)__acquires_shared(lock);
Given the "one change per patch" rule, shouldn't the annotation fixes for rwlock operations be moved into a separate patch?
include/linux/rwlock_types.h typedef struct { · line 35
Quoted 12 lines
include/linux/rwlock_types.h +3
-2-typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;
This change introduces a new globally visible "struct rwlock". Although I haven't found any existing "struct rwlock" definitions, maybe it's a good idea to use a more unique name instead.
include/linux/spinlock_api_up.h line 28
Quoted 12 lines
include/linux/spinlock_api_up.h +2
-2@@ -24,68 +24,77 @@* flags straight, to suppress compiler warnings of unused lock * variables, and to add the proper checker annotations: */ -#define ___LOCK (lock) \ - do { __acquire(lock); (void)(lock); } while (0) +#define ___LOCK_void (lock) \ + do { (void)(lock); } while (0)
Instead of introducing a new macro ___LOCK_void(), please expand this macro where it is used ((void)(lock)). I think this will make the code in this header file easier to read.
include/linux/spinlock_api_up.h line 31
Quoted 4 lines
include/linux/spinlock_api_up.h +2
-2-#define __LOCK (lock) \ - do { preempt_disable(); ___LOCK(lock); } while (0) +#define ___LOCK_ (lock) \ + do { __acquire(lock); ___LOCK_void(lock); } while (0)
Is the macro ___LOCK_() used anywhere? If not, can it be left out?
include/linux/spinlock_api_up.h line 34
Quoted 4 lines
include/linux/spinlock_api_up.h +2
-2-#define __LOCK_BH (lock) \ - do { __local_bh_disable_ip(_THIS_IP_, SOFTIRQ_LOCK_OFFSET); ___LOCK(lock); } while (0) +#define ___LOCK_shared (lock) \ + do { __acquire_shared(lock); ___LOCK_void(lock); } while (0)
The introduction of the new macros in this header file make the changes hard to follow. Please consider splitting the changes for this header file as follows:
* A first patch that splits ___LOCK() into ___LOCK_exclusive() and ___LOCK_shared().
* A second patch with the thread-safety annotation changes (__acquire() -> __acquire_shared()).
include/linux/spinlock_api_up.h typedef struct spinlock { · line 30
Quoted 13 lines
include/linux/spinlock_api_up.h +3
-2/* Non PREEMPT_RT kernels map spinlock to raw_spinlock */ -typedef struct spinlock { +context_lock_struct (spinlock) {union {struct raw_spinlock rlock;@@ -26,7 +26,8 @@ typedef struct spinlock { };#endif }; -} spinlock_t; +}; +typedef struct spinlock spinlock_t ;
Also here, a new global struct name is introduced (spinlock). Maybe the name of this new struct should be made more unique?
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 08/36] locking/rwlock, spinlock: Support Clang's context analysis
Quoted 7 lines · Bart Van Assche
Quoted 2 lines · Marco Elver
- extern void
do_raw_read_lock(rwlock_t *lock)__acquires(lock);
+ extern voiddo_raw_read_lock(rwlock_t *lock)__acquires_shared(lock);Given the "one change per patch" rule, shouldn't the annotation fixes for rwlock operations be moved into a separate patch?
Quoted 16 lines
include/linux/rwlock_types.h typedef struct { · line 35
Quoted 12 lines
include/linux/rwlock_types.h +3
-2-typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;This change introduces a new globally visible "struct rwlock". Although I haven't found any existing "struct rwlock" definitions, maybe it's a good idea to use a more unique name instead.
This doesn't actually introduce a new globally visible "struct rwlock", it's already the case before.
An inlined struct definition in a typedef is available by its struct name, so this is not introducing a new name
(https://godbolt.org/z/Y1jf66e1M).
Quoted 8 lines
Quoted 8 lines
include/linux/spinlock_api_up.h +0
-0@@ -24,68 +24,77 @@* flags straight, to suppress compiler warnings of unused lock * variables, and to add the proper checker annotations: */
Quoted 8 lines
include/linux/spinlock_api_up.h line 28
Quoted 4 lines
include/linux/spinlock_api_up.h +2
-2-#define ___LOCK (lock) \ - do { __acquire(lock); (void)(lock); } while (0) +#define ___LOCK_void (lock) \ + do { (void)(lock); } while (0)Instead of introducing a new macro
___LOCK_void(), please expand this macro where it is used ((void)(lock)). I think this will make the code in this header file easier to read.
If I recall right, we needed this to generalize __LOCK(), __LOCK_IRQ(), etc. which do preempt_disable(), local_irq_disable() in the right way, but then need to make sure we call the right acquire/release helper, which require different cases depending on the lock kind. Obviously we could just expand all the macros below, but the current pattern tried to not rewrite this altogether.
There's probably a way this can all be simplified for UP, but maybe a separate patch. I'd leave it to the locking maintainers which way they prefer to go.
Quoted 6 lines
include/linux/spinlock_api_up.h line 31
Quoted 4 lines
include/linux/spinlock_api_up.h +2
-2-#define __LOCK (lock) \ - do { preempt_disable(); ___LOCK(lock); } while (0) +#define ___LOCK_ (lock) \ + do { __acquire(lock); ___LOCK_void(lock); } while (0)Is the macro
___LOCK_()used anywhere? If not, can it be left out?
Yes, it's the default case if __VA_ARGS__ is empty.
Quoted 5 lines
include/linux/spinlock_api_up.h line 34
Quoted 4 lines
include/linux/spinlock_api_up.h +2
-2-#define __LOCK_BH (lock) \ - do { __local_bh_disable_ip(_THIS_IP_, SOFTIRQ_LOCK_OFFSET); ___LOCK(lock); } while (0) +#define ___LOCK_shared (lock) \ + do { __acquire_shared(lock); ___LOCK_void(lock); } while (0)
Quoted 7 lines
The introduction of the new macros in this header file make the changes hard to follow. Please consider splitting the changes for this header file as follows:
* A first patch that splits___LOCK()into___LOCK_exclusive()and___LOCK_shared().
* A second patch with the thread-safety annotation changes (__acquire()->__acquire_shared()).
I've wrangled with this maze of interdependent macros and definitions for days (though that was earlier in the year), believe me when I say I tried to split it up. I think the commit message hints at this:
Quoted 3 lines
Add support for Clang's context analysis for
raw_spinlock_t,spinlock_t, and rwlock. This wholesale conversion is required because all three of them are interdependent.
It's like a carefully crafted house of cards: you take one away, the whole thing breaks apart. If I recall correctly, the main problem was that as soon as you make one of these a context lock type, and because they are all interdependent, the compiler will just complain endlessly about either wrong attributes or incorrectly acquired/released locks until they are all precisely in the way you see them here.
Quoted 6 lines
Quoted 6 lines
include/linux/spinlock_api_up.h +1
-1/* Non PREEMPT_RT kernels map spinlock to raw_spinlock */ -typedef struct spinlock { +context_lock_struct (spinlock) {union {struct raw_spinlock rlock;
Quoted 10 lines
include/linux/spinlock_api_up.h typedef struct spinlock { · line 30
Quoted 7 lines
include/linux/spinlock_api_up.h +2
-1@@ -26,7 +26,8 @@ typedef struct spinlock { };#endif }; -} spinlock_t; +}; +typedef struct spinlock spinlock_t ;Also here, a new global struct name is introduced (spinlock). Maybe the name of this new struct should be made more unique?
As above.
Re: [PATCH v5 08/36] locking/rwlock, spinlock: Support Clang's context analysis
Quoted 25 lines · Marco Elver
Quoted 7 lines · Bart Van Assche
Quoted 2 lines · Marco Elver
- extern void
do_raw_read_lock(rwlock_t *lock)__acquires(lock);
+ extern voiddo_raw_read_lock(rwlock_t *lock)__acquires_shared(lock);Given the "one change per patch" rule, shouldn't the annotation fixes for rwlock operations be moved into a separate patch?
Quoted 16 lines
include/linux/rwlock_types.h typedef struct { · line 35
Quoted 12 lines
include/linux/rwlock_types.h +3
-2-typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;This change introduces a new globally visible "struct rwlock". Although I haven't found any existing "struct rwlock" definitions, maybe it's a good idea to use a more unique name instead.
Quoted 5 lines
This doesn't actually introduce a new globally visible "struct rwlock", it's already the case before.
An inlined struct definition in a typedef is available by its struct name, so this is not introducing a new name
(https://godbolt.org/z/Y1jf66e1M).
Please take another look. The godbolt example follows the pattern "typedef struct name { ... } name_t;". The "name" part is missing from the rwlock_t definition. This is why I wrote that the above code introduces a new global struct name.
Bart.
Marco Elver
maintainerRe: [PATCH v5 08/36] locking/rwlock, spinlock: Support Clang's context analysis
Quoted 33 lines · Bart Van Assche
Quoted 25 lines · Marco Elver
Quoted 7 lines · Bart Van Assche
Quoted 2 lines · Marco Elver
- extern void
do_raw_read_lock(rwlock_t *lock)__acquires(lock);
+ extern voiddo_raw_read_lock(rwlock_t *lock)__acquires_shared(lock);Given the "one change per patch" rule, shouldn't the annotation fixes for rwlock operations be moved into a separate patch?
Quoted 16 lines
include/linux/rwlock_types.h typedef struct { · line 35
Quoted 12 lines
include/linux/rwlock_types.h +3
-2-typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;This change introduces a new globally visible "struct rwlock". Although I haven't found any existing "struct rwlock" definitions, maybe it's a good idea to use a more unique name instead.
Quoted 5 lines
This doesn't actually introduce a new globally visible "struct rwlock", it's already the case before.
An inlined struct definition in a typedef is available by its struct name, so this is not introducing a new name
(https://godbolt.org/z/Y1jf66e1M).
Quoted 4 lines
Please take another look. The godbolt example follows the pattern "typedef struct name { ... }
name_t;". The "name" part is missing from therwlock_tdefinition. This is why I wrote that the above code introduces a new global struct name.
You're right. My point only applies to "typedef struct spinlock ..."
Re: [PATCH v5 08/36] locking/rwlock, spinlock: Support Clang's context analysis
In reply to Marco ElverQuoted 25 lines · Marco Elver
Quoted 7 lines · Bart Van Assche
Quoted 2 lines · Marco Elver
- extern void
do_raw_read_lock(rwlock_t *lock)__acquires(lock);
+ extern voiddo_raw_read_lock(rwlock_t *lock)__acquires_shared(lock);Given the "one change per patch" rule, shouldn't the annotation fixes for rwlock operations be moved into a separate patch?
Quoted 16 lines
include/linux/rwlock_types.h typedef struct { · line 35
Quoted 12 lines
include/linux/rwlock_types.h +3
-2-typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;This change introduces a new globally visible "struct rwlock". Although I haven't found any existing "struct rwlock" definitions, maybe it's a good idea to use a more unique name instead.
Quoted 5 lines
This doesn't actually introduce a new globally visible "struct rwlock", it's already the case before.
An inlined struct definition in a typedef is available by its struct name, so this is not introducing a new name
(https://godbolt.org/z/Y1jf66e1M).
Please take another look. The godbolt example follows the pattern "typedef struct name { ... } name_t;". The "name" part is missing from the rwlock_t definition. This is why I wrote that the above code introduces a new global struct name.
Bart.
[tip: locking/core] locking/rwlock, spinlock: Support Clang's context analysis
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: f16a802d402d735a55731f8c94952b3bbb5ddfe8 Gitweb: https://git.kernel.org/tip/f16a802d402d735a55731f8c94952b3bbb5ddfe8 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:57 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:28 +01:00
locking/rwlock, spinlock: Support Clang's context analysis
Add support for Clang's context analysis for raw_spinlock_t, spinlock_t, and rwlock. This wholesale conversion is required because all three of them are interdependent.
To avoid warnings in constructors, the initialization functions mark a lock as acquired when initialized before guarded variables.
The test verifies that common patterns do not generate false positives.
--- Documentation/dev-tools/context-analysis.rst | 3 +- include/linux/rwlock.h | 25 ++-- include/linux/rwlock_api_smp.h | 29 +++- include/linux/rwlock_rt.h | 35 +++-- include/linux/rwlock_types.h | 10 +- include/linux/spinlock.h | 93 ++++++++++--- include/linux/spinlock_api_smp.h | 14 +- include/linux/spinlock_api_up.h | 71 +++++----- include/linux/spinlock_rt.h | 21 +-- include/linux/spinlock_types.h | 10 +- include/linux/spinlock_types_raw.h | 5 +- lib/test_context-analysis.c | 128 ++++++++++++++++++- 12 files changed, 347 insertions(+), 97 deletions(-)
Documentation/dev-tools/context-analysis.rst +2 -1
@@ -78,7 +78,8 @@ More details are also documented `here Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. Currently the following synchronization primitives are supported: +Currently the following synchronization primitives are supported: +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/rwlock.h +13 -12
@@ -22,23 +22,24 @@ do { \static struct lock_class_key __key; \ \ __rwlock_init((lock), #lock, &__key); \ + __assume_ctx_lock(lock); \ } while (0)#else # define rwlock_init (lock) \ - do { *(lock) = __RW_LOCK_UNLOCKED(lock); } while (0) + do { *(lock) = __RW_LOCK_UNLOCKED(lock); __assume_ctx_lock(lock); } while (0)#endif #ifdef CONFIG_DEBUG_SPINLOCK - extern void do_raw_read_lock(rwlock_t *lock) __acquires(lock); + extern void do_raw_read_lock(rwlock_t *lock) __acquires_shared(lock);extern int do_raw_read_trylock (rwlock_t *lock); - extern void do_raw_read_unlock(rwlock_t *lock) __releases(lock); + extern void do_raw_read_unlock(rwlock_t *lock) __releases_shared(lock); extern void do_raw_write_lock(rwlock_t *lock) __acquires(lock);extern int do_raw_write_trylock (rwlock_t *lock); extern void do_raw_write_unlock(rwlock_t *lock) __releases(lock);#else -# define do_raw_read_lock (rwlock) do {__acquire(lock); arch_read_lock(&(rwlock)->raw_lock); } while (0) +# define do_raw_read_lock (rwlock) do {__acquire_shared(lock); arch_read_lock(&(rwlock)->raw_lock); } while (0)# define do_raw_read_trylock (rwlock) arch_read_trylock(&(rwlock)->raw_lock) -# define do_raw_read_unlock (rwlock) do {arch_read_unlock(&(rwlock)->raw_lock); __release(lock); } while (0) +# define do_raw_read_unlock (rwlock) do {arch_read_unlock(&(rwlock)->raw_lock); __release_shared(lock); } while (0)# define do_raw_write_lock (rwlock) do {__acquire(lock); arch_write_lock(&(rwlock)->raw_lock); } while (0)# define do_raw_write_trylock (rwlock) arch_write_trylock(&(rwlock)->raw_lock)# define do_raw_write_unlock (rwlock) do {arch_write_unlock(&(rwlock)->raw_lock); __release(lock); } while (0)
@@ -49,7 +50,7 @@ do { \* regardless of whether CONFIG_SMP or CONFIG_PREEMPT are set. The various * methods are defined as nops in the case they are not required. */ -#define read_trylock (lock) __cond_lock(lock, _raw_read_trylock(lock)) +#define read_trylock (lock) __cond_lock_shared(lock, _raw_read_trylock(lock))#define write_trylock (lock) __cond_lock(lock, _raw_write_trylock(lock))#define write_lock (lock) _raw_write_lock(lock)
@@ -112,12 +113,12 @@ do { \ } while (0)#define write_unlock_bh (lock) _raw_write_unlock_bh(lock) -#define write_trylock_irqsave (lock, flags) \ -({ \ - local_irq_save(flags); \ - write_trylock(lock) ? \ - 1 : ({ local_irq_restore(flags); 0; }); \ -}) +#define write_trylock_irqsave (lock, flags) \ + __cond_lock(lock, ({ \ + local_irq_save(flags); \ + _raw_write_trylock(lock) ? \ + 1 : ({ local_irq_restore(flags); 0; }); \ + }))#ifdef arch_rwlock_is_contended#define rwlock_is_contended (lock) \
include/linux/rwlock_api_smp.h +23 -6
@@ -15,12 +15,12 @@* Released under the General Public License (GPL). */ -void __lockfunc _raw_read_lock(rwlock_t *lock) __acquires(lock); +void __lockfunc _raw_read_lock(rwlock_t *lock) __acquires_shared(lock); void __lockfunc _raw_write_lock(rwlock_t *lock) __acquires(lock); void __lockfunc _raw_write_lock_nested(rwlock_t *lock, int subclass) __acquires(lock); -void __lockfunc _raw_read_lock_bh(rwlock_t *lock) __acquires(lock); +void __lockfunc _raw_read_lock_bh(rwlock_t *lock) __acquires_shared(lock); void __lockfunc _raw_write_lock_bh(rwlock_t *lock) __acquires(lock); -void __lockfunc _raw_read_lock_irq(rwlock_t *lock) __acquires(lock); +void __lockfunc _raw_read_lock_irq(rwlock_t *lock) __acquires_shared(lock); void __lockfunc _raw_write_lock_irq(rwlock_t *lock) __acquires(lock); unsigned long __lockfunc _raw_read_lock_irqsave(rwlock_t *lock) __acquires(lock);
@@ -28,11 +28,11 @@ unsigned long __lockfunc _raw_write_lock_irqsave(rwlock_t *lock)__acquires (lock); int __lockfunc _raw_read_trylock(rwlock_t *lock); int __lockfunc _raw_write_trylock(rwlock_t *lock); -void __lockfunc _raw_read_unlock(rwlock_t *lock) __releases(lock); +void __lockfunc _raw_read_unlock(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock(rwlock_t *lock) __releases(lock); -void __lockfunc _raw_read_unlock_bh(rwlock_t *lock) __releases(lock); +void __lockfunc _raw_read_unlock_bh(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock_bh(rwlock_t *lock) __releases(lock); -void __lockfunc _raw_read_unlock_irq(rwlock_t *lock) __releases(lock); +void __lockfunc _raw_read_unlock_irq(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock_irq(rwlock_t *lock) __releases(lock); void __lockfunc_raw_read_unlock_irqrestore (rwlock_t *lock,unsigned long flags)
@@ -145,6 +145,7 @@ static inline int __raw_write_trylock(rwlock_t *lock)#if !defined(CONFIG_GENERIC_LOCKBREAK ) || defined(CONFIG_DEBUG_LOCK_ALLOC )static inline void __raw_read_lock (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {preempt_disable ();rwlock_acquire_read (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -152,6 +153,7 @@ static inline void __raw_read_lock(rwlock_t *lock) }static inline unsigned long __raw_read_lock_irqsave (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {unsigned long flags;
@@ -163,6 +165,7 @@ static inline unsigned long __raw_read_lock_irqsave(rwlock_t *lock) }static inline void __raw_read_lock_irq (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {local_irq_disable ();preempt_disable ();
@@ -171,6 +174,7 @@ static inline void __raw_read_lock_irq(rwlock_t *lock) }static inline void __raw_read_lock_bh (rwlock_t *lock) +__acquires_shared (lock) __no_context_analysis {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );rwlock_acquire_read (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -178,6 +182,7 @@ static inline void __raw_read_lock_bh(rwlock_t *lock) }static inline unsigned long __raw_write_lock_irqsave (rwlock_t *lock) +__acquires (lock) __no_context_analysis {unsigned long flags;
@@ -189,6 +194,7 @@ static inline unsigned long __raw_write_lock_irqsave(rwlock_t *lock) }static inline void __raw_write_lock_irq (rwlock_t *lock) +__acquires (lock) __no_context_analysis {local_irq_disable ();preempt_disable ();
@@ -197,6 +203,7 @@ static inline void __raw_write_lock_irq(rwlock_t *lock) }static inline void __raw_write_lock_bh (rwlock_t *lock) +__acquires (lock) __no_context_analysis {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );rwlock_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -204,6 +211,7 @@ static inline void __raw_write_lock_bh(rwlock_t *lock) }static inline void __raw_write_lock (rwlock_t *lock) +__acquires (lock) __no_context_analysis {preempt_disable ();rwlock_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -211,6 +219,7 @@ static inline void __raw_write_lock(rwlock_t *lock) }static inline void __raw_write_lock_nested (rwlock_t *lock,int subclass) +__acquires (lock) __no_context_analysis {preempt_disable ();rwlock_acquire (&lock->dep_map, subclass,0 , _RET_IP_);
@@ -220,6 +229,7 @@ static inline void __raw_write_lock_nested(rwlock_t *lock, int subclass)#endif /* !CONFIG_GENERIC_LOCKBREAK || CONFIG_DEBUG_LOCK_ALLOC */ static inline void __raw_write_unlock (rwlock_t *lock) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
@@ -227,6 +237,7 @@ static inline void __raw_write_unlock(rwlock_t *lock) }static inline void __raw_read_unlock (rwlock_t *lock) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -235,6 +246,7 @@ static inline void __raw_read_unlock(rwlock_t *lock)static inline void __raw_read_unlock_irqrestore (rwlock_t *lock,unsigned long flags) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -243,6 +255,7 @@ __raw_read_unlock_irqrestore(rwlock_t *lock, unsigned long flags) }static inline void __raw_read_unlock_irq (rwlock_t *lock) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -251,6 +264,7 @@ static inline void __raw_read_unlock_irq(rwlock_t *lock) }static inline void __raw_read_unlock_bh (rwlock_t *lock) +__releases_shared (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_read_unlock (lock);
@@ -259,6 +273,7 @@ static inline void __raw_read_unlock_bh(rwlock_t *lock)static inline void __raw_write_unlock_irqrestore (rwlock_t *lock,unsigned long flags) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
@@ -267,6 +282,7 @@ static inline void __raw_write_unlock_irqrestore(rwlock_t *lock, }static inline void __raw_write_unlock_irq (rwlock_t *lock) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
@@ -275,6 +291,7 @@ static inline void __raw_write_unlock_irq(rwlock_t *lock) }static inline void __raw_write_unlock_bh (rwlock_t *lock) +__releases (lock) {rwlock_release (&lock->dep_map, _RET_IP_);do_raw_write_unlock (lock);
include/linux/rwlock_rt.h +24 -11
@@ -22,28 +22,32 @@ do { \ \init_rwbase_rt (&(rwl)->rwbase); \ __rt_rwlock_init(rwl, #rwl, &__key); \ +__assume_ctx_lock (rwl); \ }while (0 ) -extern void rt_read_lock(rwlock_t *rwlock) __acquires(rwlock); +extern void rt_read_lock(rwlock_t *rwlock) __acquires_shared(rwlock);extern int rt_read_trylock (rwlock_t *rwlock); -extern void rt_read_unlock(rwlock_t *rwlock) __releases(rwlock); +extern void rt_read_unlock(rwlock_t *rwlock) __releases_shared(rwlock); extern void rt_write_lock(rwlock_t *rwlock) __acquires(rwlock); extern void rt_write_lock_nested(rwlock_t *rwlock, int subclass) __acquires(rwlock);extern int rt_write_trylock (rwlock_t *rwlock); extern void rt_write_unlock(rwlock_t *rwlock) __releases(rwlock); static __always_inline void read_lock(rwlock_t *rwlock) +__acquires_shared (rwlock) {rt_read_lock (rwlock); } static __always_inline void read_lock_bh(rwlock_t *rwlock) +__acquires_shared (rwlock) {local_bh_disable ();rt_read_lock (rwlock); } static __always_inline void read_lock_irq(rwlock_t *rwlock) +__acquires_shared (rwlock) {rt_read_lock (rwlock); }
@@ -55,37 +59,43 @@ static __always_inline void read_lock_irq(rwlock_t *rwlock) flags =0 ; \ } while (0) -#define read_trylock (lock) __cond_lock(lock, rt_read_trylock(lock)) +#define read_trylock (lock) __cond_lock_shared(lock, rt_read_trylock(lock)) static __always_inline void read_unlock(rwlock_t *rwlock) +__releases_shared (rwlock) {rt_read_unlock (rwlock); } static __always_inline void read_unlock_bh(rwlock_t *rwlock) +__releases_shared (rwlock) {rt_read_unlock (rwlock);local_bh_enable (); } static __always_inline void read_unlock_irq(rwlock_t *rwlock) +__releases_shared (rwlock) {rt_read_unlock (rwlock); } static __always_inline void read_unlock_irqrestore(rwlock_t *rwlock,unsigned long flags) +__releases_shared (rwlock) {rt_read_unlock (rwlock); } static __always_inline void write_lock(rwlock_t *rwlock) +__acquires (rwlock) {rt_write_lock (rwlock); }#ifdef CONFIG_DEBUG_LOCK_ALLOC static __always_inline void write_lock_nested(rwlock_t *rwlock, int subclass) +__acquires (rwlock) {rt_write_lock_nested (rwlock, subclass); }
@@ -94,12 +104,14 @@ static __always_inline void write_lock_nested(rwlock_t *rwlock, int subclass)#endif static __always_inline void write_lock_bh(rwlock_t *rwlock) +__acquires (rwlock) {local_bh_disable ();rt_write_lock (rwlock); } static __always_inline void write_lock_irq(rwlock_t *rwlock) +__acquires (rwlock) {rt_write_lock (rwlock); }
@@ -114,33 +126,34 @@ static __always_inline void write_lock_irq(rwlock_t *rwlock)#define write_trylock (lock) __cond_lock(lock, rt_write_trylock(lock))#define write_trylock_irqsave (lock, flags) \ -({ \ - int __locked; \ - \ - typecheck(unsigned long, flags); \ - flags = 0; \ - __locked = write_trylock(lock); \ - __locked; \ -}) + __cond_lock(lock, ({ \ + typecheck(unsigned long, flags); \ + flags = 0; \ + rt_write_trylock(lock); \ + })) static __always_inline void write_unlock(rwlock_t *rwlock) +__releases (rwlock) {rt_write_unlock (rwlock); } static __always_inline void write_unlock_bh(rwlock_t *rwlock) +__releases (rwlock) {rt_write_unlock (rwlock);local_bh_enable (); } static __always_inline void write_unlock_irq(rwlock_t *rwlock) +__releases (rwlock) {rt_write_unlock (rwlock); } static __always_inline void write_unlock_irqrestore(rwlock_t *rwlock,unsigned long flags) +__releases (rwlock) {rt_write_unlock (rwlock); }
include/linux/rwlock_types.h +6 -4
@@ -22,7 +22,7 @@* portions Copyright 2005, Red Hat, Inc., Ingo Molnar * Released under the General Public License (GPL). */ -typedef struct { +context_lock_struct (rwlock) {arch_rwlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;
@@ -31,7 +31,8 @@ typedef struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} rwlock_t; +}; +typedef struct rwlock rwlock_t ;#define RWLOCK_MAGIC 0xdeaf1eed
@@ -54,13 +55,14 @@ typedef struct {#include <linux/rwbase_rt.h> -typedef struct { +context_lock_struct (rwlock) {struct rwbase_rt rwbase;atomic_t readers;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -}rwlock_t ; +}; +typedef struct rwlock rwlock_t ;#define __RWLOCK_RT_INITIALIZER (name) \ { \
include/linux/spinlock.h +77 -16
281 lines not on this page · raw message
include/linux/spinlock_api_smp.h +12 -2
@@ -34,8 +34,8 @@ unsigned long __lockfunc _raw_spin_lock_irqsave(raw_spinlock_t *lock) unsigned long __lockfunc _raw_spin_lock_irqsave_nested(raw_spinlock_t *lock, int subclass) __acquires(lock); -int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock); -int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock); +int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock) __cond_acquires(lock); +int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock) __cond_acquires(lock); void __lockfunc _raw_spin_unlock(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock) __releases(lock);
@@ -84,6 +84,7 @@ _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags)#endif static inline int __raw_spin_trylock (raw_spinlock_t *lock) +__cond_acquires (lock) {preempt_disable ();if (do_raw_spin_trylock (lock)) {
@@ -102,6 +103,7 @@ static inline int __raw_spin_trylock(raw_spinlock_t *lock)#if !defined(CONFIG_GENERIC_LOCKBREAK ) || defined(CONFIG_DEBUG_LOCK_ALLOC )static inline unsigned long __raw_spin_lock_irqsave (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {unsigned long flags;
@@ -113,6 +115,7 @@ static inline unsigned long __raw_spin_lock_irqsave(raw_spinlock_t *lock) }static inline void __raw_spin_lock_irq (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {local_irq_disable ();preempt_disable ();
@@ -121,6 +124,7 @@ static inline void __raw_spin_lock_irq(raw_spinlock_t *lock) }static inline void __raw_spin_lock_bh (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );spin_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -128,6 +132,7 @@ static inline void __raw_spin_lock_bh(raw_spinlock_t *lock) }static inline void __raw_spin_lock (raw_spinlock_t *lock) +__acquires (lock) __no_context_analysis {preempt_disable ();spin_acquire (&lock->dep_map,0 ,0 , _RET_IP_);
@@ -137,6 +142,7 @@ static inline void __raw_spin_lock(raw_spinlock_t *lock)#endif /* !CONFIG_GENERIC_LOCKBREAK || CONFIG_DEBUG_LOCK_ALLOC */ static inline void __raw_spin_unlock (raw_spinlock_t *lock) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -145,6 +151,7 @@ static inline void __raw_spin_unlock(raw_spinlock_t *lock)static inline void __raw_spin_unlock_irqrestore (raw_spinlock_t *lock,unsigned long flags) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -153,6 +160,7 @@ static inline void __raw_spin_unlock_irqrestore(raw_spinlock_t *lock, }static inline void __raw_spin_unlock_irq (raw_spinlock_t *lock) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -161,6 +169,7 @@ static inline void __raw_spin_unlock_irq(raw_spinlock_t *lock) }static inline void __raw_spin_unlock_bh (raw_spinlock_t *lock) +__releases (lock) {spin_release (&lock->dep_map, _RET_IP_);do_raw_spin_unlock (lock);
@@ -168,6 +177,7 @@ static inline void __raw_spin_unlock_bh(raw_spinlock_t *lock) }static inline int __raw_spin_trylock_bh (raw_spinlock_t *lock) +__cond_acquires (lock) {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );if (do_raw_spin_trylock (lock)) {
include/linux/spinlock_api_up.h +40 -31
108 lines not on this page · raw message
include/linux/spinlock_rt.h +13 -8
@@ -20,6 +20,7 @@ static inline void __rt_spin_lock_init(spinlock_t *lock, const char *name,do { \rt_mutex_base_init (&(slock)->lock); \__rt_spin_lock_init (slock, name, key, percpu); \ +__assume_ctx_lock (slock); \ } while (0)#define _spin_lock_init (slock, percpu) \
@@ -40,6 +41,7 @@ extern int rt_spin_trylock_bh(spinlock_t *lock);extern int rt_spin_trylock (spinlock_t *lock); static __always_inline void spin_lock(spinlock_t *lock) +__acquires (lock) {rt_spin_lock (lock); }
@@ -82,6 +84,7 @@ static __always_inline void spin_lock(spinlock_t *lock) __spin_lock_irqsave_nested(lock, flags, subclass) static __always_inline void spin_lock_bh(spinlock_t *lock) +__acquires (lock) {/* Investigate: Drop bh when blocking ? */ local_bh_disable ();
@@ -89,6 +92,7 @@ static __always_inline void spin_lock_bh(spinlock_t *lock) } static __always_inline void spin_lock_irq(spinlock_t *lock) +__acquires (lock) {rt_spin_lock (lock); }
@@ -101,23 +105,27 @@ static __always_inline void spin_lock_irq(spinlock_t *lock) }while (0 ) static __always_inline void spin_unlock(spinlock_t *lock) +__releases (lock) {rt_spin_unlock (lock); } static __always_inline void spin_unlock_bh(spinlock_t *lock) +__releases (lock) {rt_spin_unlock (lock);local_bh_enable (); } static __always_inline void spin_unlock_irq(spinlock_t *lock) +__releases (lock) {rt_spin_unlock (lock); } static __always_inline void spin_unlock_irqrestore(spinlock_t *lock,unsigned long flags) +__releases (lock) {rt_spin_unlock (lock); }
@@ -132,14 +140,11 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, __cond_lock(lock, rt_spin_trylock(lock))#define spin_trylock_irqsave (lock, flags) \ -({ \ - int __locked; \ - \ - typecheck(unsigned long, flags); \ - flags = 0; \ - __locked = spin_trylock(lock); \ - __locked; \ -}) + __cond_lock(lock, ({ \ + typecheck(unsigned long, flags); \ + flags = 0; \ + rt_spin_trylock(lock); \ + }))#define spin_is_contended (lock) (((void)(lock), 0))
include/linux/spinlock_types.h +6 -4
@@ -14,7 +14,7 @@#ifndef CONFIG_PREEMPT_RT /* Non PREEMPT_RT kernels map spinlock to raw_spinlock */ -typedef struct spinlock { +context_lock_struct (spinlock) {union { struct raw_spinlock rlock;
@@ -26,7 +26,8 @@ typedef struct spinlock { };#endif }; -} spinlock_t; +}; +typedef struct spinlock spinlock_t ;#define ___SPIN_LOCK_INITIALIZER (lockname) \ { \
@@ -47,12 +48,13 @@ typedef struct spinlock {/* PREEMPT_RT kernels map spinlock to rt_mutex */ #include <linux/rtmutex.h> -typedef struct spinlock { +context_lock_struct (spinlock) {struct rt_mutex_base lock;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -}spinlock_t ; +}; +typedef struct spinlock spinlock_t ;#define __SPIN_LOCK_UNLOCKED (name) \ { \
include/linux/spinlock_types_raw.h +3 -2
@@ -11,7 +11,7 @@#include <linux/lockdep_types.h> -typedef struct raw_spinlock { +context_lock_struct (raw_spinlock) {arch_spinlock_t raw_lock;#ifdef CONFIG_DEBUG_SPINLOCK unsigned int magic, owner_cpu;
@@ -20,7 +20,8 @@ typedef struct raw_spinlock {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif -} raw_spinlock_t; +}; +typedef struct raw_spinlock raw_spinlock_t ;#define SPINLOCK_MAGIC 0xdead4ead
lib/test_context-analysis.c +128 -0
137 lines not on this page · raw message
Marco Elver
maintainerPATCH v5 9/36 compiler-context-analysis: Change __cond_acquires to take return value
In reply to Marco ElverWhile Sparse is oblivious to the return value of conditional acquire functions, Clang's context analysis needs to know the return value which indicates successful acquisition.
Add the additional argument, and convert existing uses.
Notably, Clang's interpretation of the value merely relates to the use in a later conditional branch, i.e. 1 ==> context lock acquired in branch taken if condition non-zero, and 0 ==> context lock acquired in branch taken if condition is zero. Given the precise value does not matter, introduce symbolic variants to use instead of either 0 or 1, which should be more intuitive.
No functional change intended.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
v2:
* Use symbolic values for __cond_acquires() and __cond_acquires_shared() (suggested by Bart).
--- fs/dlm/lock.c | 2 +- include/linux/compiler-context-analysis.h | 31 +++++++++++++++++++---- include/linux/refcount.h | 6 ++--- include/linux/spinlock.h | 6 ++--- include/linux/spinlock_api_smp.h | 8 +++--- net/ipv4/tcp_sigpool.c | 2 +- 6 files changed, 38 insertions(+), 17 deletions(-)
fs/dlm/lock.c +1 -1
@@ -343,7 +343,7 @@ void dlm_hold_rsb(struct dlm_rsb *r)/* TODO move this to lib/refcount.c */ static __must_check bool dlm_refcount_dec_and_write_lock_bh (refcount_t *r,rwlock_t *lock) -__cond_acquires (lock) +__cond_acquires (true, lock) {if (refcount_dec_not_one (r))return false;
include/linux/compiler-context-analysis.h +26 -5
@@ -271,7 +271,7 @@ static inline void _context_unsafe_alias(void **p) { }# define __must_hold (x) __attribute__((context(x,1,1)))# define __must_not_hold (x)# define __acquires (x) __attribute__((context(x,0,1))) -# define __cond_acquires (x) __attribute__((context(x,0,-1))) +# define __cond_acquires (ret, x) __attribute__((context(x,0,-1)))# define __releases (x) __attribute__((context(x,1,0)))# define __acquire (x) __context__(x,1)# define __release (x) __context__(x,-1)
@@ -314,15 +314,32 @@ static inline void _context_unsafe_alias(void **p) { }*/ # define __acquires (x) __acquires_ctx_lock(x) +/* +* Clang's analysis does not care precisely about the value, only that it is +* either zero or non-zero. So the __cond_acquires() interface might be +* misleading if we say that @ret is the value returned if acquired. Instead, +* provide symbolic variants which we translate. +*/ +#define __cond_acquires_impl_true (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(1, x) +#define __cond_acquires_impl_false (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(0, x) +#define __cond_acquires_impl_nonzero (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(1, x) +#define __cond_acquires_impl_0 (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(0, x) +#define __cond_acquires_impl_nonnull (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(1, x) +#define __cond_acquires_impl_NULL (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(0, x) +/** * __cond_acquires() - function attribute, function conditionally * acquires a context lock exclusively +* @ret: abstract value returned by function if context lock acquired * @x: context lock instance pointer * * Function attribute declaring that the function conditionally acquires the -* given context lock instance @x exclusively, but does not release it. +* given context lock instance @x exclusively, but does not release it. The +* function return value @ret denotes when the context lock is acquired. +* +* @ret may be one of: true, false, nonzero, 0, nonnull, NULL. */ -# define __cond_acquires (x) __try_acquires_ctx_lock(1, x) +# define __cond_acquires (ret, x) __cond_acquires_impl_##ret(x)/** * __releases() - function attribute, function releases a context lock exclusively
@@ -389,12 +406,16 @@ static inline void _context_unsafe_alias(void **p) { }/** * __cond_acquires_shared() - function attribute, function conditionally * acquires a context lock shared +* @ret: abstract value returned by function if context lock acquired * @x: context lock instance pointer * * Function attribute declaring that the function conditionally acquires the -* given context lock instance @x with shared access, but does not release it. +* given context lock instance @x with shared access, but does not release it. The +* function return value @ret denotes when the context lock is acquired. +* +* @ret may be one of: true, false, nonzero, 0, nonnull, NULL. */ -# define __cond_acquires_shared (x) __try_acquires_shared_ctx_lock(1, x) +# define __cond_acquires_shared (ret, x) __cond_acquires_impl_##ret(x, _shared)/** * __releases_shared() - function attribute, function releases a
include/linux/refcount.h +3 -3
@@ -478,9 +478,9 @@ static inline void refcount_dec(refcount_t *r)extern __must_check bool refcount_dec_if_one (refcount_t *r);extern __must_check bool refcount_dec_not_one (refcount_t *r); -extern __must_check bool refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock) __cond_acquires(lock); -extern __must_check bool refcount_dec_and_lock(refcount_t *r, spinlock_t *lock) __cond_acquires(lock); +extern __must_check bool refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock) __cond_acquires(true, lock); +extern __must_check bool refcount_dec_and_lock(refcount_t *r, spinlock_t *lock) __cond_acquires(true, lock); extern __must_check bool refcount_dec_and_lock_irqsave(refcount_t *r, spinlock_t *lock, - unsigned long *flags) __cond_acquires(lock); + unsigned long *flags) __cond_acquires(true, lock);#endif /* _LINUX_REFCOUNT_H */
include/linux/spinlock.h +3 -3
@@ -362,7 +362,7 @@ static __always_inline void spin_lock_bh(spinlock_t *lock) } static __always_inline int spin_trylock(spinlock_t *lock) -__cond_acquires (lock) __no_context_analysis +__cond_acquires (true, lock) __no_context_analysis {return raw_spin_trylock (&lock->rlock); }
@@ -422,13 +422,13 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, unsigned lo } static __always_inline int spin_trylock_bh(spinlock_t *lock) -__cond_acquires (lock) __no_context_analysis +__cond_acquires (true, lock) __no_context_analysis {return raw_spin_trylock_bh (&lock->rlock); } static __always_inline int spin_trylock_irq(spinlock_t *lock) -__cond_acquires (lock) __no_context_analysis +__cond_acquires (true, lock) __no_context_analysis {return raw_spin_trylock_irq (&lock->rlock); }
include/linux/spinlock_api_smp.h +4 -4
@@ -34,8 +34,8 @@ unsigned long __lockfunc _raw_spin_lock_irqsave(raw_spinlock_t *lock) unsigned long __lockfunc _raw_spin_lock_irqsave_nested(raw_spinlock_t *lock, int subclass) __acquires(lock); -int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock) __cond_acquires(lock); -int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock) __cond_acquires(lock); +int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock) __cond_acquires(true, lock); +int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock) __cond_acquires(true, lock); void __lockfunc _raw_spin_unlock(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock) __releases(lock);
@@ -84,7 +84,7 @@ _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags)#endif static inline int __raw_spin_trylock (raw_spinlock_t *lock) -__cond_acquires (lock) +__cond_acquires (true, lock) {preempt_disable ();if (do_raw_spin_trylock (lock)) {
@@ -177,7 +177,7 @@ static inline void __raw_spin_unlock_bh(raw_spinlock_t *lock) }static inline int __raw_spin_trylock_bh (raw_spinlock_t *lock) -__cond_acquires (lock) +__cond_acquires (true, lock) {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );if (do_raw_spin_trylock (lock)) {
net/ipv4/tcp_sigpool.c +1 -1
@@ -257,7 +257,7 @@ void tcp_sigpool_get(unsigned int id) }EXPORT_SYMBOL_GPL (tcp_sigpool_get); -int tcp_sigpool_start (unsigned int id,struct tcp_sigpool *c)__cond_acquires (RCU_BH ) +int tcp_sigpool_start (unsigned int id,struct tcp_sigpool *c)__cond_acquires (0 ,RCU_BH ) {struct crypto_ahash *hash;
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] compiler-context-analysis: Change __cond_acquires to take return value
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 38f1311a2219220a3962fae464ca6300ef60b4c1 Gitweb: https://git.kernel.org/tip/38f1311a2219220a3962fae464ca6300ef60b4c1 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:58 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:29 +01:00
compiler-context-analysis: Change __cond_acquires to take return value
While Sparse is oblivious to the return value of conditional acquire functions, Clang's context analysis needs to know the return value which indicates successful acquisition.
Add the additional argument, and convert existing uses.
Notably, Clang's interpretation of the value merely relates to the use in a later conditional branch, i.e. 1 ==> context lock acquired in branch taken if condition non-zero, and 0 ==> context lock acquired in branch taken if condition is zero. Given the precise value does not matter, introduce symbolic variants to use instead of either 0 or 1, which should be more intuitive.
No functional change intended.
--- fs/dlm/lock.c | 2 +- include/linux/compiler-context-analysis.h | 31 ++++++++++++++++++---- include/linux/refcount.h | 6 ++-- include/linux/spinlock.h | 6 ++-- include/linux/spinlock_api_smp.h | 8 +++--- net/ipv4/tcp_sigpool.c | 2 +- 6 files changed, 38 insertions(+), 17 deletions(-)
fs/dlm/lock.c +1 -1
@@ -343,7 +343,7 @@ void dlm_hold_rsb(struct dlm_rsb *r)/* TODO move this to lib/refcount.c */ static __must_check bool dlm_refcount_dec_and_write_lock_bh (refcount_t *r,rwlock_t *lock) -__cond_acquires (lock) +__cond_acquires (true, lock) {if (refcount_dec_not_one (r))return false;
include/linux/compiler-context-analysis.h +26 -5
@@ -271,7 +271,7 @@ static inline void _context_unsafe_alias(void **p) { }# define __must_hold (x) __attribute__((context(x,1,1)))# define __must_not_hold (x)# define __acquires (x) __attribute__((context(x,0,1))) -# define __cond_acquires (x) __attribute__((context(x,0,-1))) +# define __cond_acquires (ret, x) __attribute__((context(x,0,-1)))# define __releases (x) __attribute__((context(x,1,0)))# define __acquire (x) __context__(x,1)# define __release (x) __context__(x,-1)
@@ -314,15 +314,32 @@ static inline void _context_unsafe_alias(void **p) { }*/ # define __acquires (x) __acquires_ctx_lock(x) +/* +* Clang's analysis does not care precisely about the value, only that it is +* either zero or non-zero. So the __cond_acquires() interface might be +* misleading if we say that @ret is the value returned if acquired. Instead, +* provide symbolic variants which we translate. +*/ +#define __cond_acquires_impl_true (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(1, x) +#define __cond_acquires_impl_false (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(0, x) +#define __cond_acquires_impl_nonzero (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(1, x) +#define __cond_acquires_impl_0 (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(0, x) +#define __cond_acquires_impl_nonnull (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(1, x) +#define __cond_acquires_impl_NULL (x, ...) __try_acquires##__VA_ARGS__##_ctx_lock(0, x) +/** * __cond_acquires() - function attribute, function conditionally * acquires a context lock exclusively +* @ret: abstract value returned by function if context lock acquired * @x: context lock instance pointer * * Function attribute declaring that the function conditionally acquires the -* given context lock instance @x exclusively, but does not release it. +* given context lock instance @x exclusively, but does not release it. The +* function return value @ret denotes when the context lock is acquired. +* +* @ret may be one of: true, false, nonzero, 0, nonnull, NULL. */ -# define __cond_acquires (x) __try_acquires_ctx_lock(1, x) +# define __cond_acquires (ret, x) __cond_acquires_impl_##ret(x)/** * __releases() - function attribute, function releases a context lock exclusively
@@ -389,12 +406,16 @@ static inline void _context_unsafe_alias(void **p) { }/** * __cond_acquires_shared() - function attribute, function conditionally * acquires a context lock shared +* @ret: abstract value returned by function if context lock acquired * @x: context lock instance pointer * * Function attribute declaring that the function conditionally acquires the -* given context lock instance @x with shared access, but does not release it. +* given context lock instance @x with shared access, but does not release it. The +* function return value @ret denotes when the context lock is acquired. +* +* @ret may be one of: true, false, nonzero, 0, nonnull, NULL. */ -# define __cond_acquires_shared (x) __try_acquires_shared_ctx_lock(1, x) +# define __cond_acquires_shared (ret, x) __cond_acquires_impl_##ret(x, _shared)/** * __releases_shared() - function attribute, function releases a
include/linux/refcount.h +3 -3
@@ -478,9 +478,9 @@ static inline void refcount_dec(refcount_t *r)extern __must_check bool refcount_dec_if_one (refcount_t *r);extern __must_check bool refcount_dec_not_one (refcount_t *r); -extern __must_check bool refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock) __cond_acquires(lock); -extern __must_check bool refcount_dec_and_lock(refcount_t *r, spinlock_t *lock) __cond_acquires(lock); +extern __must_check bool refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock) __cond_acquires(true, lock); +extern __must_check bool refcount_dec_and_lock(refcount_t *r, spinlock_t *lock) __cond_acquires(true, lock); extern __must_check bool refcount_dec_and_lock_irqsave(refcount_t *r, spinlock_t *lock, - unsigned long *flags) __cond_acquires(lock); + unsigned long *flags) __cond_acquires(true, lock);#endif /* _LINUX_REFCOUNT_H */
include/linux/spinlock.h +3 -3
@@ -362,7 +362,7 @@ static __always_inline void spin_lock_bh(spinlock_t *lock) } static __always_inline int spin_trylock(spinlock_t *lock) -__cond_acquires (lock) __no_context_analysis +__cond_acquires (true, lock) __no_context_analysis {return raw_spin_trylock (&lock->rlock); }
@@ -422,13 +422,13 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, unsigned lo } static __always_inline int spin_trylock_bh(spinlock_t *lock) -__cond_acquires (lock) __no_context_analysis +__cond_acquires (true, lock) __no_context_analysis {return raw_spin_trylock_bh (&lock->rlock); } static __always_inline int spin_trylock_irq(spinlock_t *lock) -__cond_acquires (lock) __no_context_analysis +__cond_acquires (true, lock) __no_context_analysis {return raw_spin_trylock_irq (&lock->rlock); }
include/linux/spinlock_api_smp.h +4 -4
@@ -34,8 +34,8 @@ unsigned long __lockfunc _raw_spin_lock_irqsave(raw_spinlock_t *lock) unsigned long __lockfunc _raw_spin_lock_irqsave_nested(raw_spinlock_t *lock, int subclass) __acquires(lock); -int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock) __cond_acquires(lock); -int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock) __cond_acquires(lock); +int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock) __cond_acquires(true, lock); +int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock) __cond_acquires(true, lock); void __lockfunc _raw_spin_unlock(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock) __releases(lock);
@@ -84,7 +84,7 @@ _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags)#endif static inline int __raw_spin_trylock (raw_spinlock_t *lock) -__cond_acquires (lock) +__cond_acquires (true, lock) {preempt_disable ();if (do_raw_spin_trylock (lock)) {
@@ -177,7 +177,7 @@ static inline void __raw_spin_unlock_bh(raw_spinlock_t *lock) }static inline int __raw_spin_trylock_bh (raw_spinlock_t *lock) -__cond_acquires (lock) +__cond_acquires (true, lock) {__local_bh_disable_ip (_RET_IP_,SOFTIRQ_LOCK_OFFSET );if (do_raw_spin_trylock (lock)) {
net/ipv4/tcp_sigpool.c +1 -1
@@ -257,7 +257,7 @@ void tcp_sigpool_get(unsigned int id) }EXPORT_SYMBOL_GPL (tcp_sigpool_get); -int tcp_sigpool_start (unsigned int id,struct tcp_sigpool *c)__cond_acquires (RCU_BH ) +int tcp_sigpool_start (unsigned int id,struct tcp_sigpool *c)__cond_acquires (0 ,RCU_BH ) {struct crypto_ahash *hash;
Marco Elver
maintainerPATCH v5 10/36 locking/mutex: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for mutex.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
v3:
* Switch to DECLARE_LOCK_GUARD_1_ATTRS() (suggested by Peter)
* __assert -> __assume rename
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/mutex.h | 38 +++++++----- include/linux/mutex_types.h | 4 +- lib/test_context-analysis.c | 64 ++++++++++++++++++++ 4 files changed, 90 insertions(+), 18 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -79,7 +79,7 @@ Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported: -`raw_spinlock_t`, `spinlock_t`, `rwlock_t`. +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/mutex.h +23 -15
@@ -62,6 +62,7 @@ do { \static struct lock_class_key __key; \ \ __mutex_init((mutex), #mutex, &__key); \ +__assume_ctx_lock (mutex); \ }while (0 )/**
@@ -182,13 +183,13 @@ static inline int __must_check __devm_mutex_init(struct device *dev, struct mute* Also see Documentation/locking/mutex-design.rst. */ #ifdef CONFIG_DEBUG_LOCK_ALLOC -extern void mutex_lock_nested (struct mutex *lock,unsigned int subclass); +extern void mutex_lock_nested(struct mutex *lock, unsigned int subclass) __acquires(lock);extern void _mutex_lock_nest_lock (struct mutex *lock,struct lockdep_map *nest_lock); extern int __must_check mutex_lock_interruptible_nested(struct mutex *lock, -unsigned int subclass); + unsigned int subclass) __cond_acquires(0, lock); extern int __must_check _mutex_lock_killable(struct mutex *lock, -unsigned int subclass,struct lockdep_map *nest_lock); -extern void mutex_lock_io_nested (struct mutex *lock,unsigned int subclass); + unsigned int subclass, struct lockdep_map *nest_lock) __cond_acquires(0, lock); +extern void mutex_lock_io_nested(struct mutex *lock, unsigned int subclass) __acquires(lock);#define mutex_lock (lock) mutex_lock_nested(lock, 0)#define mutex_lock_interruptible (lock) mutex_lock_interruptible_nested(lock, 0)
@@ -211,10 +212,10 @@ do { \ _mutex_lock_killable(lock, subclass, NULL)#else -extern void mutex_lock (struct mutex *lock); -extern int __must_check mutex_lock_interruptible (struct mutex *lock); -extern int __must_check mutex_lock_killable (struct mutex *lock); -extern void mutex_lock_io (struct mutex *lock); +extern void mutex_lock(struct mutex *lock) __acquires(lock); +extern int __must_check mutex_lock_interruptible(struct mutex *lock) __cond_acquires(0, lock); +extern int __must_check mutex_lock_killable(struct mutex *lock) __cond_acquires(0, lock); +extern void mutex_lock_io(struct mutex *lock) __acquires(lock);# define mutex_lock_nested (lock, subclass) mutex_lock(lock)# define mutex_lock_interruptible_nested (lock, subclass) mutex_lock_interruptible(lock)
@@ -232,7 +233,7 @@ extern void mutex_lock_io(struct mutex *lock);*/ #ifdef CONFIG_DEBUG_LOCK_ALLOC -extern int _mutex_trylock_nest_lock (struct mutex *lock,struct lockdep_map *nest_lock); +extern int _mutex_trylock_nest_lock(struct mutex *lock, struct lockdep_map *nest_lock) __cond_acquires(true, lock);#define mutex_trylock_nest_lock (lock, nest_lock) \ ( \
@@ -242,17 +243,24 @@ extern int _mutex_trylock_nest_lock(struct mutex *lock, struct lockdep_map *nest#define mutex_trylock (lock) _mutex_trylock_nest_lock(lock, NULL)#else -extern int mutex_trylock (struct mutex *lock); +extern int mutex_trylock(struct mutex *lock) __cond_acquires(true, lock);#define mutex_trylock_nest_lock (lock, nest_lock) mutex_trylock(lock)#endif -extern void mutex_unlock (struct mutex *lock); +extern void mutex_unlock(struct mutex *lock) __releases(lock); -extern int atomic_dec_and_mutex_lock (atomic_t *cnt,struct mutex *lock); +extern int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock) __cond_acquires(true, lock); -DEFINE_GUARD(mutex, struct mutex *, mutex_lock(_T), mutex_unlock(_T)) -DEFINE_GUARD_COND(mutex, _try, mutex_trylock(_T)) -DEFINE_GUARD_COND(mutex, _intr, mutex_lock_interruptible(_T), _RET == 0) +DEFINE_LOCK_GUARD_1(mutex, struct mutex, mutex_lock(_T->lock), mutex_unlock(_T->lock)) +DEFINE_LOCK_GUARD_1_COND(mutex, _try, mutex_trylock(_T->lock)) +DEFINE_LOCK_GUARD_1_COND(mutex, _intr, mutex_lock_interruptible(_T->lock), _RET == 0) + +DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) +#define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T) +DECLARE_LOCK_GUARD_1_ATTRS(mutex_try, __acquires(_T), __releases(*(struct mutex **)_T)) +#define class_mutex_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex_try, _T) +DECLARE_LOCK_GUARD_1_ATTRS(mutex_intr, __acquires(_T), __releases(*(struct mutex **)_T)) +#define class_mutex_intr_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex_intr, _T) extern unsigned long mutex_get_owner(struct mutex *lock);
include/linux/mutex_types.h +2 -2
@@ -38,7 +38,7 @@* - detects multi-task circular deadlocks and prints out all affected * locks and tasks (and only those tasks) */ -struct mutex { +context_lock_struct (mutex) {atomic_long_t owner;raw_spinlock_t wait_lock;#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
@@ -59,7 +59,7 @@ struct mutex {*/ #include <linux/rtmutex.h> -struct mutex { +context_lock_struct (mutex) {struct rt_mutex_base rtmutex;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;
lib/test_context-analysis.c +64 -0
73 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] locking/mutex: Support Clang's context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 370f0a345a70fe36d0185abf87c7ee8e70572e06 Gitweb: https://git.kernel.org/tip/370f0a345a70fe36d0185abf87c7ee8e70572e06 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:39:59 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:29 +01:00
locking/mutex: Support Clang's context analysis
Add support for Clang's context analysis for mutex.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/mutex.h | 38 ++++++----- include/linux/mutex_types.h | 4 +- lib/test_context-analysis.c | 64 +++++++++++++++++++- 4 files changed, 90 insertions(+), 18 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -79,7 +79,7 @@ Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported: -`raw_spinlock_t`, `spinlock_t`, `rwlock_t`. +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/mutex.h +23 -15
@@ -62,6 +62,7 @@ do { \static struct lock_class_key __key; \ \ __mutex_init((mutex), #mutex, &__key); \ +__assume_ctx_lock (mutex); \ }while (0 )/**
@@ -182,13 +183,13 @@ static inline int __must_check __devm_mutex_init(struct device *dev, struct mute* Also see Documentation/locking/mutex-design.rst. */ #ifdef CONFIG_DEBUG_LOCK_ALLOC -extern void mutex_lock_nested (struct mutex *lock,unsigned int subclass); +extern void mutex_lock_nested(struct mutex *lock, unsigned int subclass) __acquires(lock);extern void _mutex_lock_nest_lock (struct mutex *lock,struct lockdep_map *nest_lock); extern int __must_check mutex_lock_interruptible_nested(struct mutex *lock, -unsigned int subclass); + unsigned int subclass) __cond_acquires(0, lock); extern int __must_check _mutex_lock_killable(struct mutex *lock, -unsigned int subclass,struct lockdep_map *nest_lock); -extern void mutex_lock_io_nested (struct mutex *lock,unsigned int subclass); + unsigned int subclass, struct lockdep_map *nest_lock) __cond_acquires(0, lock); +extern void mutex_lock_io_nested(struct mutex *lock, unsigned int subclass) __acquires(lock);#define mutex_lock (lock) mutex_lock_nested(lock, 0)#define mutex_lock_interruptible (lock) mutex_lock_interruptible_nested(lock, 0)
@@ -211,10 +212,10 @@ do { \ _mutex_lock_killable(lock, subclass, NULL)#else -extern void mutex_lock (struct mutex *lock); -extern int __must_check mutex_lock_interruptible (struct mutex *lock); -extern int __must_check mutex_lock_killable (struct mutex *lock); -extern void mutex_lock_io (struct mutex *lock); +extern void mutex_lock(struct mutex *lock) __acquires(lock); +extern int __must_check mutex_lock_interruptible(struct mutex *lock) __cond_acquires(0, lock); +extern int __must_check mutex_lock_killable(struct mutex *lock) __cond_acquires(0, lock); +extern void mutex_lock_io(struct mutex *lock) __acquires(lock);# define mutex_lock_nested (lock, subclass) mutex_lock(lock)# define mutex_lock_interruptible_nested (lock, subclass) mutex_lock_interruptible(lock)
@@ -232,7 +233,7 @@ extern void mutex_lock_io(struct mutex *lock);*/ #ifdef CONFIG_DEBUG_LOCK_ALLOC -extern int _mutex_trylock_nest_lock (struct mutex *lock,struct lockdep_map *nest_lock); +extern int _mutex_trylock_nest_lock(struct mutex *lock, struct lockdep_map *nest_lock) __cond_acquires(true, lock);#define mutex_trylock_nest_lock (lock, nest_lock) \ ( \
@@ -242,17 +243,24 @@ extern int _mutex_trylock_nest_lock(struct mutex *lock, struct lockdep_map *nest#define mutex_trylock (lock) _mutex_trylock_nest_lock(lock, NULL)#else -extern int mutex_trylock (struct mutex *lock); +extern int mutex_trylock(struct mutex *lock) __cond_acquires(true, lock);#define mutex_trylock_nest_lock (lock, nest_lock) mutex_trylock(lock)#endif -extern void mutex_unlock (struct mutex *lock); +extern void mutex_unlock(struct mutex *lock) __releases(lock); -extern int atomic_dec_and_mutex_lock (atomic_t *cnt,struct mutex *lock); +extern int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock) __cond_acquires(true, lock); -DEFINE_GUARD(mutex, struct mutex *, mutex_lock(_T), mutex_unlock(_T)) -DEFINE_GUARD_COND(mutex, _try, mutex_trylock(_T)) -DEFINE_GUARD_COND(mutex, _intr, mutex_lock_interruptible(_T), _RET == 0) +DEFINE_LOCK_GUARD_1(mutex, struct mutex, mutex_lock(_T->lock), mutex_unlock(_T->lock)) +DEFINE_LOCK_GUARD_1_COND(mutex, _try, mutex_trylock(_T->lock)) +DEFINE_LOCK_GUARD_1_COND(mutex, _intr, mutex_lock_interruptible(_T->lock), _RET == 0) + +DECLARE_LOCK_GUARD_1_ATTRS(mutex, __acquires(_T), __releases(*(struct mutex **)_T)) +#define class_mutex_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex, _T) +DECLARE_LOCK_GUARD_1_ATTRS(mutex_try, __acquires(_T), __releases(*(struct mutex **)_T)) +#define class_mutex_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex_try, _T) +DECLARE_LOCK_GUARD_1_ATTRS(mutex_intr, __acquires(_T), __releases(*(struct mutex **)_T)) +#define class_mutex_intr_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(mutex_intr, _T) extern unsigned long mutex_get_owner(struct mutex *lock);
include/linux/mutex_types.h +2 -2
@@ -38,7 +38,7 @@* - detects multi-task circular deadlocks and prints out all affected * locks and tasks (and only those tasks) */ -struct mutex { +context_lock_struct (mutex) {atomic_long_t owner;raw_spinlock_t wait_lock;#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
@@ -59,7 +59,7 @@ struct mutex {*/ #include <linux/rtmutex.h> -struct mutex { +context_lock_struct (mutex) {struct rt_mutex_base rtmutex;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;
lib/test_context-analysis.c +64 -0
73 lines not on this page · raw message
Bart Van Assche
reviewerRe: [PATCH v5 10/36] locking/mutex: Support Clang's context analysis
In reply to Marco Elverinclude/linux/mutex.h do { \ · line 66
Quoted 10 lines · Marco Elver
include/linux/mutex.h +1
-0@@ -62,6 +62,7 @@ do { \static struct lock_class_key __key; \ \ __mutex_init((mutex), #mutex, &__key); \ +__assume_ctx_lock (mutex); \ }while (0 )
The above type of change probably will have to be reverted. If I enable context analysis for the entire kernel tree, drivers/base/devcoredump.c doesn't build. The following error is reported:
drivers/base/devcoredump.c:406:2: error: acquiring mutex '_res->mutex' that is already held [-Werror,-Wthread-safety-analysis]
406 | mutex_lock(&devcd->mutex);
| ^dev_coredumpm_timeout() calls mutex_init() and mutex_lock() from the same function. The above type of change breaks compilation of all code that initializes and locks a synchronization object from the same
function. My understanding of dev_coredumpm_timeout() is that there is a
good reason for calling both mutex_init() and mutex_lock() from that
function. Possible solutions are disabling context analysis for that
function or removing __assume_ctx_lock() again from mutex_init(). Does
anyone want to share their opinion about this?
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 10/36] locking/mutex: Support Clang's context analysis
Quoted 21 lines · Bart Van Assche' via kasan-dev
include/linux/mutex.h do { \ · line 66
Quoted 10 lines · Marco Elver
include/linux/mutex.h +1
-0@@ -62,6 +62,7 @@ do { \static struct lock_class_key __key; \ \ __mutex_init((mutex), #mutex, &__key); \ +__assume_ctx_lock (mutex); \ }while (0 )The above type of change probably will have to be reverted. If I enable context analysis for the entire kernel tree,
drivers/base/devcoredump.cdoesn't build. The following error is reported:
drivers/base/devcoredump.c:406:2: error: acquiring mutex '_res->mutex' that is already held [-Werror,-Wthread-safety-analysis]406 | mutex_lock(&devcd->mutex); | ^
Quoted 8 lines
dev_coredumpm_timeout()callsmutex_init()andmutex_lock()from the same function. The above type of change breaks compilation of all code that initializes and locks a synchronization object from the same function. My understanding ofdev_coredumpm_timeout()is that there is a good reason for calling bothmutex_init()andmutex_lock()from that function. Possible solutions are disabling context analysis for that function or removing__assume_ctx_lock()again frommutex_init(). Does anyone want to share their opinion about this?
Probably the most idiomatic option is to just factor out construction. Clearly separating complex object construction from use also helps readability regardless, esp. where concurrency is involved. We could document such advice somewhere.
For the above case, this seems cleanest and also clearer to me:
drivers/base/devcoredump.c +35 -19
@@ -339,6 +339,40 @@ void dev_coredump_put(struct device *dev) }EXPORT_SYMBOL_GPL (dev_coredump_put); +static struct devcd_entry * +dev_coredumpm_init (struct device *dev,struct module *owner,void *data, +size_t datalen,gfp_t gfp, +ssize_t (*read)(char *buffer,loff_t offset,size_t count, +void *data,size_t datalen), +void (*free)(void *data)) +{ +static atomic_t devcd_count =ATOMIC_INIT (0 ); +struct devcd_entry *devcd; + + devcd =kzalloc (sizeof (*devcd), gfp); +if (!devcd) +return NULL ; + + devcd->owner = owner; + devcd->data = data; + devcd->datalen = datalen; + devcd->read = read; + devcd->free = free; + devcd->failing_dev =get_device (dev); + devcd->deleted = false; + +mutex_init (&devcd->mutex); +device_initialize (&devcd->devcd_dev); + +dev_set_name (&devcd->devcd_dev,"devcd%d" , +atomic_inc_return (&devcd_count)); + devcd->devcd_dev.class = &devcd_class; + +dev_set_uevent_suppress (&devcd->devcd_dev, true); + +return devcd; +} +/** * dev_coredumpm_timeout - create device coredump with read/free methods with a * custom timeout.
@@ -364,7 +398,6 @@ void dev_coredumpm_timeout(struct device *dev, struct module *owner, void (*free)(void *data), unsigned long timeout) { -static atomic_t devcd_count =ATOMIC_INIT (0 );struct devcd_entry *devcd;struct device *existing;
@@ -381,27 +414,10 @@ void dev_coredumpm_timeout(struct device *dev, struct module *owner,if (!try_module_get (owner)) goto free; - devcd =kzalloc (sizeof (*devcd), gfp); + devcd =dev_coredumpm_init (dev, owner, data, datalen, gfp, read, free);if (!devcd) goto put_module; - devcd->owner = owner; - devcd->data = data; - devcd->datalen = datalen; - devcd->read = read; - devcd->free = free; - devcd->failing_dev =get_device (dev); - devcd->deleted = false; - -mutex_init (&devcd->mutex); -device_initialize (&devcd->devcd_dev); - -dev_set_name (&devcd->devcd_dev,"devcd%d" , -atomic_inc_return (&devcd_count)); - devcd->devcd_dev.class = &devcd_class; - -dev_set_uevent_suppress (&devcd->devcd_dev, true); -/* devcd->mutex prevents devcd_del() completing until init finishes */ mutex_lock (&devcd->mutex); devcd->init_completed = false;
Re: [PATCH v5 10/36] locking/mutex: Support Clang's context analysis
Quoted 4 lines · Marco Elver
Probably the most idiomatic option is to just factor out construction. Clearly separating complex object construction from use also helps readability regardless, esp. where concurrency is involved. We could document such advice somewhere.
Initializing and locking a mutex (or spinlock, or other primitive) is a not too unusual pattern, often used when inserting an object into a hash table or other lookup data structure. So supporting it without creating pointless wrapper functions would be really useful. One thing that would be nice to have and probably help here is to have lock initializers that create the lock in a held state.
Steven Rostedt
reviewerRe: [PATCH v5 10/36] locking/mutex: Support Clang's context analysis
Quoted 6 lines · On Fri, 9 Jan 2026 07:02:49 +0100 Christoph Hellwig <[email protected]> wrote:
Quoted 4 lines · Marco Elver
Probably the most idiomatic option is to just factor out construction. Clearly separating complex object construction from use also helps readability regardless, esp. where concurrency is involved. We could document such advice somewhere.
Quoted 6 lines
Initializing and locking a mutex (or spinlock, or other primitive) is a not too unusual pattern, often used when inserting an object into a hash table or other lookup data structure. So supporting it without creating pointless wrapper functions would be really useful. One thing that would be nice to have and probably help here is to have lock initializers that create the lock in a held state.
Right. If tooling can't handle a simple pattern of initializing a lock than taking it, that's a hard show stopper of adding that tooling.
-- Steve
Marco Elver
maintainerRe: [PATCH v5 10/36] locking/mutex: Support Clang's context analysis
In reply to Christoph HellwigQuoted 6 lines · Christoph Hellwig
Quoted 4 lines · Marco Elver
Probably the most idiomatic option is to just factor out construction. Clearly separating complex object construction from use also helps readability regardless, esp. where concurrency is involved. We could document such advice somewhere.
Quoted 6 lines
Initializing and locking a mutex (or spinlock, or other primitive) is a not too unusual pattern, often used when inserting an object into a hash table or other lookup data structure. So supporting it without creating pointless wrapper functions would be really useful. One thing that would be nice to have and probably help here is to have lock initializers that create the lock in a held state.
Fair point. Without new APIs, we can fix it with the below patch; essentially "promoting" the context lock to "reentrant" during initialization scope. It's not exactly well documented on the Clang side, but is a side-effect of how reentrancy works in the analysis:
https://github.com/llvm/llvm-project/pull/175267
------ >8 ------
From 9c9b521b286f241f849dcc4f9efbd9582dabd3cc Mon Sep 17 00:00:00 2001
From: Marco Elver <[email protected]>
Date: Sat, 10 Jan 2026 00:47:35 +0100
Subject: [PATCH] compiler-context-analysis: Support immediate acquisition
after initialization
When a lock is initialized (e.g. mutex_init()), we assume/assert that the context lock is held to allow initialization of guarded members within the same scope.
However, this previously prevented actually acquiring the lock within that same scope, as the analyzer would report a double-lock warning:
mutex_init(&mtx);
...
mutex_lock(&mtx); // acquiring mutex 'mtx' that is already held
To fix (without new init+lock APIs), we can tell the analysis to treat the "held" context lock resulting from initialization as reentrant, allowing subsequent acquisitions to succeed.
To do so *only* within the initialization scope, we can cast the lock pointer to any reentrant type for the init assume/assert. Introduce a generic reentrant context lock type struct __ctx_lock_init and add __inits_ctx_lock() that casts the lock pointer to this type before assuming/asserting it.
This ensures that the initial "held" state is reentrant, allowing patterns like:
mutex_init(&lock); ... mutex_lock(&lock);
to compile without false positives, and avoids having to make all context lock types reentrant outside an initialization scope.
The caveat here is missing real double-lock bugs right after init scope. However, this is a classic trade-off of avoiding false positives against (unlikely) false negatives.
--- include/linux/compiler-context-analysis.h | 12 ++++++++++++ include/linux/local_lock_internal.h | 6 +++--- include/linux/mutex.h | 2 +- include/linux/rwlock.h | 4 ++-- include/linux/rwlock_rt.h | 2 +- include/linux/rwsem.h | 4 ++-- include/linux/seqlock.h | 2 +- include/linux/spinlock.h | 8 ++++---- include/linux/spinlock_rt.h | 2 +- include/linux/ww_mutex.h | 2 +- lib/test_context-analysis.c | 3 +++ 11 files changed, 31 insertions(+), 16 deletions(-)
include/linux/compiler-context-analysis.h +12 -0
@@ -43,6 +43,14 @@# define __assumes_ctx_lock (...) __attribute__((assert_capability(__VA_ARGS__)))# define __assumes_shared_ctx_lock (...) __attribute__((assert_shared_capability(__VA_ARGS__))) +/* +* Generic reentrant context lock type that we cast to when initializing context +* locks with __assumes_ctx_lock(), so that we can support guarded member +* initialization, but also immediate use after initialization. +*/ +struct __ctx_lock_type(init_generic) __reentrant_ctx_lock __ctx_lock_init; +# define __inits_ctx_lock (var) __assumes_ctx_lock((const struct __ctx_lock_init *)(var)) +/** * __guarded_by - struct member and globals attribute, declares variable * only accessible within active context
@@ -120,6 +128,8 @@ __attribute__((overloadable))__assumes_ctx_lock (var) { } \ static __always_inline void __assume_shared_ctx_lock(const struct name *var) \ __attribute__((overloadable))__assumes_shared_ctx_lock (var) { } \ + static __always_inline void __init_ctx_lock(const struct name *var) \ + __attribute__((overloadable))__inits_ctx_lock (var) { } \struct name /**
@@ -162,6 +172,7 @@# define __releases_shared_ctx_lock (...)# define __assumes_ctx_lock (...)# define __assumes_shared_ctx_lock (...) +# define __inits_ctx_lock (var)# define __returns_ctx_lock (var)# define __guarded_by (...)# define __pt_guarded_by (...)
@@ -176,6 +187,7 @@# define __release_shared_ctx_lock (var) do { } while (0)# define __assume_ctx_lock (var) do { (void)(var); } while (0)# define __assume_shared_ctx_lock (var) do { (void)(var); } while (0) +# define __init_ctx_lock (var) do { (void)(var); } while (0)# define context_lock_struct (name, ...) struct __VA_ARGS__ name# define disable_context_analysis ()# define enable_context_analysis ()
include/linux/local_lock_internal.h +3 -3
@@ -86,13 +86,13 @@ do { \0 ,LD_WAIT_CONFIG ,LD_WAIT_INV , \ LD_LOCK_PERCPU); \local_lock_debug_init (lock); \ -__assume_ctx_lock (lock); \ +__init_ctx_lock (lock); \ } while (0)#define __local_trylock_init (lock) \ do { \ __local_lock_init((local_lock_t *)lock); \ - __assume_ctx_lock(lock); \ + __init_ctx_lock(lock); \ } while (0)#define __spinlock_nested_bh_init (lock) \
@@ -104,7 +104,7 @@ do { \0 ,LD_WAIT_CONFIG ,LD_WAIT_INV , \ LD_LOCK_NORMAL); \local_lock_debug_init (lock); \ -__assume_ctx_lock (lock); \ +__init_ctx_lock (lock); \ }while (0 ) #define __local_lock_acquire(lock) \
include/linux/mutex.h +1 -1
@@ -62,7 +62,7 @@ do { \static struct lock_class_key __key; \ \ __mutex_init((mutex), #mutex, &__key); \ -__assume_ctx_lock (mutex); \ +__init_ctx_lock (mutex); \ }while (0 )/**
include/linux/rwlock.h +2 -2
@@ -22,11 +22,11 @@ do { \static struct lock_class_key __key; \ \ __rwlock_init((lock), #lock, &__key); \ - __assume_ctx_lock(lock); \ + __init_ctx_lock(lock); \ } while (0)#else # define rwlock_init (lock) \ - do { *(lock) = __RW_LOCK_UNLOCKED(lock); __assume_ctx_lock(lock); } while (0) + do { *(lock) = __RW_LOCK_UNLOCKED(lock); __init_ctx_lock(lock); } while (0)#endif #ifdef CONFIG_DEBUG_SPINLOCK
include/linux/rwlock_rt.h +1 -1
@@ -22,7 +22,7 @@ do { \ \init_rwbase_rt (&(rwl)->rwbase); \ __rt_rwlock_init(rwl, #rwl, &__key); \ -__assume_ctx_lock (rwl); \ +__init_ctx_lock (rwl); \ }while (0 ) extern void rt_read_lock(rwlock_t *rwlock) __acquires_shared(rwlock);
include/linux/rwsem.h +2 -2
@@ -121,7 +121,7 @@ do { \static struct lock_class_key __key; \ \ __init_rwsem((sem), #sem, &__key); \ -__assume_ctx_lock (sem); \ +__init_ctx_lock (sem); \ }while (0 )/*
@@ -175,7 +175,7 @@ do { \static struct lock_class_key __key; \ \ __init_rwsem((sem), #sem, &__key); \ -__assume_ctx_lock (sem); \ +__init_ctx_lock (sem); \ }while (0 ) static __always_inline int rwsem_is_locked(const struct rw_semaphore *sem)
include/linux/seqlock.h +1 -1
@@ -816,7 +816,7 @@ static __always_inline void write_seqcount_latch_end(seqcount_latch_t *s)do { \spin_lock_init (&(sl)->lock); \seqcount_spinlock_init (&(sl)->seqcount, &(sl)->lock); \ -__assume_ctx_lock (sl); \ +__init_ctx_lock (sl); \ }while (0 )/**
include/linux/spinlock.h +4 -4
@@ -106,12 +106,12 @@ do { \static struct lock_class_key __key; \ \ __raw_spin_lock_init((lock), #lock, &__key, LD_WAIT_SPIN); \ - __assume_ctx_lock(lock); \ + __init_ctx_lock(lock); \ } while (0)#else # define raw_spin_lock_init (lock) \ - do { *(lock) = __RAW_SPIN_LOCK_UNLOCKED(lock); __assume_ctx_lock(lock); } while (0) + do { *(lock) = __RAW_SPIN_LOCK_UNLOCKED(lock); __init_ctx_lock(lock); } while (0)#endif #define raw_spin_is_locked (lock) arch_spin_is_locked(&(lock)->raw_lock)
@@ -324,7 +324,7 @@ do { \ \ __raw_spin_lock_init(spinlock_check(lock), \#lock , &__key, LD_WAIT_CONFIG); \ - __assume_ctx_lock(lock); \ + __init_ctx_lock(lock); \ } while (0)#else
@@ -333,7 +333,7 @@ do { \do { \spinlock_check (_lock); \ *(_lock) =__SPIN_LOCK_UNLOCKED (_lock); \ -__assume_ctx_lock (_lock); \ +__init_ctx_lock (_lock); \ } while (0)#endif
include/linux/spinlock_rt.h +1 -1
@@ -20,7 +20,7 @@ static inline void __rt_spin_lock_init(spinlock_t *lock, const char *name,do { \rt_mutex_base_init (&(slock)->lock); \__rt_spin_lock_init (slock, name, key, percpu); \ -__assume_ctx_lock (slock); \ +__init_ctx_lock (slock); \ } while (0)#define _spin_lock_init (slock, percpu) \
include/linux/ww_mutex.h +1 -1
@@ -107,7 +107,7 @@ context_lock_struct(ww_acquire_ctx) {*/ static inline void ww_mutex_init (struct ww_mutex *lock,struct ww_class *ww_class) -__assumes_ctx_lock (lock) +__inits_ctx_lock (lock) {ww_mutex_base_init (&lock->base, ww_class->mutex_name, &ww_class->mutex_key); lock->ctx =NULL ;
lib/test_context-analysis.c +3 -0
@@ -165,6 +165,9 @@ static void __used test_mutex_init(struct test_mutex_data *d) {mutex_init (&d->mtx); d->counter =0 ; + +mutex_lock (&d->mtx); +mutex_unlock (&d->mtx); }static void __used test_mutex_lock (struct test_mutex_data *d)
Signature · 1 line
2.52.0.457.g6b5491de43-goog
Marco Elver
maintainerPATCH v5 11/36 locking/seqlock: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for seqlock_t.
---
v5:
* Support scoped_seqlock_read().
* Rename "context guard" -> "context lock".
v3:
* __assert -> __assume rename
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/seqlock.h | 38 ++++++++++++++- include/linux/seqlock_types.h | 5 +- lib/test_context-analysis.c | 50 ++++++++++++++++++++ 4 files changed, 91 insertions(+), 4 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -79,7 +79,7 @@ Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported: -`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`. +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/seqlock.h +37 -1
@@ -816,6 +816,7 @@ static __always_inline void write_seqcount_latch_end(seqcount_latch_t *s)do { \spin_lock_init (&(sl)->lock); \seqcount_spinlock_init (&(sl)->seqcount, &(sl)->lock); \ +__assume_ctx_lock (sl); \ }while (0 )/**
@@ -832,6 +833,7 @@ static __always_inline void write_seqcount_latch_end(seqcount_latch_t *s)* Return: count, to be passed to read_seqretry() */ static inline unsigned read_seqbegin (const seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {return read_seqcount_begin (&sl->seqcount); }
@@ -848,6 +850,7 @@ static inline unsigned read_seqbegin(const seqlock_t *sl)* Return: true if a read section retry is required, else false */ static inline unsigned read_seqretry (const seqlock_t *sl,unsigned start) +__releases_shared (sl) __no_context_analysis {return read_seqcount_retry (&sl->seqcount, start); }
@@ -872,6 +875,7 @@ static inline unsigned read_seqretry(const seqlock_t *sl, unsigned start)* _irqsave or _bh variants of this function instead. */ static inline void write_seqlock (seqlock_t *sl) +__acquires (sl) __no_context_analysis {spin_lock (&sl->lock);do_write_seqcount_begin (&sl->seqcount.seqcount);
@@ -885,6 +889,7 @@ static inline void write_seqlock(seqlock_t *sl)* critical section of given seqlock_t. */ static inline void write_sequnlock (seqlock_t *sl) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock (&sl->lock);
@@ -898,6 +903,7 @@ static inline void write_sequnlock(seqlock_t *sl)* other write side sections, can be invoked from softirq contexts. */ static inline void write_seqlock_bh (seqlock_t *sl) +__acquires (sl) __no_context_analysis {spin_lock_bh (&sl->lock);do_write_seqcount_begin (&sl->seqcount.seqcount);
@@ -912,6 +918,7 @@ static inline void write_seqlock_bh(seqlock_t *sl)* write_seqlock_bh(). */ static inline void write_sequnlock_bh (seqlock_t *sl) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock_bh (&sl->lock);
@@ -925,6 +932,7 @@ static inline void write_sequnlock_bh(seqlock_t *sl)* other write sections, can be invoked from hardirq contexts. */ static inline void write_seqlock_irq (seqlock_t *sl) +__acquires (sl) __no_context_analysis {spin_lock_irq (&sl->lock);do_write_seqcount_begin (&sl->seqcount.seqcount);
@@ -938,12 +946,14 @@ static inline void write_seqlock_irq(seqlock_t *sl)* seqlock_t write side section opened with write_seqlock_irq(). */ static inline void write_sequnlock_irq (seqlock_t *sl) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock_irq (&sl->lock); }static inline unsigned long __write_seqlock_irqsave (seqlock_t *sl) +__acquires (sl) __no_context_analysis {unsigned long flags;
@@ -976,6 +986,7 @@ static inline unsigned long __write_seqlock_irqsave(seqlock_t *sl)*/ static inline void write_sequnlock_irqrestore (seqlock_t *sl,unsigned long flags) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock_irqrestore (&sl->lock, flags);
@@ -998,6 +1009,7 @@ write_sequnlock_irqrestore(seqlock_t *sl, unsigned long flags)* The opened read section must be closed with read_sequnlock_excl(). */ static inline void read_seqlock_excl (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {spin_lock (&sl->lock); }
@@ -1007,6 +1019,7 @@ static inline void read_seqlock_excl(seqlock_t *sl)* @sl: Pointer to seqlock_t */ static inline void read_sequnlock_excl (seqlock_t *sl) +__releases_shared (sl) __no_context_analysis {spin_unlock (&sl->lock); }
@@ -1021,6 +1034,7 @@ static inline void read_sequnlock_excl(seqlock_t *sl)* from softirq contexts. */ static inline void read_seqlock_excl_bh (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {spin_lock_bh (&sl->lock); }
@@ -1031,6 +1045,7 @@ static inline void read_seqlock_excl_bh(seqlock_t *sl)* @sl: Pointer to seqlock_t */ static inline void read_sequnlock_excl_bh (seqlock_t *sl) +__releases_shared (sl) __no_context_analysis {spin_unlock_bh (&sl->lock); }
@@ -1045,6 +1060,7 @@ static inline void read_sequnlock_excl_bh(seqlock_t *sl)* hardirq context. */ static inline void read_seqlock_excl_irq (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {spin_lock_irq (&sl->lock); }
@@ -1055,11 +1071,13 @@ static inline void read_seqlock_excl_irq(seqlock_t *sl)* @sl: Pointer to seqlock_t */ static inline void read_sequnlock_excl_irq (seqlock_t *sl) +__releases_shared (sl) __no_context_analysis {spin_unlock_irq (&sl->lock); }static inline unsigned long __read_seqlock_excl_irqsave (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {unsigned long flags;
@@ -1089,6 +1107,7 @@ static inline unsigned long __read_seqlock_excl_irqsave(seqlock_t *sl)*/ static inline void read_sequnlock_excl_irqrestore (seqlock_t *sl,unsigned long flags) +__releases_shared (sl) __no_context_analysis {spin_unlock_irqrestore (&sl->lock, flags); }
@@ -1125,6 +1144,7 @@ read_sequnlock_excl_irqrestore(seqlock_t *sl, unsigned long flags)* parameter of the next read_seqbegin_or_lock() iteration. */ static inline void read_seqbegin_or_lock (seqlock_t *lock,int *seq) +__acquires_shared (lock) __no_context_analysis {if (!(*seq &1 ))/* Even */ *seq =read_seqbegin (lock);
@@ -1140,6 +1160,7 @@ static inline void read_seqbegin_or_lock(seqlock_t *lock, int *seq)* Return: true if a read section retry is required, false otherwise */ static inline int need_seqretry (seqlock_t *lock,int seq) +__releases_shared (lock) __no_context_analysis {return !(seq &1 ) &&read_seqretry (lock, seq); }
@@ -1153,6 +1174,7 @@ static inline int need_seqretry(seqlock_t *lock, int seq)* with read_seqbegin_or_lock() and validated by need_seqretry(). */ static inline void done_seqretry (seqlock_t *lock,int seq) + __no_context_analysis {if (seq &1 )read_sequnlock_excl (lock);
@@ -1180,6 +1202,7 @@ static inline void done_seqretry(seqlock_t *lock, int seq)*/ static inline unsigned long read_seqbegin_or_lock_irqsave (seqlock_t *lock,int *seq) +__acquires_shared (lock) __no_context_analysis {unsigned long flags =0 ;
@@ -1205,6 +1228,7 @@ read_seqbegin_or_lock_irqsave(seqlock_t *lock, int *seq)*/ static inline void done_seqretry_irqrestore (seqlock_t *lock,int seq,unsigned long flags) + __no_context_analysis {if (seq &1 )read_sequnlock_excl_irqrestore (lock, flags);
@@ -1225,6 +1249,7 @@ struct ss_tmp { }; static __always_inline void __scoped_seqlock_cleanup(struct ss_tmp *sst) + __no_context_analysis {if (sst->lock)spin_unlock (sst->lock);
@@ -1254,6 +1279,7 @@ extern void __scoped_seqlock_bug(void); static __always_inline void__scoped_seqlock_next (struct ss_tmp *sst,seqlock_t *lock,enum ss_state target) + __no_context_analysis {switch (sst->state) {case ss_done:
@@ -1296,9 +1322,19 @@ __scoped_seqlock_next(struct ss_tmp *sst, seqlock_t *lock, enum ss_state target) } } +/* +* Context analysis no-op helper to release seqlock at the end of the for-scope; +* the alias analysis of the compiler will recognize that the pointer @s is an +* alias to @_seqlock passed to read_seqbegin(_seqlock) below. +*/ +static __always_inline void __scoped_seqlock_cleanup_ctx(struct ss_tmp **s) + __releases_shared(*((seqlock_t **)s)) __no_context_analysis {} +#define __scoped_seqlock_read (_seqlock, _target, _s) \ for (struct ss_tmp _s __cleanup(__scoped_seqlock_cleanup) = \ - { .state = ss_lockless, .data = read_seqbegin(_seqlock) }; \ + { .state = ss_lockless, .data = read_seqbegin(_seqlock) }, \ + *__UNIQUE_ID(ctx) __cleanup(__scoped_seqlock_cleanup_ctx) =\ + (struct ss_tmp *)_seqlock; \ _s.state != ss_done; \ __scoped_seqlock_next(&_s, _seqlock, _target))
include/linux/seqlock_types.h +3 -2
@@ -81,13 +81,14 @@ SEQCOUNT_LOCKNAME(mutex, struct mutex, true, mutex)* - Comments on top of seqcount_t * - Documentation/locking/seqlock.rst */ -typedef struct { +context_lock_struct (seqlock) {/* * Make sure that readers don't starve writers on PREEMPT_RT: use * seqcount_spinlock_t instead of seqcount_t. Check __SEQ_LOCK(). */ seqcount_spinlock_t seqcount;spinlock_t lock; -}seqlock_t ; +}; +typedef struct seqlock seqlock_t ;#endif /* __LINUX_SEQLOCK_TYPES_H */
lib/test_context-analysis.c +50 -0
59 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] locking/seqlock: Support Clang's context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 8f8a55f49cda5fee914bbea1ab5af8df3a6ba8af Gitweb: https://git.kernel.org/tip/8f8a55f49cda5fee914bbea1ab5af8df3a6ba8af Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:00 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:29 +01:00
locking/seqlock: Support Clang's context analysis
Add support for Clang's context analysis for seqlock_t.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/seqlock.h | 38 +++++++++++++- include/linux/seqlock_types.h | 5 +- lib/test_context-analysis.c | 50 +++++++++++++++++++- 4 files changed, 91 insertions(+), 4 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -79,7 +79,7 @@ Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported: -`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`. +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/seqlock.h +37 -1
@@ -816,6 +816,7 @@ static __always_inline void write_seqcount_latch_end(seqcount_latch_t *s)do { \spin_lock_init (&(sl)->lock); \seqcount_spinlock_init (&(sl)->seqcount, &(sl)->lock); \ +__assume_ctx_lock (sl); \ }while (0 )/**
@@ -832,6 +833,7 @@ static __always_inline void write_seqcount_latch_end(seqcount_latch_t *s)* Return: count, to be passed to read_seqretry() */ static inline unsigned read_seqbegin (const seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {return read_seqcount_begin (&sl->seqcount); }
@@ -848,6 +850,7 @@ static inline unsigned read_seqbegin(const seqlock_t *sl)* Return: true if a read section retry is required, else false */ static inline unsigned read_seqretry (const seqlock_t *sl,unsigned start) +__releases_shared (sl) __no_context_analysis {return read_seqcount_retry (&sl->seqcount, start); }
@@ -872,6 +875,7 @@ static inline unsigned read_seqretry(const seqlock_t *sl, unsigned start)* _irqsave or _bh variants of this function instead. */ static inline void write_seqlock (seqlock_t *sl) +__acquires (sl) __no_context_analysis {spin_lock (&sl->lock);do_write_seqcount_begin (&sl->seqcount.seqcount);
@@ -885,6 +889,7 @@ static inline void write_seqlock(seqlock_t *sl)* critical section of given seqlock_t. */ static inline void write_sequnlock (seqlock_t *sl) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock (&sl->lock);
@@ -898,6 +903,7 @@ static inline void write_sequnlock(seqlock_t *sl)* other write side sections, can be invoked from softirq contexts. */ static inline void write_seqlock_bh (seqlock_t *sl) +__acquires (sl) __no_context_analysis {spin_lock_bh (&sl->lock);do_write_seqcount_begin (&sl->seqcount.seqcount);
@@ -912,6 +918,7 @@ static inline void write_seqlock_bh(seqlock_t *sl)* write_seqlock_bh(). */ static inline void write_sequnlock_bh (seqlock_t *sl) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock_bh (&sl->lock);
@@ -925,6 +932,7 @@ static inline void write_sequnlock_bh(seqlock_t *sl)* other write sections, can be invoked from hardirq contexts. */ static inline void write_seqlock_irq (seqlock_t *sl) +__acquires (sl) __no_context_analysis {spin_lock_irq (&sl->lock);do_write_seqcount_begin (&sl->seqcount.seqcount);
@@ -938,12 +946,14 @@ static inline void write_seqlock_irq(seqlock_t *sl)* seqlock_t write side section opened with write_seqlock_irq(). */ static inline void write_sequnlock_irq (seqlock_t *sl) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock_irq (&sl->lock); }static inline unsigned long __write_seqlock_irqsave (seqlock_t *sl) +__acquires (sl) __no_context_analysis {unsigned long flags;
@@ -976,6 +986,7 @@ static inline unsigned long __write_seqlock_irqsave(seqlock_t *sl)*/ static inline void write_sequnlock_irqrestore (seqlock_t *sl,unsigned long flags) +__releases (sl) __no_context_analysis {do_write_seqcount_end (&sl->seqcount.seqcount);spin_unlock_irqrestore (&sl->lock, flags);
@@ -998,6 +1009,7 @@ write_sequnlock_irqrestore(seqlock_t *sl, unsigned long flags)* The opened read section must be closed with read_sequnlock_excl(). */ static inline void read_seqlock_excl (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {spin_lock (&sl->lock); }
@@ -1007,6 +1019,7 @@ static inline void read_seqlock_excl(seqlock_t *sl)* @sl: Pointer to seqlock_t */ static inline void read_sequnlock_excl (seqlock_t *sl) +__releases_shared (sl) __no_context_analysis {spin_unlock (&sl->lock); }
@@ -1021,6 +1034,7 @@ static inline void read_sequnlock_excl(seqlock_t *sl)* from softirq contexts. */ static inline void read_seqlock_excl_bh (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {spin_lock_bh (&sl->lock); }
@@ -1031,6 +1045,7 @@ static inline void read_seqlock_excl_bh(seqlock_t *sl)* @sl: Pointer to seqlock_t */ static inline void read_sequnlock_excl_bh (seqlock_t *sl) +__releases_shared (sl) __no_context_analysis {spin_unlock_bh (&sl->lock); }
@@ -1045,6 +1060,7 @@ static inline void read_sequnlock_excl_bh(seqlock_t *sl)* hardirq context. */ static inline void read_seqlock_excl_irq (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {spin_lock_irq (&sl->lock); }
@@ -1055,11 +1071,13 @@ static inline void read_seqlock_excl_irq(seqlock_t *sl)* @sl: Pointer to seqlock_t */ static inline void read_sequnlock_excl_irq (seqlock_t *sl) +__releases_shared (sl) __no_context_analysis {spin_unlock_irq (&sl->lock); }static inline unsigned long __read_seqlock_excl_irqsave (seqlock_t *sl) +__acquires_shared (sl) __no_context_analysis {unsigned long flags;
@@ -1089,6 +1107,7 @@ static inline unsigned long __read_seqlock_excl_irqsave(seqlock_t *sl)*/ static inline void read_sequnlock_excl_irqrestore (seqlock_t *sl,unsigned long flags) +__releases_shared (sl) __no_context_analysis {spin_unlock_irqrestore (&sl->lock, flags); }
@@ -1125,6 +1144,7 @@ read_sequnlock_excl_irqrestore(seqlock_t *sl, unsigned long flags)* parameter of the next read_seqbegin_or_lock() iteration. */ static inline void read_seqbegin_or_lock (seqlock_t *lock,int *seq) +__acquires_shared (lock) __no_context_analysis {if (!(*seq &1 ))/* Even */ *seq =read_seqbegin (lock);
@@ -1140,6 +1160,7 @@ static inline void read_seqbegin_or_lock(seqlock_t *lock, int *seq)* Return: true if a read section retry is required, false otherwise */ static inline int need_seqretry (seqlock_t *lock,int seq) +__releases_shared (lock) __no_context_analysis {return !(seq &1 ) &&read_seqretry (lock, seq); }
@@ -1153,6 +1174,7 @@ static inline int need_seqretry(seqlock_t *lock, int seq)* with read_seqbegin_or_lock() and validated by need_seqretry(). */ static inline void done_seqretry (seqlock_t *lock,int seq) + __no_context_analysis {if (seq &1 )read_sequnlock_excl (lock);
@@ -1180,6 +1202,7 @@ static inline void done_seqretry(seqlock_t *lock, int seq)*/ static inline unsigned long read_seqbegin_or_lock_irqsave (seqlock_t *lock,int *seq) +__acquires_shared (lock) __no_context_analysis {unsigned long flags =0 ;
@@ -1205,6 +1228,7 @@ read_seqbegin_or_lock_irqsave(seqlock_t *lock, int *seq)*/ static inline void done_seqretry_irqrestore (seqlock_t *lock,int seq,unsigned long flags) + __no_context_analysis {if (seq &1 )read_sequnlock_excl_irqrestore (lock, flags);
@@ -1225,6 +1249,7 @@ struct ss_tmp { }; static __always_inline void __scoped_seqlock_cleanup(struct ss_tmp *sst) + __no_context_analysis {if (sst->lock)spin_unlock (sst->lock);
@@ -1254,6 +1279,7 @@ extern void __scoped_seqlock_bug(void); static __always_inline void__scoped_seqlock_next (struct ss_tmp *sst,seqlock_t *lock,enum ss_state target) + __no_context_analysis {switch (sst->state) {case ss_done:
@@ -1296,9 +1322,19 @@ __scoped_seqlock_next(struct ss_tmp *sst, seqlock_t *lock, enum ss_state target) } } +/* +* Context analysis no-op helper to release seqlock at the end of the for-scope; +* the alias analysis of the compiler will recognize that the pointer @s is an +* alias to @_seqlock passed to read_seqbegin(_seqlock) below. +*/ +static __always_inline void __scoped_seqlock_cleanup_ctx(struct ss_tmp **s) + __releases_shared(*((seqlock_t **)s)) __no_context_analysis {} +#define __scoped_seqlock_read (_seqlock, _target, _s) \ for (struct ss_tmp _s __cleanup(__scoped_seqlock_cleanup) = \ - { .state = ss_lockless, .data = read_seqbegin(_seqlock) }; \ + { .state = ss_lockless, .data = read_seqbegin(_seqlock) }, \ + *__UNIQUE_ID(ctx) __cleanup(__scoped_seqlock_cleanup_ctx) =\ + (struct ss_tmp *)_seqlock; \ _s.state != ss_done; \ __scoped_seqlock_next(&_s, _seqlock, _target))
include/linux/seqlock_types.h +3 -2
@@ -81,13 +81,14 @@ SEQCOUNT_LOCKNAME(mutex, struct mutex, true, mutex)* - Comments on top of seqcount_t * - Documentation/locking/seqlock.rst */ -typedef struct { +context_lock_struct (seqlock) {/* * Make sure that readers don't starve writers on PREEMPT_RT: use * seqcount_spinlock_t instead of seqcount_t. Check __SEQ_LOCK(). */ seqcount_spinlock_t seqcount;spinlock_t lock; -}seqlock_t ; +}; +typedef struct seqlock seqlock_t ;#endif /* __LINUX_SEQLOCK_TYPES_H */
lib/test_context-analysis.c +50 -0
59 lines not on this page · raw message
Marco Elver
maintainerPATCH v5 12/36 bit_spinlock: Include missing <asm/processor.h>
In reply to Marco ElverIncluding <linux/bit_spinlock.h> into an empty TU will result in the compiler complaining:
./include/linux/bit_spinlock.h:34:4: error: call to undeclared function 'cpu_relax'; <...>
34 | cpu_relax();
| ^1 error generated.
Include <asm/processor.h> to allow including bit_spinlock.h where <asm/processor.h> is not otherwise included.
--- include/linux/bit_spinlock.h | 2 ++ 1 file changed, 2 insertions(+)
include/linux/bit_spinlock.h +2 -0
@@ -7,6 +7,8 @@#include <linux/atomic.h> #include <linux/bug.h> +#include <asm/processor.h> /* for cpu_relax() */ +/* * bit-based spin_lock() *
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Re: [PATCH v5 12/36] bit_spinlock: Include missing <asm/processor.h>
Quoted 21 lines · Marco Elver
Including <
linux/bit_spinlock.h> into an empty TU will result in the compiler complaining:
./include/linux/bit_spinlock.h:34:4: error: call to undeclared function 'cpu_relax'; <...>34 | cpu_relax(); | ^1 error generated.
Include <
asm/processor.h> to allow includingbit_spinlock.hwhere <asm/processor.h> is not otherwise included.Signed-off-by Marco Elver <[email protected]>--- include/linux/bit_spinlock.h | 2 ++ 1 file changed, 2 insertions(+)include/linux/bit_spinlock.h +0
-0
include/linux/bit_spinlock.h line 14
Quoted 8 lines
include/linux/bit_spinlock.h +2
-0@@ -7,6 +7,8 @@#include <linux/atomic.h> #include <linux/bug.h> +#include <asm/processor.h> /* for cpu_relax() */ +/* * bit-based spin_lock() *
The abbreviation "TU" is uncommon so it's probably a good idea to expand it. Anyway:
[tip: locking/core] bit_spinlock: Include missing <asm/processor.h>
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 5f7ba059710609bb997d50775ba92fbf29be51da Gitweb: https://git.kernel.org/tip/5f7ba059710609bb997d50775ba92fbf29be51da Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:01 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:29 +01:00
bit_spinlock: Include missing <asm/processor.h>
Including <linux/bit_spinlock.h> into an empty TU will result in the compiler complaining:
./include/linux/bit_spinlock.h:34:4: error: call to undeclared function 'cpu_relax'; <...>
34 | cpu_relax();
| ^1 error generated.
Include <asm/processor.h> to allow including bit_spinlock.h where <asm/processor.h> is not otherwise included.
--- include/linux/bit_spinlock.h | 2 ++ 1 file changed, 2 insertions(+)
include/linux/bit_spinlock.h +2 -0
@@ -7,6 +7,8 @@#include <linux/atomic.h> #include <linux/bug.h> +#include <asm/processor.h> /* for cpu_relax() */ +/* * bit-based spin_lock() *
Marco Elver
maintainerPATCH v5 13/36 bit_spinlock: Support Clang's context analysis
In reply to Marco ElverThe annotations for bit_spinlock.h have simply been using "bitlock" as the token. For Sparse, that was likely sufficient in most cases. But Clang's context analysis is more precise, and we need to ensure we can distinguish different bitlocks.
To do so, add a token context, and a macro __bitlock(bitnum, addr) that is used to construct unique per-bitlock tokens.
Add the appropriate test.
<linux/list_bl.h> is implicitly included through other includes, and requires 2 annotations to indicate that acquisition (without release) and release (without prior acquisition) of its bitlock is intended.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
--- Documentation/dev-tools/context-analysis.rst | 3 ++- include/linux/bit_spinlock.h | 22 ++++++++++++++--- include/linux/list_bl.h | 2 ++ lib/test_context-analysis.c | 26 ++++++++++++++++++++ 4 files changed, 48 insertions(+), 5 deletions(-)
Documentation/dev-tools/context-analysis.rst +2 -1
@@ -79,7 +79,8 @@ Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported: -`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`. +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, +`bit_spinlock`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/bit_spinlock.h +18 -4
@@ -9,6 +9,16 @@#include <asm/processor.h> /* for cpu_relax() */ +/* +* For static context analysis, we need a unique token for each possible bit +* that can be used as a bit_spinlock. The easiest way to do that is to create a +* fake context that we can cast to with the __bitlock(bitnum, addr) macro +* below, which will give us unique instances for each (bit, addr) pair that the +* static analysis can use. +*/ +context_lock_struct (__context_bitlock) { }; +#define __bitlock (bitnum, addr) (struct __context_bitlock *)(bitnum + (addr)) +/* * bit-based spin_lock() *
@@ -16,6 +26,7 @@* are significantly faster. */ static __always_inline void bit_spin_lock(int bitnum, unsigned long *addr) +__acquires (__bitlock (bitnum, addr)) {/* * Assuming the lock is uncontended, this never enters
@@ -34,13 +45,14 @@ static __always_inline void bit_spin_lock(int bitnum, unsigned long *addr)preempt_disable (); }#endif -__acquire (bitlock); +__acquire (__bitlock (bitnum, addr)); }/* * Return true if it was acquired */ static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr) +__cond_acquires (true,__bitlock (bitnum, addr)) {preempt_disable ();#if defined(CONFIG_SMP ) || defined(CONFIG_DEBUG_SPINLOCK )
@@ -49,7 +61,7 @@ static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr) return 0; }#endif -__acquire (bitlock); +__acquire (__bitlock (bitnum ,addr ));return 1 ; }
@@ -57,6 +69,7 @@ static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr)* bit-based spin_unlock() */ static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr) +__releases (__bitlock (bitnum, addr)) {#ifdef CONFIG_DEBUG_SPINLOCK BUG_ON (!test_bit (bitnum, addr));
@@ -65,7 +78,7 @@ static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr)clear_bit_unlock (bitnum, addr);#endif preempt_enable (); -__release (bitlock); +__release (__bitlock (bitnum, addr)); }/*
@@ -74,6 +87,7 @@ static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr)* protecting the rest of the flags in the word. */ static __always_inline void __bit_spin_unlock(int bitnum, unsigned long *addr) +__releases (__bitlock (bitnum, addr)) {#ifdef CONFIG_DEBUG_SPINLOCK BUG_ON (!test_bit (bitnum, addr));
@@ -82,7 +96,7 @@ static __always_inline void __bit_spin_unlock(int bitnum, unsigned long *addr)__clear_bit_unlock (bitnum, addr);#endif preempt_enable (); -__release (bitlock); +__release (__bitlock (bitnum, addr)); }/*
include/linux/list_bl.h +2 -0
@@ -144,11 +144,13 @@ static inline void hlist_bl_del_init(struct hlist_bl_node *n) }static inline void hlist_bl_lock (struct hlist_bl_head *b) +__acquires (__bitlock (0 , b)) {bit_spin_lock (0 , (unsigned long *)b); }static inline void hlist_bl_unlock (struct hlist_bl_head *b) +__releases (__bitlock (0 , b)) {__bit_spin_unlock (0 , (unsigned long *)b); }
lib/test_context-analysis.c +26 -0
@@ -4,6 +4,7 @@* positive errors when compiled with Clang's context analysis. */ +#include <linux/bit_spinlock.h> #include <linux/build_bug.h> #include <linux/mutex.h> #include <linux/seqlock.h>
@@ -258,3 +259,28 @@ static void __used test_seqlock_scoped(struct test_seqlock_data *d) (void )d->counter; } } + +struct test_bit_spinlock_data { +unsigned long bits; + int counter __guarded_by(__bitlock(3, &bits)); +}; + +static void __used test_bit_spin_lock (struct test_bit_spinlock_data *d) +{ +/* +* Note, the analysis seems to have false negatives, because it won't +* precisely recognize the bit of the fake __bitlock() token. +*/ +bit_spin_lock (3 , &d->bits); + d->counter++; +bit_spin_unlock (3 , &d->bits); + +bit_spin_lock (3 , &d->bits); + d->counter++; +__bit_spin_unlock (3 , &d->bits); + +if (bit_spin_trylock (3 , &d->bits)) { + d->counter++; +bit_spin_unlock (3 , &d->bits); + } +}
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 13/36] bit_spinlock: Support Clang's context analysis
include/linux/bit_spinlock.h line 20
Quoted 9 lines · Marco Elver
include/linux/bit_spinlock.h +9
-0+/* +* For static context analysis, we need a unique token for each possible bit +* that can be used as a bit_spinlock. The easiest way to do that is to create a +* fake context that we can cast to with the __bitlock(bitnum, addr) macro +* below, which will give us unique instances for each (bit, addr) pair that the +* static analysis can use. +*/ +context_lock_struct (__context_bitlock) { }; +#define __bitlock (bitnum, addr) (struct __context_bitlock *)(bitnum + (addr))
Will this cause static analyzers to complain about out-of-bounds accesses for (bitnum + (addr)), which is equivalent to &(addr)[bitnum]?
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 13/36] bit_spinlock: Support Clang's context analysis
Quoted 14 lines · Bart Van Assche' via kasan-dev
include/linux/bit_spinlock.h line 20
Quoted 9 lines · Marco Elver
include/linux/bit_spinlock.h +9
-0+/* +* For static context analysis, we need a unique token for each possible bit +* that can be used as a bit_spinlock. The easiest way to do that is to create a +* fake context that we can cast to with the __bitlock(bitnum, addr) macro +* below, which will give us unique instances for each (bit, addr) pair that the +* static analysis can use. +*/ +context_lock_struct (__context_bitlock) { }; +#define __bitlock (bitnum, addr) (struct __context_bitlock *)(bitnum + (addr))Will this cause static analyzers to complain about out-of-bounds accesses for (bitnum + (addr)), which is equivalent to &(addr)[bitnum]?
Only if they decide to interpret never-executed code (i think the kernel has various dead code that's optimized out that might trigger static analyzers if they analyzed it).
But this could probably be improved by using a different idiom, and using an empty inline function that takes bitnum, addr as args, and Clang simply takes the call to that function as the context lock identity.
[tip: locking/core] bit_spinlock: Support Clang's context analysis
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: eb7d96a13bf45f86909006a59e7855d8810f020a Gitweb: https://git.kernel.org/tip/eb7d96a13bf45f86909006a59e7855d8810f020a Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:02 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:30 +01:00
bit_spinlock: Support Clang's context analysis
The annotations for bit_spinlock.h have simply been using "bitlock" as the token. For Sparse, that was likely sufficient in most cases. But Clang's context analysis is more precise, and we need to ensure we can distinguish different bitlocks.
To do so, add a token context, and a macro __bitlock(bitnum, addr) that is used to construct unique per-bitlock tokens.
Add the appropriate test.
<linux/list_bl.h> is implicitly included through other includes, and requires 2 annotations to indicate that acquisition (without release) and release (without prior acquisition) of its bitlock is intended.
--- Documentation/dev-tools/context-analysis.rst | 3 +- include/linux/bit_spinlock.h | 22 +++++++++++++--- include/linux/list_bl.h | 2 +- lib/test_context-analysis.c | 26 +++++++++++++++++++- 4 files changed, 48 insertions(+), 5 deletions(-)
Documentation/dev-tools/context-analysis.rst +2 -1
@@ -79,7 +79,8 @@ Supported Kernel Primitives ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported: -`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`. +`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, +`bit_spinlock`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/bit_spinlock.h +18 -4
@@ -10,12 +10,23 @@#include <asm/processor.h> /* for cpu_relax() */ /* +* For static context analysis, we need a unique token for each possible bit +* that can be used as a bit_spinlock. The easiest way to do that is to create a +* fake context that we can cast to with the __bitlock(bitnum, addr) macro +* below, which will give us unique instances for each (bit, addr) pair that the +* static analysis can use. +*/ +context_lock_struct (__context_bitlock) { }; +#define __bitlock (bitnum, addr) (struct __context_bitlock *)(bitnum + (addr)) + +/* * bit-based spin_lock() * * Don't use this unless you really need to: spin_lock() and spin_unlock() * are significantly faster. */ static __always_inline void bit_spin_lock(int bitnum, unsigned long *addr) +__acquires (__bitlock (bitnum, addr)) {/* * Assuming the lock is uncontended, this never enters
@@ -34,13 +45,14 @@ static __always_inline void bit_spin_lock(int bitnum, unsigned long *addr)preempt_disable (); }#endif -__acquire (bitlock); +__acquire (__bitlock (bitnum, addr)); }/* * Return true if it was acquired */ static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr) +__cond_acquires (true,__bitlock (bitnum, addr)) {preempt_disable ();#if defined(CONFIG_SMP ) || defined(CONFIG_DEBUG_SPINLOCK )
@@ -49,7 +61,7 @@ static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr) return 0; }#endif -__acquire (bitlock); +__acquire (__bitlock (bitnum ,addr ));return 1 ; }
@@ -57,6 +69,7 @@ static __always_inline int bit_spin_trylock(int bitnum, unsigned long *addr)* bit-based spin_unlock() */ static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr) +__releases (__bitlock (bitnum, addr)) {#ifdef CONFIG_DEBUG_SPINLOCK BUG_ON (!test_bit (bitnum, addr));
@@ -65,7 +78,7 @@ static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr)clear_bit_unlock (bitnum, addr);#endif preempt_enable (); -__release (bitlock); +__release (__bitlock (bitnum, addr)); }/*
@@ -74,6 +87,7 @@ static __always_inline void bit_spin_unlock(int bitnum, unsigned long *addr)* protecting the rest of the flags in the word. */ static __always_inline void __bit_spin_unlock(int bitnum, unsigned long *addr) +__releases (__bitlock (bitnum, addr)) {#ifdef CONFIG_DEBUG_SPINLOCK BUG_ON (!test_bit (bitnum, addr));
@@ -82,7 +96,7 @@ static __always_inline void __bit_spin_unlock(int bitnum, unsigned long *addr)__clear_bit_unlock (bitnum, addr);#endif preempt_enable (); -__release (bitlock); +__release (__bitlock (bitnum, addr)); }/*
include/linux/list_bl.h +2 -0
@@ -144,11 +144,13 @@ static inline void hlist_bl_del_init(struct hlist_bl_node *n) }static inline void hlist_bl_lock (struct hlist_bl_head *b) +__acquires (__bitlock (0 , b)) {bit_spin_lock (0 , (unsigned long *)b); }static inline void hlist_bl_unlock (struct hlist_bl_head *b) +__releases (__bitlock (0 , b)) {__bit_spin_unlock (0 , (unsigned long *)b); }
lib/test_context-analysis.c +26 -0
@@ -4,6 +4,7 @@* positive errors when compiled with Clang's context analysis. */ +#include <linux/bit_spinlock.h> #include <linux/build_bug.h> #include <linux/mutex.h> #include <linux/seqlock.h>
@@ -258,3 +259,28 @@ static void __used test_seqlock_scoped(struct test_seqlock_data *d) (void )d->counter; } } + +struct test_bit_spinlock_data { +unsigned long bits; + int counter __guarded_by(__bitlock(3, &bits)); +}; + +static void __used test_bit_spin_lock (struct test_bit_spinlock_data *d) +{ +/* +* Note, the analysis seems to have false negatives, because it won't +* precisely recognize the bit of the fake __bitlock() token. +*/ +bit_spin_lock (3 , &d->bits); + d->counter++; +bit_spin_unlock (3 , &d->bits); + +bit_spin_lock (3 , &d->bits); + d->counter++; +__bit_spin_unlock (3 , &d->bits); + +if (bit_spin_trylock (3 , &d->bits)) { + d->counter++; +bit_spin_unlock (3 , &d->bits); + } +}
Marco Elver
maintainerPATCH v5 14/36 rcu: Support Clang's context analysis
In reply to Marco ElverImprove the existing annotations to properly support Clang's context analysis.
The old annotations distinguished between RCU, RCU_BH, and RCU_SCHED; however, to more easily be able to express that "hold the RCU read lock" without caring if the normal, _bh(), or _sched() variant was used we'd have to remove the distinction of the latter variants: change the _bh() and _sched() variants to also acquire "RCU".
When (and if) we introduce context locks to denote more generally that "IRQ", "BH", "PREEMPT" contexts are disabled, it would make sense to acquire these instead of RCU_BH and RCU_SCHED respectively.
The above change also simplified introducing __guarded_by support, where only the "RCU" context lock needs to be held: introduce __rcu_guarded, where Clang's context analysis warns if a pointer is dereferenced without any of the RCU locks held, or updated without the appropriate helpers.
The primitives rcu_assign_pointer() and friends are wrapped with context_unsafe(), which enforces using them to update RCU-protected pointers marked with __rcu_guarded.
---
v5:
* Rename "context guard" -> "context lock".
v3:
* Properly support reentrancy via new compiler support.
v2:
* Reword commit message and point out reentrancy caveat.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/rcupdate.h | 77 ++++++++++++------ lib/test_context-analysis.c | 85 ++++++++++++++++++++ 3 files changed, 139 insertions(+), 25 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`. +`bit_spinlock`, RCU. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/rcupdate.h +53 -24
229 lines not on this page · raw message
lib/test_context-analysis.c +85 -0
94 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] rcu: Support Clang's context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: fe00f6e84621ad441aa99005f2f0fefd0e5e1a2c Gitweb: https://git.kernel.org/tip/fe00f6e84621ad441aa99005f2f0fefd0e5e1a2c Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:03 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:30 +01:00
rcu: Support Clang's context analysis
Improve the existing annotations to properly support Clang's context analysis.
The old annotations distinguished between RCU, RCU_BH, and RCU_SCHED; however, to more easily be able to express that "hold the RCU read lock" without caring if the normal, _bh(), or _sched() variant was used we'd have to remove the distinction of the latter variants: change the _bh() and _sched() variants to also acquire "RCU".
When (and if) we introduce context locks to denote more generally that "IRQ", "BH", "PREEMPT" contexts are disabled, it would make sense to acquire these instead of RCU_BH and RCU_SCHED respectively.
The above change also simplified introducing __guarded_by support, where only the "RCU" context lock needs to be held: introduce __rcu_guarded, where Clang's context analysis warns if a pointer is dereferenced without any of the RCU locks held, or updated without the appropriate helpers.
The primitives rcu_assign_pointer() and friends are wrapped with context_unsafe(), which enforces using them to update RCU-protected pointers marked with __rcu_guarded.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/rcupdate.h | 77 +++++++++++------ lib/test_context-analysis.c | 85 +++++++++++++++++++- 3 files changed, 139 insertions(+), 25 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`. +`bit_spinlock`, RCU. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/rcupdate.h +53 -24
229 lines not on this page · raw message
lib/test_context-analysis.c +85 -0
94 lines not on this page · raw message
Marco Elver
maintainerPATCH v5 15/36 srcu: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for SRCU.
---
v5:
* Fix up annotation for recently added SRCU interfaces.
* Rename "context guard" -> "context lock".
* Use new cleanup.h helpers to properly support scoped lock guards.
v4:
* Rename capability -> context analysis.
v3:
* Switch to DECLARE_LOCK_GUARD_1_ATTRS() (suggested by Peter)
* Support SRCU being reentrant.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/srcu.h | 73 ++++++++++++++------ include/linux/srcutiny.h | 6 ++ include/linux/srcutree.h | 10 ++- lib/test_context-analysis.c | 25 +++++++ 5 files changed, 91 insertions(+), 25 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU. +`bit_spinlock`, RCU, SRCU (`srcu_struct`). For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/srcu.h +50 -23
220 lines not on this page · raw message
include/linux/srcutiny.h +6 -0
@@ -73,6 +73,7 @@ void synchronize_srcu(struct srcu_struct *ssp);* index that must be passed to the matching srcu_read_unlock(). */ static inline int __srcu_read_lock (struct srcu_struct *ssp) +__acquires_shared (ssp) {int idx;
@@ -80,6 +81,7 @@ static inline int __srcu_read_lock(struct srcu_struct *ssp) idx = ((READ_ONCE (ssp->srcu_idx) +1 ) &0x2 ) >>1 ;WRITE_ONCE (ssp->srcu_lock_nesting[idx],READ_ONCE (ssp->srcu_lock_nesting[idx]) +1 );preempt_enable (); +__acquire_shared (ssp);return idx; }
@@ -96,22 +98,26 @@ static inline struct srcu_ctr __percpu *__srcu_ctr_to_ptr(struct srcu_struct *ss }static inline struct srcu_ctr __percpu *__srcu_read_lock_fast (struct srcu_struct *ssp) +__acquires_shared (ssp) {return __srcu_ctr_to_ptr (ssp,__srcu_read_lock (ssp)); }static inline void __srcu_read_unlock_fast (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) {__srcu_read_unlock (ssp,__srcu_ptr_to_ctr (ssp, scp)); }static inline struct srcu_ctr __percpu *__srcu_read_lock_fast_updown (struct srcu_struct *ssp) +__acquires_shared (ssp) {return __srcu_ctr_to_ptr (ssp,__srcu_read_lock (ssp)); }static inline void __srcu_read_unlock_fast_updown (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) {__srcu_read_unlock (ssp,__srcu_ptr_to_ctr (ssp, scp)); }
include/linux/srcutree.h +9 -1
@@ -233,7 +233,7 @@ struct srcu_struct {#define DEFINE_STATIC_SRCU_FAST_UPDOWN (name) \ __DEFINE_SRCU(name, SRCU_READ_FLAVOR_FAST_UPDOWN, static) -int __srcu_read_lock(struct srcu_struct *ssp) __acquires(ssp); +int __srcu_read_lock(struct srcu_struct *ssp) __acquires_shared(ssp);void synchronize_srcu_expedited (struct srcu_struct *ssp);void srcu_barrier (struct srcu_struct *ssp);void srcu_expedite_current (struct srcu_struct *ssp);
@@ -286,6 +286,7 @@ static inline struct srcu_ctr __percpu *__srcu_ctr_to_ptr(struct srcu_struct *ss* implementations of this_cpu_inc(). */ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast(struct srcu_struct *ssp) +__acquires_shared (ssp) {struct srcu_ctr __percpu *scp =READ_ONCE (ssp->srcu_ctrp);
@@ -294,6 +295,7 @@ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast(struct srcelse atomic_long_inc (raw_cpu_ptr (&scp->srcu_locks));// Y, and implicit RCU reader. barrier ();/* Avoid leaking the critical section. */ +__acquire_shared (ssp);return scp; }
@@ -308,7 +310,9 @@ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast(struct src*/ static inline void notrace__srcu_read_unlock_fast (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) { +__release_shared (ssp);barrier ();/* Avoid leaking the critical section. */ if (!IS_ENABLED (CONFIG_NEED_SRCU_NMI_SAFE ))this_cpu_inc (scp->srcu_unlocks.counter);// Z, and implicit RCU reader.
@@ -326,6 +330,7 @@ __srcu_read_unlock_fast(struct srcu_struct *ssp, struct srcu_ctr __percpu *scp)*/ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast_updown(struct srcu_struct *ssp) +__acquires_shared (ssp) {struct srcu_ctr __percpu *scp =READ_ONCE (ssp->srcu_ctrp);
@@ -334,6 +339,7 @@ struct srcu_ctr __percpu notrace *__srcu_read_lock_fast_updown(struct srcu_strucelse atomic_long_inc (raw_cpu_ptr (&scp->srcu_locks));// Y, and implicit RCU reader. barrier ();/* Avoid leaking the critical section. */ +__acquire_shared (ssp);return scp; }
@@ -348,7 +354,9 @@ struct srcu_ctr __percpu notrace *__srcu_read_lock_fast_updown(struct srcu_struc*/ static inline void notrace__srcu_read_unlock_fast_updown (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) { +__release_shared (ssp);barrier ();/* Avoid leaking the critical section. */ if (!IS_ENABLED (CONFIG_NEED_SRCU_NMI_SAFE ))this_cpu_inc (scp->srcu_unlocks.counter);// Z, and implicit RCU reader.
lib/test_context-analysis.c +25 -0
@@ -10,6 +10,7 @@#include <linux/rcupdate.h> #include <linux/seqlock.h> #include <linux/spinlock.h> +#include <linux/srcu.h> /* * Test that helper macros work as expected.
@@ -369,3 +370,27 @@ static void __used test_rcu_assert_variants(void)lockdep_assert_in_rcu_read_lock_sched ();wants_rcu_held_sched (); } + +struct test_srcu_data { +struct srcu_struct srcu; +long __rcu_guarded *data; +}; + +static void __used test_srcu (struct test_srcu_data *d) +{ +init_srcu_struct (&d->srcu); + +int idx =srcu_read_lock (&d->srcu); +long *data =srcu_dereference (d->data, &d->srcu); + (void )data; +srcu_read_unlock (&d->srcu, idx); + +rcu_assign_pointer (d->data,NULL ); +} + +static void __used test_srcu_guard (struct test_srcu_data *d) +{ + {guard (srcu)(&d->srcu); (void )srcu_dereference (d->data, &d->srcu); } + {guard (srcu_fast)(&d->srcu); (void )srcu_dereference (d->data, &d->srcu); } + {guard (srcu_fast_notrace)(&d->srcu); (void )srcu_dereference (d->data, &d->srcu); } +}
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] srcu: Support Clang's context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: f0b7ce22d71810c8c11abcd912fbd6f57c2e9677 Gitweb: https://git.kernel.org/tip/f0b7ce22d71810c8c11abcd912fbd6f57c2e9677 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:04 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:30 +01:00
srcu: Support Clang's context analysis
Add support for Clang's context analysis for SRCU.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/srcu.h | 73 +++++++++++++------ include/linux/srcutiny.h | 6 ++- include/linux/srcutree.h | 10 ++- lib/test_context-analysis.c | 25 +++++++- 5 files changed, 91 insertions(+), 25 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU. +`bit_spinlock`, RCU, SRCU (`srcu_struct`). For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/srcu.h +50 -23
220 lines not on this page · raw message
include/linux/srcutiny.h +6 -0
@@ -73,6 +73,7 @@ void synchronize_srcu(struct srcu_struct *ssp);* index that must be passed to the matching srcu_read_unlock(). */ static inline int __srcu_read_lock (struct srcu_struct *ssp) +__acquires_shared (ssp) {int idx;
@@ -80,6 +81,7 @@ static inline int __srcu_read_lock(struct srcu_struct *ssp) idx = ((READ_ONCE (ssp->srcu_idx) +1 ) &0x2 ) >>1 ;WRITE_ONCE (ssp->srcu_lock_nesting[idx],READ_ONCE (ssp->srcu_lock_nesting[idx]) +1 );preempt_enable (); +__acquire_shared (ssp);return idx; }
@@ -96,22 +98,26 @@ static inline struct srcu_ctr __percpu *__srcu_ctr_to_ptr(struct srcu_struct *ss }static inline struct srcu_ctr __percpu *__srcu_read_lock_fast (struct srcu_struct *ssp) +__acquires_shared (ssp) {return __srcu_ctr_to_ptr (ssp,__srcu_read_lock (ssp)); }static inline void __srcu_read_unlock_fast (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) {__srcu_read_unlock (ssp,__srcu_ptr_to_ctr (ssp, scp)); }static inline struct srcu_ctr __percpu *__srcu_read_lock_fast_updown (struct srcu_struct *ssp) +__acquires_shared (ssp) {return __srcu_ctr_to_ptr (ssp,__srcu_read_lock (ssp)); }static inline void __srcu_read_unlock_fast_updown (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) {__srcu_read_unlock (ssp,__srcu_ptr_to_ctr (ssp, scp)); }
include/linux/srcutree.h +9 -1
@@ -233,7 +233,7 @@ struct srcu_struct {#define DEFINE_STATIC_SRCU_FAST_UPDOWN (name) \ __DEFINE_SRCU(name, SRCU_READ_FLAVOR_FAST_UPDOWN, static) -int __srcu_read_lock(struct srcu_struct *ssp) __acquires(ssp); +int __srcu_read_lock(struct srcu_struct *ssp) __acquires_shared(ssp);void synchronize_srcu_expedited (struct srcu_struct *ssp);void srcu_barrier (struct srcu_struct *ssp);void srcu_expedite_current (struct srcu_struct *ssp);
@@ -286,6 +286,7 @@ static inline struct srcu_ctr __percpu *__srcu_ctr_to_ptr(struct srcu_struct *ss* implementations of this_cpu_inc(). */ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast(struct srcu_struct *ssp) +__acquires_shared (ssp) {struct srcu_ctr __percpu *scp =READ_ONCE (ssp->srcu_ctrp);
@@ -294,6 +295,7 @@ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast(struct srcelse atomic_long_inc (raw_cpu_ptr (&scp->srcu_locks));// Y, and implicit RCU reader. barrier ();/* Avoid leaking the critical section. */ +__acquire_shared (ssp);return scp; }
@@ -308,7 +310,9 @@ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast(struct src*/ static inline void notrace__srcu_read_unlock_fast (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) { +__release_shared (ssp);barrier ();/* Avoid leaking the critical section. */ if (!IS_ENABLED (CONFIG_NEED_SRCU_NMI_SAFE ))this_cpu_inc (scp->srcu_unlocks.counter);// Z, and implicit RCU reader.
@@ -326,6 +330,7 @@ __srcu_read_unlock_fast(struct srcu_struct *ssp, struct srcu_ctr __percpu *scp)*/ static inline struct srcu_ctr __percpu notrace *__srcu_read_lock_fast_updown(struct srcu_struct *ssp) +__acquires_shared (ssp) {struct srcu_ctr __percpu *scp =READ_ONCE (ssp->srcu_ctrp);
@@ -334,6 +339,7 @@ struct srcu_ctr __percpu notrace *__srcu_read_lock_fast_updown(struct srcu_strucelse atomic_long_inc (raw_cpu_ptr (&scp->srcu_locks));// Y, and implicit RCU reader. barrier ();/* Avoid leaking the critical section. */ +__acquire_shared (ssp);return scp; }
@@ -348,7 +354,9 @@ struct srcu_ctr __percpu notrace *__srcu_read_lock_fast_updown(struct srcu_struc*/ static inline void notrace__srcu_read_unlock_fast_updown (struct srcu_struct *ssp,struct srcu_ctr __percpu *scp) +__releases_shared (ssp) { +__release_shared (ssp);barrier ();/* Avoid leaking the critical section. */ if (!IS_ENABLED (CONFIG_NEED_SRCU_NMI_SAFE ))this_cpu_inc (scp->srcu_unlocks.counter);// Z, and implicit RCU reader.
lib/test_context-analysis.c +25 -0
@@ -10,6 +10,7 @@#include <linux/rcupdate.h> #include <linux/seqlock.h> #include <linux/spinlock.h> +#include <linux/srcu.h> /* * Test that helper macros work as expected.
@@ -369,3 +370,27 @@ static void __used test_rcu_assert_variants(void)lockdep_assert_in_rcu_read_lock_sched ();wants_rcu_held_sched (); } + +struct test_srcu_data { +struct srcu_struct srcu; +long __rcu_guarded *data; +}; + +static void __used test_srcu (struct test_srcu_data *d) +{ +init_srcu_struct (&d->srcu); + +int idx =srcu_read_lock (&d->srcu); +long *data =srcu_dereference (d->data, &d->srcu); + (void )data; +srcu_read_unlock (&d->srcu, idx); + +rcu_assign_pointer (d->data,NULL ); +} + +static void __used test_srcu_guard (struct test_srcu_data *d) +{ + {guard (srcu)(&d->srcu); (void )srcu_dereference (d->data, &d->srcu); } + {guard (srcu_fast)(&d->srcu); (void )srcu_dereference (d->data, &d->srcu); } + {guard (srcu_fast_notrace)(&d->srcu); (void )srcu_dereference (d->data, &d->srcu); } +}
Bart Van Assche
reviewerRe: [PATCH v5 15/36] srcu: Support Clang's context analysis
In reply to Marco ElverQuoted 17 lines · Marco Elver
include/linux/srcu.h +8
-2+/* +* No-op helper to denote that ssp must be held. Because SRCU-protected pointers +* should still be marked with __rcu_guarded, and we do not want to mark them +* with __guarded_by(ssp) as it would complicate annotations for writers, we +* choose the following strategy: srcu_dereference_check() calls this helper +* that checks that the passed ssp is held, and then fake-acquires 'RCU'. +*/ +static inline void __srcu_read_lock_must_hold (const struct srcu_struct *ssp)__must_hold_shared (ssp) { }/** * srcu_dereference_check - fetch SRCU-protected pointer for later dereferencing @@ -223,9 +233,15 @@ static inline int srcu_read_lock_held(const struct srcu_struct *ssp)* to 1. The @c argument will normally be a logical expression containing * lockdep_is_held() calls. */ -#define srcu_dereference_check (p, ssp, c) \ - __rcu_dereference_check((p), __UNIQUE_ID(rcu), \
include/linux/srcu.h static inline int srcu_read_lock_held(const struct srcu_struct *ssp) · line 244
Quoted 10 lines
include/linux/srcu.h +9
-1- (c) || srcu_read_lock_held(ssp), __rcu) +#define srcu_dereference_check (p, ssp, c) \ +({ \ + __srcu_read_lock_must_hold(ssp); \ + __acquire_shared_ctx_lock(RCU); \ + __auto_type __v = __rcu_dereference_check((p), __UNIQUE_ID(rcu), \ + (c) || srcu_read_lock_held(ssp), __rcu); \ + __release_shared_ctx_lock(RCU); \ + __v; \ +})
Hi Marco,
The above change is something I'm not happy about. The original implementation of the srcu_dereference_check() macro shows that it is sufficient to either hold an SRCU reader lock or the updater lock ('c'). The addition of "__srcu_read_lock_must_hold()" will cause compilation to fail if the caller doesn't hold an SRCU reader lock. I'm concerned that this will either lead to adding __no_context_analysis to SRCU updater code that uses srcu_dereference_check() or to adding misleading __assume_ctx_lock(ssp) annotations in SRCU updater code.
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 15/36] srcu: Support Clang's context analysis
Quoted 30 lines · Bart Van Assche
Quoted 16 lines · Marco Elver
include/linux/srcu.h +8
-2+/* +* No-op helper to denote that ssp must be held. Because SRCU-protected pointers +* should still be marked with __rcu_guarded, and we do not want to mark them +* with __guarded_by(ssp) as it would complicate annotations for writers, we +* choose the following strategy: srcu_dereference_check() calls this helper +* that checks that the passed ssp is held, and then fake-acquires 'RCU'. +*/ +static inline void __srcu_read_lock_must_hold (const struct srcu_struct *ssp)__must_hold_shared (ssp) { }/** * srcu_dereference_check - fetch SRCU-protected pointer for later dereferencing @@ -223,9 +233,15 @@ static inline int srcu_read_lock_held(const struct srcu_struct *ssp)* to 1. The @c argument will normally be a logical expression containing * lockdep_is_held() calls. */ -#define srcu_dereference_check (p, ssp, c) \ - __rcu_dereference_check((p), __UNIQUE_ID(rcu), \include/linux/srcu.h static inline int srcu_read_lock_held(const struct srcu_struct *ssp) · line 244
Quoted 10 lines
include/linux/srcu.h +9
-1- (c) || srcu_read_lock_held(ssp), __rcu) +#define srcu_dereference_check (p, ssp, c) \ +({ \ + __srcu_read_lock_must_hold(ssp); \ + __acquire_shared_ctx_lock(RCU); \ + __auto_type __v = __rcu_dereference_check((p), __UNIQUE_ID(rcu), \ + (c) || srcu_read_lock_held(ssp), __rcu); \ + __release_shared_ctx_lock(RCU); \ + __v; \ +})Hi Marco,
Quoted 8 lines
The above change is something I'm not happy about. The original implementation of the
srcu_dereference_check()macro shows that it is sufficient to either hold an SRCU reader lock or the updater lock ('c'). The addition of "__srcu_read_lock_must_hold()" will cause compilation to fail if the caller doesn't hold an SRCU reader lock. I'm concerned that this will either lead to adding__no_context_analysisto SRCU updater code that usessrcu_dereference_check()or to adding misleading__assume_ctx_lock(ssp)annotations in SRCU updater code.
Right, and it doesn't help 'c' is an arbitrary condition. But it's fundamentally difficult to say "hold either this or that lock".
That being said, I don't think it's wrong to write e.g.:
spin_lock(&updater_lock); __acquire_shared(ssp); ... // writes happen through rcu_assign_pointer() // reads can happen through srcu_dereference_check() ... __release_shared(ssp); spin_unlock(&updater_lock);
, given holding the updater lock implies reader access.
And given the analysis is opt-in (CONTEXT_ANALYSIS := y), I think it's a manageable problem.
If you have a different idea how we can solve this, please let us know.
One final note, usage of srcu_dereference_check() is rare enough:
arch/x86/kvm/hyperv.c: irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu, arch/x86/kvm/x86.c: kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1)); arch/x86/kvm/x86.c: kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1)); drivers/gpio/gpiolib.c: label = srcu_dereference_check(desc->label, &desc->gdev->desc_srcu, drivers/hv/mshv_irq.c: girq_tbl = srcu_dereference_check(partition->pt_girq_tbl, drivers/hwtracing/stm/core.c: link = srcu_dereference_check(src->link, &stm_source_srcu, 1); drivers/infiniband/hw/hfi1/user_sdma.c: pq = srcu_dereference_check(fd->pq, &fd->pq_srcu, fs/quota/dquot.c: struct dquot *dquot = srcu_dereference_check( fs/quota/dquot.c: struct dquot *dquot = srcu_dereference_check( fs/quota/dquot.c: put[cnt] = srcu_dereference_check(dquots[cnt], &dquot_srcu, fs/quota/dquot.c: transfer_from[cnt] = srcu_dereference_check(dquots[cnt], include/linux/kvm_host.h: return srcu_dereference_check(kvm->memslots[as_id], &kvm->srcu, virt/kvm/irqchip.c: irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu,
, that I think it's easy enough to annotate these places with the above suggestions in case you're trying out global enablement.
Bart Van Assche
reviewerRe: [PATCH v5 15/36] srcu: Support Clang's context analysis
Quoted 11 lines · Marco Elver
That being said, I don't think it's wrong to write e.g.:
spin_lock(&updater_lock); __acquire_shared(ssp); ... // writes happen through rcu_assign_pointer() // reads can happen through srcu_dereference_check() ... __release_shared(ssp); spin_unlock(&updater_lock);
Quoted 4 lines
, given holding the updater lock implies reader access.
And given the analysis is opt-in (
CONTEXT_ANALYSIS:= y), I think it's a manageable problem.
I'd like to make context-analysis mandatory for the entire kernel tree.
Quoted 18 lines
If you have a different idea how we can solve this, please let us know.
One final note, usage of
srcu_dereference_check()is rare enough:arch/x86/kvm/hyperv.c: irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu, arch/x86/kvm/x86.c: kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1)); arch/x86/kvm/x86.c: kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1)); drivers/gpio/gpiolib.c: label = srcu_dereference_check(desc->label, &desc->gdev->desc_srcu, drivers/hv/mshv_irq.c: girq_tbl = srcu_dereference_check(partition->pt_girq_tbl, drivers/hwtracing/stm/core.c: link = srcu_dereference_check(src->link, &stm_source_srcu, 1); drivers/infiniband/hw/hfi1/user_sdma.c: pq = srcu_dereference_check(fd->pq, &fd->pq_srcu, fs/quota/dquot.c: struct dquot *dquot = srcu_dereference_check( fs/quota/dquot.c: struct dquot *dquot = srcu_dereference_check( fs/quota/dquot.c: put[cnt] = srcu_dereference_check(dquots[cnt], &dquot_srcu, fs/quota/dquot.c: transfer_from[cnt] = srcu_dereference_check(dquots[cnt], include/linux/kvm_host.h: return srcu_dereference_check(kvm->memslots[as_id], &kvm->srcu, virt/kvm/irqchip.c: irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu,
Quoted 2 lines
, that I think it's easy enough to annotate these places with the above suggestions in case you're trying out global enablement.
Has it ever been considered to add support in the clang compiler for a variant of __must_hold() that expresses that one of two capabilities must be held by the caller? I think that would remove the need to annotate SRCU update-side code with __acquire_shared(ssp) and __release_shared(ssp).
Thanks,
Bart.
Peter Zijlstra
maintainerRe: [PATCH v5 15/36] srcu: Support Clang's context analysis
Quoted 5 lines · Bart Van Assche
Has it ever been considered to add support in the clang compiler for a variant of
__must_hold()that expresses that one of two capabilities must be held by the caller? I think that would remove the need to annotate SRCU update-side code with__acquire_shared(ssp)and__release_shared(ssp).
Right, I think I've asked for logical operators like that. Although I think it was in the __guarded_by() clause rather than the __must_hold(). Both || and && would be nice to have ;-)
Specifically, I think I asked for something like:
cpumask_t cpus_allowed __guarded_by(pi_lock && rq->__lock)
__guarded_shared_by(pi_lock || rq->__lock);I think Marco's suggestion was to use 'fake' locks to mimic those semantics.
Marco Elver
maintainerRe: [PATCH v5 15/36] srcu: Support Clang's context analysis
Quoted 9 lines · Peter Zijlstra
Quoted 5 lines · Bart Van Assche
Has it ever been considered to add support in the clang compiler for a variant of
__must_hold()that expresses that one of two capabilities must be held by the caller? I think that would remove the need to annotate SRCU update-side code with__acquire_shared(ssp)and__release_shared(ssp).
Quoted 3 lines
Right, I think I've asked for logical operators like that. Although I think it was in the
__guarded_by()clause rather than the__must_hold(). Both || and && would be nice to have ;-)
Some attributes take multiple arguments (__must_hold does), though __guarded_by doesn't. Yet, && can still be had with adding it multiple times e.g. '__guarded_by(pi_lock) __guarded_by(rq->__lock)'.
Only thing that doesn't exist is ||. I think the syntax you ask for won't fly, but I can add it to the backlog to investigate an _any variant of these attributes. Don't hold your breath though, given the time it takes to land all that in a released Clang version.
Quoted 8 lines
Specifically, I think I asked for something like:
cpumask_t cpus_allowed __guarded_by(pi_lock && rq->__lock) __guarded_shared_by(pi_lock || rq->__lock);I think Marco's suggestion was to use 'fake' locks to mimic those semantics.
Marco Elver
maintainerPATCH v5 16/36 kref: Add context-analysis annotations
In reply to Marco ElverMark functions that conditionally acquire the passed lock.
--- include/linux/kref.h | 2 ++ 1 file changed, 2 insertions(+)
include/linux/kref.h +2 -0
@@ -81,6 +81,7 @@ static inline int kref_put(struct kref *kref, void (*release)(struct kref *kref)static inline int kref_put_mutex (struct kref *kref,void (*release)(struct kref *kref),struct mutex *mutex) +__cond_acquires (true, mutex) {if (refcount_dec_and_mutex_lock (&kref->refcount, mutex)) {release (kref);
@@ -102,6 +103,7 @@ static inline int kref_put_mutex(struct kref *kref,static inline int kref_put_lock (struct kref *kref,void (*release)(struct kref *kref),spinlock_t *lock) +__cond_acquires (true, lock) {if (refcount_dec_and_lock (&kref->refcount, lock)) {release (kref);
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Re: [PATCH v5 16/36] kref: Add context-analysis annotations
Quoted 1 line · Marco Elver
Mark functions that conditionally acquire the passed lock.
[tip: locking/core] kref: Add context-analysis annotations
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 5e256db9325e75e9f000ddd64e4f1dbd2a6d8acd Gitweb: https://git.kernel.org/tip/5e256db9325e75e9f000ddd64e4f1dbd2a6d8acd Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:05 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:31 +01:00
kref: Add context-analysis annotations
Mark functions that conditionally acquire the passed lock.
--- include/linux/kref.h | 2 ++ 1 file changed, 2 insertions(+)
include/linux/kref.h +2 -0
@@ -81,6 +81,7 @@ static inline int kref_put(struct kref *kref, void (*release)(struct kref *kref)static inline int kref_put_mutex (struct kref *kref,void (*release)(struct kref *kref),struct mutex *mutex) +__cond_acquires (true, mutex) {if (refcount_dec_and_mutex_lock (&kref->refcount, mutex)) {release (kref);
@@ -102,6 +103,7 @@ static inline int kref_put_mutex(struct kref *kref,static inline int kref_put_lock (struct kref *kref,void (*release)(struct kref *kref),spinlock_t *lock) +__cond_acquires (true, lock) {if (refcount_dec_and_lock (&kref->refcount, lock)) {release (kref);
Marco Elver
maintainerPATCH v5 17/36 locking/rwsem: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for rw_semaphore.
---
v5:
* Rename "context guard" -> "context lock".
* Use new cleanup.h helpers to properly support scoped lock guards.
v4:
* Rename capability -> context analysis.
v3:
* Switch to DECLARE_LOCK_GUARD_1_ATTRS() (suggested by Peter)
* __assert -> __assume rename
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/rwsem.h | 76 +++++++++++++------- lib/test_context-analysis.c | 64 +++++++++++++++++ 3 files changed, 114 insertions(+), 28 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU, SRCU (`srcu_struct`). +`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/rwsem.h +49 -27
176 lines not on this page · raw message
lib/test_context-analysis.c +64 -0
76 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 17/36] locking/rwsem: Support Clang's context analysis
Quoted 12 lines · Marco Elver
static inline void
rwsem_assert_held_nolockdep(const struct rw_semaphore *sem)include/linux/rwsem.h +2
-0+__assumes_ctx_lock (sem) {WARN_ON (atomic_long_read (&sem->count) ==RWSEM_UNLOCKED_VALUE ); }static inline void rwsem_assert_held_write_nolockdep (const struct rw_semaphore *sem) +__assumes_ctx_lock (sem) {WARN_ON (!(atomic_long_read (&sem->count) &RWSEM_WRITER_LOCKED )); }
include/linux/rwsem.h do { \ · line 125
Quoted 5 lines
include/linux/rwsem.h +1
-0@@ -119,6 +121,7 @@ do { \static struct lock_class_key __key; \ \ __init_rwsem((sem), #sem, &__key); \ +__assume_ctx_lock (sem); \ }while (0 )
Just like as for lockdep.h, I think that the above annotations should be changed into __must_hold().
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 17/36] locking/rwsem: Support Clang's context analysis
Quoted 8 lines · Bart Van Assche' via kasan-dev
Quoted 6 lines · Marco Elver
static inline void
rwsem_assert_held_nolockdep(const struct rw_semaphore *sem)
+__assumes_ctx_lock(sem){ WARN_ON(atomic_long_read(&sem->count) == RWSEM_UNLOCKED_VALUE);}
Quoted 14 lines
include/linux/rwsem.h do { \ · line 125
Quoted 11 lines
static inline void
rwsem_assert_held_write_nolockdep(const struct rw_semaphore *sem)include/linux/rwsem.h +2
-0+__assumes_ctx_lock (sem) {WARN_ON (!(atomic_long_read (&sem->count) &RWSEM_WRITER_LOCKED )); }@@ -119,6 +121,7 @@ do { \static struct lock_class_key __key; \ \ __init_rwsem((sem), #sem, &__key); \ +__assume_ctx_lock (sem); \ }while (0 )Just like as for
lockdep.h, I think that the above annotations should be changed into__must_hold().
My point is the same: we use it to delegate to dynamic analysis where we reach the limits of static analysis, to avoid false positives [1]. Code should apply __must_hold() or __guarded_by() to called or protected variables respectively, which is both cleaner and the idiomatic way to use all this.
[1] https://lore.kernel.org/all/CANpmjNPp6Gkz3rdaD0V7EkPrm60sA5tPpw+m8Xg3u8MTXuc2mg@mail.gmail.com/
[tip: locking/core] locking/rwsem: Support Clang's context analysis
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: e4fd3be884cf33a42c5bcde087b0722a5b8f25ca Gitweb: https://git.kernel.org/tip/e4fd3be884cf33a42c5bcde087b0722a5b8f25ca Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:06 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:31 +01:00
locking/rwsem: Support Clang's context analysis
Add support for Clang's context analysis for rw_semaphore.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/rwsem.h | 76 ++++++++++++------- lib/test_context-analysis.c | 64 ++++++++++++++++- 3 files changed, 114 insertions(+), 28 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU, SRCU (`srcu_struct`). +`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/rwsem.h +49 -27
176 lines not on this page · raw message
lib/test_context-analysis.c +64 -0
76 lines not on this page · raw message
Marco Elver
maintainerPATCH v5 18/36 locking/local_lock: Include missing headers
In reply to Marco ElverIncluding <linux/local_lock.h> into an empty TU will result in the compiler complaining:
./include/linux/local_lock.h: In function ‘class_local_lock_irqsave_constructor’:./include/linux/local_lock_internal.h:95:17: error: implicit declaration of function ‘local_irq_save’; <...>
95 | local_irq_save(flags); \
| ^~~~~~~~~~~~~~As well as (some architectures only, such as 'sh'):
./include/linux/local_lock_internal.h: In function ‘local_lock_acquire’:./include/linux/local_lock_internal.h:33:20: error: ‘current’ undeclared (first use in this function)
33 | l->owner = current;
Include missing headers to allow including local_lock.h where the required headers are not otherwise included.
--- include/linux/local_lock_internal.h | 2 ++ 1 file changed, 2 insertions(+)
include/linux/local_lock_internal.h +2 -0
@@ -4,7 +4,9 @@#endif #include <linux/percpu-defs.h> +#include <linux/irqflags.h> #include <linux/lockdep.h> +#include <asm/current.h> #ifndef CONFIG_PREEMPT_RT
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Re: [PATCH v5 18/36] locking/local_lock: Include missing headers
Quoted 27 lines · Marco Elver
Including <
linux/local_lock.h> into an empty TU will result in the compiler complaining:
./include/linux/local_lock.h: In function ‘class_local_lock_irqsave_constructor’:./include/linux/local_lock_internal.h:95:17: error: implicit declaration of function ‘local_irq_save’; <...>95 | local_irq_save(flags); \ | ^~~~~~~~~~~~~~As well as (some architectures only, such as 'sh'):
./include/linux/local_lock_internal.h: In function ‘local_lock_acquire’:./include/linux/local_lock_internal.h:33:20: error: ‘current’ undeclared (first use in this function)33 | l->owner = current;Include missing headers to allow including
local_lock.hwhere the required headers are not otherwise included.Signed-off-by Marco Elver <[email protected]>--- include/linux/local_lock_internal.h | 2 ++ 1 file changed, 2 insertions(+)include/linux/local_lock_internal.h +0
-0
include/linux/local_lock_internal.h line 12
Quoted 9 lines
include/linux/local_lock_internal.h +2
-0@@ -4,7 +4,9 @@#endif #include <linux/percpu-defs.h> +#include <linux/irqflags.h> #include <linux/lockdep.h> +#include <asm/current.h> #ifndef CONFIG_PREEMPT_RT
The abbreviation "TU" is uncommon. Hence, please expand that abbreviation. Anyway:
[tip: locking/core] locking/local_lock: Include missing headers
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 8c9c8566e139c0f1398245fbe3aa409fc1a79da8 Gitweb: https://git.kernel.org/tip/8c9c8566e139c0f1398245fbe3aa409fc1a79da8 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:07 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:31 +01:00
locking/local_lock: Include missing headers
Including <linux/local_lock.h> into an empty TU will result in the compiler complaining:
./include/linux/local_lock.h: In function ‘class_local_lock_irqsave_constructor’:./include/linux/local_lock_internal.h:95:17: error: implicit declaration of function ‘local_irq_save’; <...>
95 | local_irq_save(flags); \
| ^~~~~~~~~~~~~~As well as (some architectures only, such as 'sh'):
./include/linux/local_lock_internal.h: In function ‘local_lock_acquire’:./include/linux/local_lock_internal.h:33:20: error: ‘current’ undeclared (first use in this function)
33 | l->owner = current;
Include missing headers to allow including local_lock.h where the required headers are not otherwise included.
--- include/linux/local_lock_internal.h | 2 ++ 1 file changed, 2 insertions(+)
include/linux/local_lock_internal.h +2 -0
@@ -4,7 +4,9 @@#endif #include <linux/percpu-defs.h> +#include <linux/irqflags.h> #include <linux/lockdep.h> +#include <asm/current.h> #ifndef CONFIG_PREEMPT_RT
Marco Elver
maintainerPATCH v5 19/36 locking/local_lock: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for local_lock_t and local_trylock_t.
---
v5:
* Rename "context guard" -> "context lock".
* Use new cleanup.h helpers to properly support scoped lock guards.
v4:
* Rename capability -> context analysis.
v3:
* Switch to DECLARE_LOCK_GUARD_1_ATTRS() (suggested by Peter)
* __assert -> __assume rename
* Rework __this_cpu_local_lock helper
* Support local_trylock_t
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/local_lock.h | 51 ++++++++------ include/linux/local_lock_internal.h | 71 +++++++++++++++---- lib/test_context-analysis.c | 73 ++++++++++++++++++++ 4 files changed, 161 insertions(+), 36 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`. +`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/local_lock.h +30 -21
103 lines not on this page · raw message
include/linux/local_lock_internal.h +57 -14
187 lines not on this page · raw message
lib/test_context-analysis.c +73 -0
83 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] locking/local_lock: Support Clang's context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: d3febf16dee28a74b01ba43195ee4965edb6208f Gitweb: https://git.kernel.org/tip/d3febf16dee28a74b01ba43195ee4965edb6208f Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:08 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:31 +01:00
locking/local_lock: Support Clang's context analysis
Add support for Clang's context analysis for local_lock_t and local_trylock_t.
--- Documentation/dev-tools/context-analysis.rst | 2 +- include/linux/local_lock.h | 51 +++++++------ include/linux/local_lock_internal.h | 71 ++++++++++++++---- lib/test_context-analysis.c | 73 +++++++++++++++++++- 4 files changed, 161 insertions(+), 36 deletions(-)
Documentation/dev-tools/context-analysis.rst +1 -1
@@ -80,7 +80,7 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`. +`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/local_lock.h +30 -21
103 lines not on this page · raw message
include/linux/local_lock_internal.h +57 -14
187 lines not on this page · raw message
lib/test_context-analysis.c +73 -0
83 lines not on this page · raw message
Marco Elver
maintainerPATCH v5 20/36 locking/ww_mutex: Support Clang's context analysis
In reply to Marco ElverAdd support for Clang's context analysis for ww_mutex.
The programming model for ww_mutex is subtly more complex than other locking primitives when using ww_acquire_ctx. Encoding the respective pre-conditions for ww_mutex lock/unlock based on ww_acquire_ctx state using Clang's context analysis makes incorrect use of the API harder.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
v3:
* __assert -> __assume rename
v2:
* New patch.
--- Documentation/dev-tools/context-analysis.rst | 3 +- include/linux/ww_mutex.h | 22 +++++-- lib/test_context-analysis.c | 69 ++++++++++++++++++++ 3 files changed, 87 insertions(+), 7 deletions(-)
Documentation/dev-tools/context-analysis.rst +2 -1
@@ -80,7 +80,8 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`. +`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`, +`ww_mutex`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/ww_mutex.h +16 -6
@@ -44,7 +44,7 @@ struct ww_class {unsigned int is_wait_die; }; -struct ww_mutex { +context_lock_struct (ww_mutex) {struct WW_MUTEX_BASE base;struct ww_acquire_ctx *ctx;#ifdef DEBUG_WW_MUTEXES
@@ -52,7 +52,7 @@ struct ww_mutex {#endif }; -struct ww_acquire_ctx { +context_lock_struct (ww_acquire_ctx) {struct task_struct *task;unsigned long stamp;unsigned int acquired;
@@ -107,6 +107,7 @@ struct ww_acquire_ctx {*/ static inline void ww_mutex_init (struct ww_mutex *lock,struct ww_class *ww_class) +__assumes_ctx_lock (lock) {ww_mutex_base_init (&lock->base, ww_class->mutex_name, &ww_class->mutex_key); lock->ctx =NULL ;
@@ -141,6 +142,7 @@ static inline void ww_mutex_init(struct ww_mutex *lock,*/ static inline void ww_acquire_init (struct ww_acquire_ctx *ctx,struct ww_class *ww_class) +__acquires (ctx) __no_context_analysis { ctx->task = current; ctx->stamp =atomic_long_inc_return_relaxed (&ww_class->stamp);
@@ -179,6 +181,7 @@ static inline void ww_acquire_init(struct ww_acquire_ctx *ctx,* data structures. */ static inline void ww_acquire_done (struct ww_acquire_ctx *ctx) +__releases (ctx)__acquires_shared (ctx) __no_context_analysis {#ifdef DEBUG_WW_MUTEXES lockdep_assert_held (ctx);
@@ -196,6 +199,7 @@ static inline void ww_acquire_done(struct ww_acquire_ctx *ctx)* mutexes have been released with ww_mutex_unlock. */ static inline void ww_acquire_fini (struct ww_acquire_ctx *ctx) +__releases_shared (ctx) __no_context_analysis {#ifdef CONFIG_DEBUG_LOCK_ALLOC mutex_release (&ctx->first_lock_dep_map, _THIS_IP_);
@@ -245,7 +249,8 @@ static inline void ww_acquire_fini(struct ww_acquire_ctx *ctx)* * A mutex acquired with this function must be released with ww_mutex_unlock. */ -extern int /* __must_check */ ww_mutex_lock (struct ww_mutex *lock,struct ww_acquire_ctx *ctx); +extern int /* __must_check */ ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) + __cond_acquires(0, lock) __must_hold(ctx);/** * ww_mutex_lock_interruptible - acquire the w/w mutex, interruptible
@@ -278,7 +283,8 @@ extern int /* __must_check */ ww_mutex_lock(struct ww_mutex *lock, struct ww_acq* A mutex acquired with this function must be released with ww_mutex_unlock. */ extern int __must_check ww_mutex_lock_interruptible(struct ww_mutex *lock, -struct ww_acquire_ctx *ctx); + struct ww_acquire_ctx *ctx) + __cond_acquires(0, lock) __must_hold(ctx);/** * ww_mutex_lock_slow - slowpath acquiring of the w/w mutex
@@ -305,6 +311,7 @@ extern int __must_check ww_mutex_lock_interruptible(struct ww_mutex *lock,*/ static inline void ww_mutex_lock_slow (struct ww_mutex *lock,struct ww_acquire_ctx *ctx) +__acquires (lock)__must_hold (ctx) __no_context_analysis {int ret;#ifdef DEBUG_WW_MUTEXES
@@ -342,6 +349,7 @@ ww_mutex_lock_slow(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)static inline int __must_check ww_mutex_lock_slow_interruptible (struct ww_mutex *lock,struct ww_acquire_ctx *ctx) +__cond_acquires (0 , lock)__must_hold (ctx) {#ifdef DEBUG_WW_MUTEXES DEBUG_LOCKS_WARN_ON (!ctx->contending_lock);
@@ -349,10 +357,11 @@ ww_mutex_lock_slow_interruptible(struct ww_mutex *lock,return ww_mutex_lock_interruptible (lock, ctx); } -extern void ww_mutex_unlock (struct ww_mutex *lock); +extern void ww_mutex_unlock(struct ww_mutex *lock) __releases(lock); extern int __must_check ww_mutex_trylock(struct ww_mutex *lock, -struct ww_acquire_ctx *ctx); + struct ww_acquire_ctx *ctx) + __cond_acquires(true, lock) __must_hold(ctx);/*** * ww_mutex_destroy - mark a w/w mutex unusable
@@ -363,6 +372,7 @@ extern int __must_check ww_mutex_trylock(struct ww_mutex *lock,* this function is called. */ static inline void ww_mutex_destroy (struct ww_mutex *lock) +__must_not_hold (lock) {#ifndef CONFIG_PREEMPT_RT mutex_destroy (&lock->base);
lib/test_context-analysis.c +69 -0
78 lines not on this page · raw message
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] locking/ww_mutex: Support Clang's context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 47907461e4f6fcdce8cf91dd164369192deeb7c4 Gitweb: https://git.kernel.org/tip/47907461e4f6fcdce8cf91dd164369192deeb7c4 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:09 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:32 +01:00
locking/ww_mutex: Support Clang's context analysis
Add support for Clang's context analysis for ww_mutex.
The programming model for ww_mutex is subtly more complex than other locking primitives when using ww_acquire_ctx. Encoding the respective pre-conditions for ww_mutex lock/unlock based on ww_acquire_ctx state using Clang's context analysis makes incorrect use of the API harder.
--- Documentation/dev-tools/context-analysis.rst | 3 +- include/linux/ww_mutex.h | 22 ++++-- lib/test_context-analysis.c | 69 +++++++++++++++++++- 3 files changed, 87 insertions(+), 7 deletions(-)
Documentation/dev-tools/context-analysis.rst +2 -1
@@ -80,7 +80,8 @@ Supported Kernel Primitives Currently the following synchronization primitives are supported: `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`, -`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`. +`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`, +`ww_mutex`. For context locks with an initialization function (e.g., `spin_lock_init()`), calling this function before initializing any guarded members or globals
include/linux/ww_mutex.h +16 -6
@@ -44,7 +44,7 @@ struct ww_class {unsigned int is_wait_die; }; -struct ww_mutex { +context_lock_struct (ww_mutex) {struct WW_MUTEX_BASE base;struct ww_acquire_ctx *ctx;#ifdef DEBUG_WW_MUTEXES
@@ -52,7 +52,7 @@ struct ww_mutex {#endif }; -struct ww_acquire_ctx { +context_lock_struct (ww_acquire_ctx) {struct task_struct *task;unsigned long stamp;unsigned int acquired;
@@ -107,6 +107,7 @@ struct ww_acquire_ctx {*/ static inline void ww_mutex_init (struct ww_mutex *lock,struct ww_class *ww_class) +__assumes_ctx_lock (lock) {ww_mutex_base_init (&lock->base, ww_class->mutex_name, &ww_class->mutex_key); lock->ctx =NULL ;
@@ -141,6 +142,7 @@ static inline void ww_mutex_init(struct ww_mutex *lock,*/ static inline void ww_acquire_init (struct ww_acquire_ctx *ctx,struct ww_class *ww_class) +__acquires (ctx) __no_context_analysis { ctx->task = current; ctx->stamp =atomic_long_inc_return_relaxed (&ww_class->stamp);
@@ -179,6 +181,7 @@ static inline void ww_acquire_init(struct ww_acquire_ctx *ctx,* data structures. */ static inline void ww_acquire_done (struct ww_acquire_ctx *ctx) +__releases (ctx)__acquires_shared (ctx) __no_context_analysis {#ifdef DEBUG_WW_MUTEXES lockdep_assert_held (ctx);
@@ -196,6 +199,7 @@ static inline void ww_acquire_done(struct ww_acquire_ctx *ctx)* mutexes have been released with ww_mutex_unlock. */ static inline void ww_acquire_fini (struct ww_acquire_ctx *ctx) +__releases_shared (ctx) __no_context_analysis {#ifdef CONFIG_DEBUG_LOCK_ALLOC mutex_release (&ctx->first_lock_dep_map, _THIS_IP_);
@@ -245,7 +249,8 @@ static inline void ww_acquire_fini(struct ww_acquire_ctx *ctx)* * A mutex acquired with this function must be released with ww_mutex_unlock. */ -extern int /* __must_check */ ww_mutex_lock (struct ww_mutex *lock,struct ww_acquire_ctx *ctx); +extern int /* __must_check */ ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) + __cond_acquires(0, lock) __must_hold(ctx);/** * ww_mutex_lock_interruptible - acquire the w/w mutex, interruptible
@@ -278,7 +283,8 @@ extern int /* __must_check */ ww_mutex_lock(struct ww_mutex *lock, struct ww_acq* A mutex acquired with this function must be released with ww_mutex_unlock. */ extern int __must_check ww_mutex_lock_interruptible(struct ww_mutex *lock, -struct ww_acquire_ctx *ctx); + struct ww_acquire_ctx *ctx) + __cond_acquires(0, lock) __must_hold(ctx);/** * ww_mutex_lock_slow - slowpath acquiring of the w/w mutex
@@ -305,6 +311,7 @@ extern int __must_check ww_mutex_lock_interruptible(struct ww_mutex *lock,*/ static inline void ww_mutex_lock_slow (struct ww_mutex *lock,struct ww_acquire_ctx *ctx) +__acquires (lock)__must_hold (ctx) __no_context_analysis {int ret;#ifdef DEBUG_WW_MUTEXES
@@ -342,6 +349,7 @@ ww_mutex_lock_slow(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)static inline int __must_check ww_mutex_lock_slow_interruptible (struct ww_mutex *lock,struct ww_acquire_ctx *ctx) +__cond_acquires (0 , lock)__must_hold (ctx) {#ifdef DEBUG_WW_MUTEXES DEBUG_LOCKS_WARN_ON (!ctx->contending_lock);
@@ -349,10 +357,11 @@ ww_mutex_lock_slow_interruptible(struct ww_mutex *lock,return ww_mutex_lock_interruptible (lock, ctx); } -extern void ww_mutex_unlock (struct ww_mutex *lock); +extern void ww_mutex_unlock(struct ww_mutex *lock) __releases(lock); extern int __must_check ww_mutex_trylock(struct ww_mutex *lock, -struct ww_acquire_ctx *ctx); + struct ww_acquire_ctx *ctx) + __cond_acquires(true, lock) __must_hold(ctx);/*** * ww_mutex_destroy - mark a w/w mutex unusable
@@ -363,6 +372,7 @@ extern int __must_check ww_mutex_trylock(struct ww_mutex *lock,* this function is called. */ static inline void ww_mutex_destroy (struct ww_mutex *lock) +__must_not_hold (lock) {#ifndef CONFIG_PREEMPT_RT mutex_destroy (&lock->base);
lib/test_context-analysis.c +69 -0
78 lines not on this page · raw message
Bart Van Assche
reviewerRe: [PATCH v5 20/36] locking/ww_mutex: Support Clang's context analysis
In reply to Marco ElverQuoted 6 lines · Marco Elver
Add support for Clang's context analysis for
ww_mutex.The programming model for
ww_mutexis subtly more complex than other locking primitives when usingww_acquire_ctx. Encoding the respective pre-conditions forww_mutexlock/unlock based onww_acquire_ctxstate using Clang's context analysis makes incorrect use of the API harder.
That's a very short description. It should have been explained in the patch description how the ww_acquire_ctx changes affect callers of the ww_acquire_{init,done,fini}() functions.
include/linux/ww_mutex.h static inline void ww_acquire_init(struct ww_acquire_ctx *ctx,
Quoted 10 lines
static inline void ww_acquire_init(struct
ww_acquire_ctx*ctx,
structww_class*ww_class)include/linux/ww_mutex.h +3
-0+ __acquires(ctx) __no_context_analysisstatic inline void ww_acquire_done (struct ww_acquire_ctx *ctx) +__releases (ctx)__acquires_shared (ctx) __no_context_analysis { static inline void ww_acquire_fini(struct ww_acquire_ctx *ctx) + __releases_shared(ctx) __no_context_analysis
The above changes make it mandatory to call ww_acquire_done() before calling ww_acquire_fini(). In Documentation/locking/ww-mutex-design.rst there is an example where there is no ww_acquire_done() call between ww_acquire_init() and ww_acquire_fini() (see also line 202). The function dma_resv_lockdep() in drivers/dma-buf/dma-resv.c doesn't call ww_acquire_done() at all. Does this mean that the above annotations are wrong? Is there a better solution than removing the __acquire() and __release() annotations from the above three functions?
Bart.
Marco Elver
maintainerRe: [PATCH v5 20/36] locking/ww_mutex: Support Clang's context analysis
Quoted 11 lines · Bart Van Assche
Quoted 6 lines · Marco Elver
Add support for Clang's context analysis for
ww_mutex.The programming model for
ww_mutexis subtly more complex than other locking primitives when usingww_acquire_ctx. Encoding the respective pre-conditions forww_mutexlock/unlock based onww_acquire_ctxstate using Clang's context analysis makes incorrect use of the API harder.That's a very short description. It should have been explained in the patch description how the
ww_acquire_ctxchanges affect callers of the ww_acquire_{init,done,fini}() functions.
How so? The API is the same (now statically enforced), and there's no functional change at runtime. Or did I miss something?
Quoted 7 lines
Quoted 7 lines
static inline void ww_acquire_init(struct
ww_acquire_ctx*ctx,
structww_class*ww_class)include/linux/ww_mutex.h +2
-0+ __acquires(ctx) __no_context_analysisstatic inline void ww_acquire_done (struct ww_acquire_ctx *ctx) +__releases (ctx)__acquires_shared (ctx) __no_context_analysis {
Quoted 8 lines
include/linux/ww_mutex.h static inline void ww_acquire_done(struct ww_acquire_ctx *ctx) · line 202
Quoted 3 lines
[ ... ]
static inline voidww_acquire_fini(struct ww_acquire_ctx *ctx)include/linux/ww_mutex.h +1
-0+__releases_shared (ctx) __no_context_analysisThe above changes make it mandatory to call
ww_acquire_done()before callingww_acquire_fini(). InDocumentation/locking/ww-mutex-design.rstthere is an example where there is noww_acquire_done()call betweenww_acquire_init()andww_acquire_fini()(see also line 202).
It might be worth updating the example with what the kernel-doc documentation recommends (below).
Quoted 4 lines
The
functiondma_resv_lockdep()indrivers/dma-buf/dma-resv.cdoesn't callww_acquire_done()at all. Does this mean that the above annotations are wrong?
If there's 1 out of N ww_mutex users that missed ww_acquire_done() there's a good chance that 1 case is wrong.
But generally, depends if we want to enforce ww_acquire_done() or not which itself is no-op in non-lockdep builds, however, with DEBUG_WW_MUTEXES it's no longer no-op so it might be a good idea to enforce it to get proper lockdep checking.
Quoted 2 lines
Is there a better solution than removing the
__acquire()and__release()annotations from the above three functions?
The kernel-doc comment for ww_acquire_done() says:
/** * ww_acquire_done - marks the end of the acquire phase * @ctx: the acquire context *
Quoted 6 lines
Quoted 6 lines
* Marks the end of the acquire phase, any further w/w mutex lock calls using
* this context are forbidden.
*
* Calling this function is optional, it is just useful to document w/w mutex
* code and clearly designated the acquire phase from actually using the locked
* data structures.
*/
static inline void ww_acquire_done(struct ww_acquire_ctx *ctx)
__releases(ctx) __acquires_shared(ctx) __no_context_analysis
{
#ifdef DEBUG_WW_MUTEXES
lockdep_assert_held(ctx);
DEBUG_LOCKS_WARN_ON(ctx->done_acquire);
ctx->done_acquire = 1;
#endif
}It states it's optional, but it's unclear if that's true with DEBUG_WW_MUTEXES builds. I'd vote for enforcing use of ww_acquire_done(). If there's old code that's not using it, it should be added there to get proper lockdep checking.
Bart Van Assche
reviewerRe: [PATCH v5 20/36] locking/ww_mutex: Support Clang's context analysis
(+Maarten)
Quoted 2 lines · Marco Elver
If there's 1 out of N
ww_mutexusers that missedww_acquire_done()there's a good chance that 1 case is wrong.
$ git grep -w ww_acquire_done '**c'|wc -l 11 $ git grep -w ww_acquire_fini '**c'|wc -l 33
The above statistics show that there are more cases where ww_acquire_done() is not called rather than cases where ww_acquire_done() is called.
Maarten, since you introduced the ww_mutex code, do you perhaps prefer that calling ww_acquire_done() is optional or rather that all users that do not call ww_acquire_done() are modified such that they call ww_acquire_done()? The full email conversation is available here:
https://lore.kernel.org/all/[email protected]/
Thanks,
Bart.
Re: [PATCH v5 20/36] locking/ww_mutex: Support Clang's context analysis
Hey,
The acquire_done() call was always optional. It's meant to indicate that after this point, ww_acquire_lock may no longer be called and backoff can no longer occur.
It's allowed to call ww_acquire_fini() without ww_acquire_done()
Think of this case:ww_acquire_init()
ww_acquire_lock_interruptible() -> -ERESTARTSYS
ww_acquire_fini()
Here it wouldn't make sense to call ww_acquire_done().
It's mostly to facilitate this case:
ww_acquire_init()
ww_acquire_lock() a bunch.
/* Got all locks, do the work as no more backoff occurs */ ww_acquire_done()
...
unlock_all()ww_acquire_fini()
If you call ww_acquire_lock after done, a warning should occur as this should no longer happen.
Kind regards,
~Maarten Lankhorst
Den 2026-01-09 kl. 22:26, skrev Bart Van Assche:
Quoted 24 lines
(+Maarten)
Quoted 2 lines · Marco Elver
If there's 1 out of N
ww_mutexusers that missedww_acquire_done()there's a good chance that 1 case is wrong.$ git grep -w ww_acquire_done '**c'|wc -l 11 $ git grep -w ww_acquire_fini '**c'|wc -l 33The above statistics show that there are more cases where
ww_acquire_done()is not called rather than cases whereww_acquire_done()is called.Maarten, since you introduced the
ww_mutexcode, do you perhaps prefer that callingww_acquire_done()is optional or rather that all users that do not callww_acquire_done()are modified such that they callww_acquire_done()? The full email conversation is available here:
https://lore.kernel.org/all/[email protected]/Thanks,
Bart.
Marco Elver
maintainerPATCH v5 21/36 debugfs: Make debugfs_cancellation a context lock struct
In reply to Marco ElverWhen compiling include/linux/debugfs.h with CONTEXT_ANALYSIS enabled, we can see this error:
./include/linux/debugfs.h:239:17: error: use of undeclared identifier 'cancellation'
239 | void __acquires(cancellation)
Move the __acquires(..) attribute after the declaration, so that the compiler can see the cancellation function argument, as well as making struct debugfs_cancellation a real context lock to benefit from Clang's context analysis.
This change is a preparatory change to allow enabling context analysis in subsystems that include the above header.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
--- include/linux/debugfs.h | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-)
include/linux/debugfs.h +5 -7
@@ -239,18 +239,16 @@ ssize_t debugfs_read_file_str(struct file *file, char __user *user_buf,* @cancel: callback to call * @cancel_data: extra data for the callback to call */ -struct debugfs_cancellation { +context_lock_struct (debugfs_cancellation) {struct list_head list;void (*cancel)(struct dentry *,void *);void *cancel_data; }; -void __acquires(cancellation) -debugfs_enter_cancellation(struct file *file, - struct debugfs_cancellation *cancellation); -void __releases(cancellation) -debugfs_leave_cancellation(struct file *file, - struct debugfs_cancellation *cancellation); +void debugfs_enter_cancellation(struct file *file, + struct debugfs_cancellation *cancellation) __acquires(cancellation); +void debugfs_leave_cancellation(struct file *file, + struct debugfs_cancellation *cancellation) __releases(cancellation);#else
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Re: [PATCH v5 21/36] debugfs: Make debugfs_cancellation a context lock struct
Quoted 6 lines · Marco Elver
When compiling
include/linux/debugfs.hwithCONTEXT_ANALYSISenabled, we can see this error:
./include/linux/debugfs.h:239:17: error: use of undeclared identifier 'cancellation'
239 | void__acquires(cancellation)
Quoted 7 lines
Move the
__acquires(..)attribute after the declaration, so that the compiler can see the cancellation function argument, as well as making structdebugfs_cancellationa real context lock to benefit from Clang's context analysis.This change is a preparatory change to allow enabling context analysis in subsystems that include the above header.
[tip: locking/core] debugfs: Make debugfs_cancellation a context lock struct
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 6e530e2e31191d88f692e6c8d3bd245e43416e4f Gitweb: https://git.kernel.org/tip/6e530e2e31191d88f692e6c8d3bd245e43416e4f Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:10 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:32 +01:00
debugfs: Make debugfs_cancellation a context lock struct
When compiling include/linux/debugfs.h with CONTEXT_ANALYSIS enabled, we can see this error:
./include/linux/debugfs.h:239:17: error: use of undeclared identifier 'cancellation'
239 | void __acquires(cancellation)
Move the __acquires(..) attribute after the declaration, so that the compiler can see the cancellation function argument, as well as making struct debugfs_cancellation a real context lock to benefit from Clang's context analysis.
This change is a preparatory change to allow enabling context analysis in subsystems that include the above header.
--- include/linux/debugfs.h | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-)
include/linux/debugfs.h +5 -7
@@ -239,18 +239,16 @@ ssize_t debugfs_read_file_str(struct file *file, char __user *user_buf,* @cancel: callback to call * @cancel_data: extra data for the callback to call */ -struct debugfs_cancellation { +context_lock_struct (debugfs_cancellation) {struct list_head list;void (*cancel)(struct dentry *,void *);void *cancel_data; }; -void __acquires(cancellation) -debugfs_enter_cancellation(struct file *file, - struct debugfs_cancellation *cancellation); -void __releases(cancellation) -debugfs_leave_cancellation(struct file *file, - struct debugfs_cancellation *cancellation); +void debugfs_enter_cancellation(struct file *file, + struct debugfs_cancellation *cancellation) __acquires(cancellation); +void debugfs_leave_cancellation(struct file *file, + struct debugfs_cancellation *cancellation) __releases(cancellation);#else
Marco Elver
maintainerPATCH v5 22/36 um: Fix incorrect __acquires/__releases annotations
In reply to Marco ElverWith Clang's context analysis, the compiler is a bit more strict about what goes into the __acquires/__releases annotations and can't refer to non-existent variables.
On an UM build, mm_id.h is transitively included into mm_types.h, and we can observe the following error (if context analysis is enabled in e.g. stackdepot.c):
In file included from lib/stackdepot.c:17:
In file included from include/linux/debugfs.h:15:
In file included from include/linux/fs.h:5:
In file included from include/linux/fs/super.h:5:
In file included from include/linux/fs/super_types.h:7:
In file included from include/linux/list_lru.h:14:
In file included from include/linux/xarray.h:16:
In file included from include/linux/gfp.h:7:
In file included from include/linux/mmzone.h:22:
In file included from include/linux/mm_types.h:26:
In file included from arch/um/include/asm/mmu.h:12:
Quoted 1 line
Quoted 1 line
arch/um/include/shared/skas/mm_id.h:24:54: error: use of undeclared identifier 'turnstile'
24 | void enter_turnstile(struct mm_id *mm_id) __acquires(turnstile);
| ^~~~~~~~~
arch/um/include/shared/skas/mm_id.h:25:53: error: use of undeclared identifier 'turnstile'
25 | void exit_turnstile(struct mm_id *mm_id) __releases(turnstile);
| ^~~~~~~~~One (discarded) option was to use token_context_lock(turnstile) to just define a token with the already used name, but that would not allow the compiler to distinguish between different mm_id-dependent instances.
Another constraint is that struct mm_id is only declared and incomplete in the header, so even if we tried to construct an expression to get to the mutex instance, this would fail (including more headers transitively everywhere should also be avoided).
Instead, just declare an mm_id-dependent helper to return the mutex, and use the mm_id-dependent call expression in the __acquires/__releases attributes; the compiler will consider the identity of the mutex to be the call expression. Then using __get_turnstile() in the lock/unlock wrappers (with context analysis enabled for mmu.c) the compiler will be able to verify the implementation of the wrappers as-is.
We leave context analysis disabled in arch/um/kernel/skas/ for now. This change is a preparatory change to allow enabling context analysis in subsystems that include any of the above headers.
No functional change intended.
--- arch/um/include/shared/skas/mm_id.h | 5 +++-- arch/um/kernel/skas/mmu.c | 13 ++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-)
arch/um/include/shared/skas/mm_id.h +3 -2
@@ -21,8 +21,9 @@ struct mm_id {int syscall_fd_map[STUB_MAX_FDS ]; }; -void enter_turnstile(struct mm_id *mm_id) __acquires(turnstile); -void exit_turnstile(struct mm_id *mm_id) __releases(turnstile); +struct mutex *__get_turnstile (struct mm_id *mm_id); +void enter_turnstile(struct mm_id *mm_id) __acquires(__get_turnstile(mm_id)); +void exit_turnstile(struct mm_id *mm_id) __releases(__get_turnstile(mm_id));void notify_mm_kill (int pid);
arch/um/kernel/skas/mmu.c +8 -5
@@ -23,18 +23,21 @@ static_assert(sizeof(struct stub_data) == STUB_DATA_PAGES * UM_KERN_PAGE_SIZE);static spinlock_t mm_list_lock;static struct list_head mm_list; -void enter_turnstile (struct mm_id *mm_id)__acquires (turnstile) +struct mutex *__get_turnstile (struct mm_id *mm_id) { struct mm_context *ctx = container_of(mm_id, struct mm_context, id); -mutex_lock (&ctx->turnstile); +return &ctx->turnstile; } -void exit_turnstile (struct mm_id *mm_id)__releases (turnstile) +void enter_turnstile (struct mm_id *mm_id) { - struct mm_context *ctx = container_of(mm_id, struct mm_context, id); +mutex_lock (__get_turnstile (mm_id)); +} -mutex_unlock (&ctx->turnstile); +void exit_turnstile (struct mm_id *mm_id) +{ +mutex_unlock (__get_turnstile (mm_id)); }int init_new_context (struct task_struct *task,struct mm_struct *mm)
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Bart Van Assche
reviewerRe: [PATCH v5 22/36] um: Fix incorrect __acquires/__releases annotations
arch/um/kernel/skas/mmu.c static_assert(sizeof(struct stub_data) == STUB_DATA_PAGES * UM_KERN_PAGE_SIZE); · line 31
Quoted 8 lines · Marco Elver
arch/um/kernel/skas/mmu.c +2
-2-void enter_turnstile (struct mm_id *mm_id)__acquires (turnstile) +struct mutex *__get_turnstile (struct mm_id *mm_id) { struct mm_context *ctx = container_of(mm_id, struct mm_context, id); -mutex_lock (&ctx->turnstile); +return &ctx->turnstile; }
Many "container_of()" wrappers have "to" in their name. Please follow that convention and rename this function into e.g. mm_id_to_turnstile().
Thanks,
Bart.
[tip: locking/core] um: Fix incorrect __acquires/__releases annotations
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 4f109baeea4dc6fa1426ab559159d3bb35e05343 Gitweb: https://git.kernel.org/tip/4f109baeea4dc6fa1426ab559159d3bb35e05343 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:11 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:32 +01:00
um: Fix incorrect __acquires/__releases annotations
With Clang's context analysis, the compiler is a bit more strict about what goes into the __acquires/__releases annotations and can't refer to non-existent variables.
On an UM build, mm_id.h is transitively included into mm_types.h, and we can observe the following error (if context analysis is enabled in e.g. stackdepot.c):
In file included from lib/stackdepot.c:17:
In file included from include/linux/debugfs.h:15:
In file included from include/linux/fs.h:5:
In file included from include/linux/fs/super.h:5:
In file included from include/linux/fs/super_types.h:7:
In file included from include/linux/list_lru.h:14:
In file included from include/linux/xarray.h:16:
In file included from include/linux/gfp.h:7:
In file included from include/linux/mmzone.h:22:
In file included from include/linux/mm_types.h:26:
In file included from arch/um/include/asm/mmu.h:12:
Quoted 1 line
Quoted 1 line
arch/um/include/shared/skas/mm_id.h:24:54: error: use of undeclared identifier 'turnstile'
24 | void enter_turnstile(struct mm_id *mm_id) __acquires(turnstile);
| ^~~~~~~~~
arch/um/include/shared/skas/mm_id.h:25:53: error: use of undeclared identifier 'turnstile'
25 | void exit_turnstile(struct mm_id *mm_id) __releases(turnstile);
| ^~~~~~~~~One (discarded) option was to use token_context_lock(turnstile) to just define a token with the already used name, but that would not allow the compiler to distinguish between different mm_id-dependent instances.
Another constraint is that struct mm_id is only declared and incomplete in the header, so even if we tried to construct an expression to get to the mutex instance, this would fail (including more headers transitively everywhere should also be avoided).
Instead, just declare an mm_id-dependent helper to return the mutex, and use the mm_id-dependent call expression in the __acquires/__releases attributes; the compiler will consider the identity of the mutex to be the call expression. Then using __get_turnstile() in the lock/unlock wrappers (with context analysis enabled for mmu.c) the compiler will be able to verify the implementation of the wrappers as-is.
We leave context analysis disabled in arch/um/kernel/skas/ for now. This change is a preparatory change to allow enabling context analysis in subsystems that include any of the above headers.
No functional change intended.
--- arch/um/include/shared/skas/mm_id.h | 5 +++-- arch/um/kernel/skas/mmu.c | 13 ++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-)
arch/um/include/shared/skas/mm_id.h +3 -2
@@ -21,8 +21,9 @@ struct mm_id {int syscall_fd_map[STUB_MAX_FDS ]; }; -void enter_turnstile(struct mm_id *mm_id) __acquires(turnstile); -void exit_turnstile(struct mm_id *mm_id) __releases(turnstile); +struct mutex *__get_turnstile (struct mm_id *mm_id); +void enter_turnstile(struct mm_id *mm_id) __acquires(__get_turnstile(mm_id)); +void exit_turnstile(struct mm_id *mm_id) __releases(__get_turnstile(mm_id));void notify_mm_kill (int pid);
arch/um/kernel/skas/mmu.c +8 -5
@@ -23,18 +23,21 @@ static_assert(sizeof(struct stub_data) == STUB_DATA_PAGES * UM_KERN_PAGE_SIZE);static spinlock_t mm_list_lock;static struct list_head mm_list; -void enter_turnstile (struct mm_id *mm_id)__acquires (turnstile) +struct mutex *__get_turnstile (struct mm_id *mm_id) { struct mm_context *ctx = container_of(mm_id, struct mm_context, id); -mutex_lock (&ctx->turnstile); +return &ctx->turnstile; } -void exit_turnstile (struct mm_id *mm_id)__releases (turnstile) +void enter_turnstile (struct mm_id *mm_id) { - struct mm_context *ctx = container_of(mm_id, struct mm_context, id); +mutex_lock (__get_turnstile (mm_id)); +} -mutex_unlock (&ctx->turnstile); +void exit_turnstile (struct mm_id *mm_id) +{ +mutex_unlock (__get_turnstile (mm_id)); }int init_new_context (struct task_struct *task,struct mm_struct *mm)
Marco Elver
maintainerPATCH v5 23/36 compiler-context-analysis: Remove Sparse support
In reply to Marco ElverRemove Sparse support as discussed at [1].
The kernel codebase is still scattered with numerous places that try to appease Sparse's context tracking ("annotation for sparse", "fake out sparse", "work around sparse", etc.). Eventually, as more subsystems enable Clang's context analysis, these places will show up and need adjustment or removal of the workarounds altogether.
---
v5:
* Rename "context guard" -> "context lock".
v4:
* Rename capability -> context analysis.
v2:
* New patch.
--- Documentation/dev-tools/sparse.rst | 19 ----- include/linux/compiler-context-analysis.h | 85 +++++++---------------- include/linux/rcupdate.h | 15 +--- 3 files changed, 28 insertions(+), 91 deletions(-)
Documentation/dev-tools/sparse.rst +0 -19
@@ -53,25 +53,6 @@ sure that bitwise types don't get mixed up (little-endian vs big-endian vs cpu-endian vs whatever), and there the constant "0" really _is_ special. -Using sparse for lock checking ------------------------------- - -The following macros are undefined for gcc and defined during a sparse -run to use the "context" tracking feature of sparse, applied to -locking. These annotations tell sparse when a lock is held, with -regard to the annotated function's entry and exit. - -__must_hold - The specified lock is held on function entry and exit. - -__acquires - The specified lock is held on function exit, but not entry. - -__releases - The specified lock is held on function entry, but not exit. - -If the function enters and exits without the lock held, acquiring and -releasing the lock inside the function in a balanced way, no -annotation is needed. The three annotations above are for cases where -sparse would otherwise report a context imbalance. - Getting sparse --------------
include/linux/compiler-context-analysis.h +27 -58
186 lines not on this page · raw message
include/linux/rcupdate.h +1 -14
@@ -1219,20 +1219,7 @@ rcu_head_after_call_rcu(struct rcu_head *rhp, rcu_callback_t f)extern int rcu_expedited;extern int rcu_normal; -DEFINE_LOCK_GUARD_0(rcu, - do { - rcu_read_lock(); - /* - * sparse doesn't call the cleanup function, - * so just release immediately and don't track - * the context. We don't need to anyway, since - * the whole point of the guard is to not need - * the explicit unlock. - */ - __release(RCU); - } while (0), - rcu_read_unlock()) - +DEFINE_LOCK_GUARD_0(rcu, rcu_read_lock(), rcu_read_unlock()) DECLARE_LOCK_GUARD_0_ATTRS(rcu, __acquires_shared(RCU), __releases_shared(RCU))#endif /* __LINUX_RCUPDATE_H */
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Re: [PATCH v5 23/36] compiler-context-analysis: Remove Sparse support
Quoted 1 line · Marco Elver
Remove Sparse support as discussed at [1].
Kernel patch descriptions should be self-contained. In other words, the conclusion from [1] should be summarized in the patch description instead of only referring to that discussion with a hyperlink.
Thanks,
Bart.
[tip: locking/core] compiler-context-analysis: Remove Sparse support
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 5b63d0ae94ccfd64dcbdb693d88eb3650eb3c64c Gitweb: https://git.kernel.org/tip/5b63d0ae94ccfd64dcbdb693d88eb3650eb3c64c Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:12 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:33 +01:00
compiler-context-analysis: Remove Sparse support
Remove Sparse support as discussed at [1].
The kernel codebase is still scattered with numerous places that try to appease Sparse's context tracking ("annotation for sparse", "fake out sparse", "work around sparse", etc.). Eventually, as more subsystems enable Clang's context analysis, these places will show up and need adjustment or removal of the workarounds altogether.
--- Documentation/dev-tools/sparse.rst | 19 +----- include/linux/compiler-context-analysis.h | 85 ++++++---------------- include/linux/rcupdate.h | 15 +---- 3 files changed, 28 insertions(+), 91 deletions(-)
Documentation/dev-tools/sparse.rst +0 -19
@@ -53,25 +53,6 @@ sure that bitwise types don't get mixed up (little-endian vs big-endian vs cpu-endian vs whatever), and there the constant "0" really _is_ special. -Using sparse for lock checking ------------------------------- - -The following macros are undefined for gcc and defined during a sparse -run to use the "context" tracking feature of sparse, applied to -locking. These annotations tell sparse when a lock is held, with -regard to the annotated function's entry and exit. - -__must_hold - The specified lock is held on function entry and exit. - -__acquires - The specified lock is held on function exit, but not entry. - -__releases - The specified lock is held on function entry, but not exit. - -If the function enters and exits without the lock held, acquiring and -releasing the lock inside the function in a balanced way, no -annotation is needed. The three annotations above are for cases where -sparse would otherwise report a context imbalance. - Getting sparse --------------
include/linux/compiler-context-analysis.h +27 -58
186 lines not on this page · raw message
include/linux/rcupdate.h +1 -14
@@ -1219,20 +1219,7 @@ rcu_head_after_call_rcu(struct rcu_head *rhp, rcu_callback_t f)extern int rcu_expedited;extern int rcu_normal; -DEFINE_LOCK_GUARD_0(rcu, - do { - rcu_read_lock(); - /* - * sparse doesn't call the cleanup function, - * so just release immediately and don't track - * the context. We don't need to anyway, since - * the whole point of the guard is to not need - * the explicit unlock. - */ - __release(RCU); - } while (0), - rcu_read_unlock()) - +DEFINE_LOCK_GUARD_0(rcu, rcu_read_lock(), rcu_read_unlock()) DECLARE_LOCK_GUARD_0_ATTRS(rcu, __acquires_shared(RCU), __releases_shared(RCU))#endif /* __LINUX_RCUPDATE_H */
Marco Elver
maintainerPATCH v5 24/36 compiler-context-analysis: Remove __cond_lock() function-like helper
In reply to Marco ElverAs discussed in [1], removing __cond_lock() will improve the readability of trylock code. Now that Sparse context tracking support has been removed, we can also remove __cond_lock().
Change existing APIs to either drop __cond_lock() completely, or make use of the __cond_acquires() function attribute instead.
In particular, spinlock and rwlock implementations required switching over to inline helpers rather than statement-expressions for their trylock_* variants.
---
v5:
* Fix up include/linux/lockref.h, too.
v2:
* New patch.
--- Documentation/dev-tools/context-analysis.rst | 2 - Documentation/mm/process_addrs.rst | 6 +- .../net/wireless/intel/iwlwifi/iwl-trans.c | 4 +- .../net/wireless/intel/iwlwifi/iwl-trans.h | 6 +- .../intel/iwlwifi/pcie/gen1_2/internal.h | 5 +- .../intel/iwlwifi/pcie/gen1_2/trans.c | 4 +- include/linux/compiler-context-analysis.h | 31 ---------- include/linux/lockref.h | 4 +- include/linux/mm.h | 33 ++-------- include/linux/rwlock.h | 11 +--- include/linux/rwlock_api_smp.h | 14 ++++- include/linux/rwlock_rt.h | 21 ++++--- include/linux/sched/signal.h | 14 +---- include/linux/spinlock.h | 45 +++++--------- include/linux/spinlock_api_smp.h | 20 ++++++ include/linux/spinlock_api_up.h | 61 ++++++++++++++++--- include/linux/spinlock_rt.h | 26 ++++---- kernel/signal.c | 4 +- kernel/time/posix-timers.c | 13 +--- lib/dec_and_lock.c | 8 +-- lib/lockref.c | 1 - mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +++--- tools/include/linux/compiler_types.h | 2 - 24 files changed, 163 insertions(+), 195 deletions(-)
Documentation/dev-tools/context-analysis.rst +0 -2
@@ -112,10 +112,8 @@ Keywords __releases_shared __acquire __release - __cond_lock __acquire_shared __release_shared - __cond_lock_shared __acquire_ret __acquire_shared_ret context_unsafe
Documentation/mm/process_addrs.rst +3 -3
@@ -583,7 +583,7 @@ To access PTE-level page tables, a helper like :c:func:`!pte_offset_map_lock` or :c:func:`!pte_offset_map` can be used depending on stability requirements. These map the page table into kernel memory if required, take the RCU lock, and depending on variant, may also look up or acquire the PTE lock. -See the comment on :c:func:`!__pte_offset_map_lock`. +See the comment on :c:func:`!pte_offset_map_lock`. Atomicity ^^^^^^^^^
@@ -667,7 +667,7 @@ must be released via :c:func:`!pte_unmap_unlock`. .. note:: There are some variants on this, such as :c:func:`!pte_offset_map_rw_nolock` when we know we hold the PTE stable but for brevity we do not explore this. See the comment for - :c:func:`!__pte_offset_map_lock` for more details. + :c:func:`!pte_offset_map_lock` for more details. When modifying data in ranges we typically only wish to allocate higher page tables as necessary, using these locks to avoid races or overwriting anything,
@@ -686,7 +686,7 @@ At the leaf page table, that is the PTE, we can't entirely rely on this pattern as we have separate PMD and PTE locks and a THP collapse for instance might have eliminated the PMD entry as well as the PTE from under us. -This is why :c:func:`!__pte_offset_map_lock` locklessly retrieves the PMD entry +This is why :c:func:`!pte_offset_map_lock` locklessly retrieves the PMD entry for the PTE, carefully checking it is as expected, before acquiring the PTE-specific lock, and then *again* checking that the PMD entry is as expected.
drivers/net/wireless/intel/iwlwifi/iwl-trans.c +2 -2
@@ -548,11 +548,11 @@ int iwl_trans_read_config32(struct iwl_trans *trans, u32 ofs,return iwl_trans_pcie_read_config32 (trans, ofs, val); } -bool _iwl_trans_grab_nic_access (struct iwl_trans *trans) +bool iwl_trans_grab_nic_access (struct iwl_trans *trans) {return iwl_trans_pcie_grab_nic_access (trans); } -IWL_EXPORT_SYMBOL (_iwl_trans_grab_nic_access); +IWL_EXPORT_SYMBOL (iwl_trans_grab_nic_access); void __releases(nic_access) iwl_trans_release_nic_access(struct iwl_trans *trans)
drivers/net/wireless/intel/iwlwifi/iwl-trans.h +1 -5
@@ -1063,11 +1063,7 @@ int iwl_trans_sw_reset(struct iwl_trans *trans);void iwl_trans_set_bits_mask (struct iwl_trans *trans,u32 reg,u32 mask,u32 value); -bool _iwl_trans_grab_nic_access (struct iwl_trans *trans); - -#define iwl_trans_grab_nic_access (trans) \ - __cond_lock(nic_access, \ - likely(_iwl_trans_grab_nic_access(trans))) +bool iwl_trans_grab_nic_access (struct iwl_trans *trans); void __releases(nic_access) iwl_trans_release_nic_access(struct iwl_trans *trans);
drivers/net/wireless/intel/iwlwifi/pcie/gen1_2/internal.h +1 -4
@@ -553,10 +553,7 @@ void iwl_trans_pcie_free(struct iwl_trans *trans);void iwl_trans_pcie_free_pnvm_dram_regions (struct iwl_dram_regions *dram_regions,struct device *dev); -bool __iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent); -#define _iwl_trans_pcie_grab_nic_access (trans, silent) \ - __cond_lock(nic_access_nobh, \ - likely(__iwl_trans_pcie_grab_nic_access(trans, silent))) +bool _iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent);void iwl_trans_pcie_check_product_reset_status (struct pci_dev *pdev);void iwl_trans_pcie_check_product_reset_mode (struct pci_dev *pdev);
drivers/net/wireless/intel/iwlwifi/pcie/gen1_2/trans.c +2 -2
@@ -2327,7 +2327,7 @@ EXPORT_SYMBOL(iwl_trans_pcie_reset);* This version doesn't disable BHs but rather assumes they're * already disabled. */ -bool __iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent) +bool _iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent) {int ret;struct iwl_trans_pcie *trans_pcie =IWL_TRANS_GET_PCIE_TRANS (trans);
@@ -2415,7 +2415,7 @@ bool iwl_trans_pcie_grab_nic_access(struct iwl_trans *trans)bool ret;local_bh_disable (); - ret =__iwl_trans_pcie_grab_nic_access (trans, false); + ret =_iwl_trans_pcie_grab_nic_access (trans, false);if (ret) {/* keep BHs disabled until iwl_trans_pcie_release_nic_access */ return ret;
include/linux/compiler-context-analysis.h +0 -31
@@ -341,24 +341,6 @@ static inline void _context_unsafe_alias(void **p) { }*/ #define __release (x) __release_ctx_lock(x) -/** -* __cond_lock() - function that conditionally acquires a context lock -* exclusively -* @x: context lock instance pinter -* @c: boolean expression -* -* Return: result of @c -* -* No-op function that conditionally acquires context lock instance @x -* exclusively, if the boolean expression @c is true. The result of @c is the -* return value; for example: -* -* .. code-block:: c -* -* #define spin_trylock(l) __cond_lock(&lock, _spin_trylock(&lock)) -*/ -#define __cond_lock (x, c) __try_acquire_ctx_lock(x, c) -/** * __must_hold_shared() - function attribute, caller must hold shared context lock *
@@ -417,19 +399,6 @@ static inline void _context_unsafe_alias(void **p) { }*/ #define __release_shared (x) __release_shared_ctx_lock(x) -/** -* __cond_lock_shared() - function that conditionally acquires a context lock shared -* @x: context lock instance pinter -* @c: boolean expression -* -* Return: result of @c -* -* No-op function that conditionally acquires context lock instance @x with -* shared access, if the boolean expression @c is true. The result of @c is the -* return value. -*/ -#define __cond_lock_shared (x, c) __try_acquire_shared_ctx_lock(x, c) -/** * __acquire_ret() - helper to acquire context lock of return value * @call: call expression
include/linux/lockref.h +1 -3
@@ -49,9 +49,7 @@ static inline void lockref_init(struct lockref *lockref)void lockref_get (struct lockref *lockref);int lockref_put_return (struct lockref *lockref);bool lockref_get_not_zero (struct lockref *lockref); -bool lockref_put_or_lock (struct lockref *lockref); -#define lockref_put_or_lock (_lockref) \ - (!__cond_lock((_lockref)->lock, !lockref_put_or_lock(_lockref))) +bool lockref_put_or_lock(struct lockref *lockref) __cond_acquires(false, &lockref->lock);void lockref_mark_dead (struct lockref *lockref);bool lockref_get_not_dead (struct lockref *lockref);
include/linux/mm.h +5 -28
@@ -2975,15 +2975,8 @@ static inline pud_t pud_mkspecial(pud_t pud) }#endif /* CONFIG_ARCH_SUPPORTS_PUD_PFNMAP */ -extern pte_t *__get_locked_pte (struct mm_struct *mm,unsigned long addr, -spinlock_t **ptl); -static inline pte_t *get_locked_pte (struct mm_struct *mm,unsigned long addr, -spinlock_t **ptl) -{ -pte_t *ptep; -__cond_lock (*ptl, ptep =__get_locked_pte (mm, addr, ptl)); -return ptep; -} +extern pte_t *get_locked_pte (struct mm_struct *mm,unsigned long addr, +spinlock_t **ptl);#ifdef __PAGETABLE_P4D_FOLDED static inline int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd,
@@ -3337,31 +3330,15 @@ static inline bool pagetable_pte_ctor(struct mm_struct *mm,return true; } -pte_t *___pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp); -static inline pte_t *__pte_offset_map (pmd_t *pmd,unsigned long addr, -pmd_t *pmdvalp) -{ -pte_t *pte; +pte_t *__pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp); -__cond_lock (RCU , pte =___pte_offset_map (pmd, addr, pmdvalp)); -return pte; -}static inline pte_t *pte_offset_map (pmd_t *pmd,unsigned long addr) {return __pte_offset_map (pmd, addr,NULL ); } -pte_t *__pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, -unsigned long addr,spinlock_t **ptlp); -static inline pte_t *pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, -unsigned long addr,spinlock_t **ptlp) -{ -pte_t *pte; - -__cond_lock (RCU ,__cond_lock (*ptlp, - pte =__pte_offset_map_lock (mm, pmd, addr, ptlp))); -return pte; -} +pte_t *pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, +unsigned long addr,spinlock_t **ptlp);pte_t *pte_offset_map_ro_nolock (struct mm_struct *mm,pmd_t *pmd,unsigned long addr,spinlock_t **ptlp);
include/linux/rwlock.h +3 -8
@@ -50,8 +50,8 @@ do { \* regardless of whether CONFIG_SMP or CONFIG_PREEMPT are set. The various * methods are defined as nops in the case they are not required. */ -#define read_trylock (lock) __cond_lock_shared(lock, _raw_read_trylock(lock)) -#define write_trylock (lock) __cond_lock(lock, _raw_write_trylock(lock)) +#define read_trylock (lock) _raw_read_trylock(lock) +#define write_trylock (lock) _raw_write_trylock(lock)#define write_lock (lock) _raw_write_lock(lock)#define read_lock (lock) _raw_read_lock(lock)
@@ -113,12 +113,7 @@ do { \ } while (0)#define write_unlock_bh (lock) _raw_write_unlock_bh(lock) -#define write_trylock_irqsave (lock, flags) \ - __cond_lock(lock, ({ \ - local_irq_save(flags); \ - _raw_write_trylock(lock) ? \ - 1 : ({ local_irq_restore(flags); 0; }); \ - })) +#define write_trylock_irqsave (lock, flags) _raw_write_trylock_irqsave(lock, &(flags))#ifdef arch_rwlock_is_contended#define rwlock_is_contended (lock) \
include/linux/rwlock_api_smp.h +12 -2
@@ -26,8 +26,8 @@ unsigned long __lockfunc _raw_read_lock_irqsave(rwlock_t *lock)__acquires (lock); unsigned long __lockfunc _raw_write_lock_irqsave(rwlock_t *lock) __acquires(lock); -int __lockfunc _raw_read_trylock(rwlock_t *lock); -int __lockfunc _raw_write_trylock(rwlock_t *lock); +int __lockfunc _raw_read_trylock(rwlock_t *lock) __cond_acquires_shared(true, lock); +int __lockfunc _raw_write_trylock(rwlock_t *lock) __cond_acquires(true, lock); void __lockfunc _raw_read_unlock(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock(rwlock_t *lock) __releases(lock); void __lockfunc _raw_read_unlock_bh(rwlock_t *lock) __releases_shared(lock);
@@ -41,6 +41,16 @@ void __lockfunc _raw_write_unlock_irqrestore(rwlock_t *lock, unsigned long flags)__releases (lock); +static inline bool _raw_write_trylock_irqsave (rwlock_t *lock,unsigned long *flags) +__cond_acquires (true, lock) +{ +local_irq_save (*flags); +if (_raw_write_trylock (lock)) +return true; +local_irq_restore (*flags); +return false; +} +#ifdef CONFIG_INLINE_READ_LOCK #define _raw_read_lock (lock) __raw_read_lock(lock)#endif
include/linux/rwlock_rt.h +11 -10
@@ -26,11 +26,11 @@ do { \ }while (0 ) extern void rt_read_lock(rwlock_t *rwlock) __acquires_shared(rwlock); -extern int rt_read_trylock (rwlock_t *rwlock); +extern int rt_read_trylock(rwlock_t *rwlock) __cond_acquires_shared(true, rwlock); extern void rt_read_unlock(rwlock_t *rwlock) __releases_shared(rwlock); extern void rt_write_lock(rwlock_t *rwlock) __acquires(rwlock); extern void rt_write_lock_nested(rwlock_t *rwlock, int subclass) __acquires(rwlock); -extern int rt_write_trylock (rwlock_t *rwlock); +extern int rt_write_trylock(rwlock_t *rwlock) __cond_acquires(true, rwlock); extern void rt_write_unlock(rwlock_t *rwlock) __releases(rwlock); static __always_inline void read_lock(rwlock_t *rwlock)
@@ -59,7 +59,7 @@ static __always_inline void read_lock_irq(rwlock_t *rwlock) flags =0 ; \ } while (0) -#define read_trylock (lock) __cond_lock_shared(lock, rt_read_trylock(lock)) +#define read_trylock (lock) rt_read_trylock(lock) static __always_inline void read_unlock(rwlock_t *rwlock) __releases_shared(rwlock)
@@ -123,14 +123,15 @@ static __always_inline void write_lock_irq(rwlock_t *rwlock) flags =0 ; \ } while (0) -#define write_trylock (lock) __cond_lock(lock, rt_write_trylock(lock)) +#define write_trylock (lock) rt_write_trylock(lock) -#define write_trylock_irqsave (lock, flags) \ - __cond_lock(lock, ({ \ - typecheck(unsigned long, flags); \ - flags = 0; \ - rt_write_trylock(lock); \ - })) +static __always_inline bool _write_trylock_irqsave(rwlock_t *rwlock, unsigned long *flags) +__cond_acquires (true, rwlock) +{ + *flags =0 ; +return rt_write_trylock (rwlock); +} +#define write_trylock_irqsave (lock, flags) _write_trylock_irqsave(lock, &(flags)) static __always_inline void write_unlock(rwlock_t *rwlock) __releases(rwlock)
include/linux/sched/signal.h +2 -12
@@ -737,18 +737,8 @@ static inline int thread_group_empty(struct task_struct *p)#define delay_group_leader (p) \ (thread_group_leader(p) && !thread_group_empty(p)) -extern struct sighand_struct *__lock_task_sighand (struct task_struct *task, -unsigned long *flags); - -static inline struct sighand_struct *lock_task_sighand (struct task_struct *task, -unsigned long *flags) -{ -struct sighand_struct *ret; - - ret =__lock_task_sighand (task, flags); - (void )__cond_lock (&task->sighand->siglock, ret); -return ret; -} +extern struct sighand_struct *lock_task_sighand (struct task_struct *task, +unsigned long *flags);static inline void unlock_task_sighand (struct task_struct *task,unsigned long *flags)
include/linux/spinlock.h +16 -29
76 lines not on this page · raw message
include/linux/spinlock_api_smp.h +20 -0
@@ -95,6 +95,26 @@ static inline int __raw_spin_trylock(raw_spinlock_t *lock)return 0 ; } +static __always_inline bool _raw_spin_trylock_irq(raw_spinlock_t *lock) +__cond_acquires (true, lock) +{ +local_irq_disable (); +if (_raw_spin_trylock (lock)) +return true; +local_irq_enable (); +return false; +} + +static __always_inline bool _raw_spin_trylock_irqsave(raw_spinlock_t *lock, unsigned long *flags) +__cond_acquires (true, lock) +{ +local_irq_save (*flags); +if (_raw_spin_trylock (lock)) +return true; +local_irq_restore (*flags); +return false; +} +/* * If lockdep is enabled then we use the non-preemption spin-ops * even on CONFIG_PREEMPTION, because lockdep assumes that interrupts are
include/linux/spinlock_api_up.h +52 -9
76 lines not on this page · raw message
include/linux/spinlock_rt.h +12 -14
@@ -37,8 +37,8 @@ extern void rt_spin_lock_nested(spinlock_t *lock, int subclass) __acquires(lock) extern void rt_spin_lock_nest_lock(spinlock_t *lock, struct lockdep_map *nest_lock) __acquires(lock); extern void rt_spin_unlock(spinlock_t *lock) __releases(lock);extern void rt_spin_lock_unlock (spinlock_t *lock); -extern int rt_spin_trylock_bh (spinlock_t *lock); -extern int rt_spin_trylock (spinlock_t *lock); +extern int rt_spin_trylock_bh(spinlock_t *lock) __cond_acquires(true, lock); +extern int rt_spin_trylock(spinlock_t *lock) __cond_acquires(true, lock); static __always_inline void spin_lock(spinlock_t *lock) __acquires(lock)
@@ -130,21 +130,19 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock,rt_spin_unlock (lock); } -#define spin_trylock (lock) \ - __cond_lock(lock, rt_spin_trylock(lock)) +#define spin_trylock (lock) rt_spin_trylock(lock) -#define spin_trylock_bh (lock) \ - __cond_lock(lock, rt_spin_trylock_bh(lock)) +#define spin_trylock_bh (lock) rt_spin_trylock_bh(lock) -#define spin_trylock_irq (lock) \ - __cond_lock(lock, rt_spin_trylock(lock)) +#define spin_trylock_irq (lock) rt_spin_trylock(lock) -#define spin_trylock_irqsave (lock, flags) \ - __cond_lock(lock, ({ \ - typecheck(unsigned long, flags); \ - flags = 0; \ - rt_spin_trylock(lock); \ - })) +static __always_inline bool _spin_trylock_irqsave(spinlock_t *lock, unsigned long *flags) +__cond_acquires (true, lock) +{ + *flags =0 ; +return rt_spin_trylock (lock); +} +#define spin_trylock_irqsave (lock, flags) _spin_trylock_irqsave(lock, &(flags))#define spin_is_contended (lock) (((void)(lock), 0))
kernel/signal.c +2 -2
@@ -1355,8 +1355,8 @@ int zap_other_threads(struct task_struct *p)return count; } -struct sighand_struct *__lock_task_sighand (struct task_struct *tsk, -unsigned long *flags) +struct sighand_struct *lock_task_sighand (struct task_struct *tsk, +unsigned long *flags) {struct sighand_struct *sighand;
kernel/time/posix-timers.c +3 -10
@@ -66,14 +66,7 @@ static const struct k_clock clock_realtime, clock_monotonic;#error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"#endif -static struct k_itimer *__lock_timer (timer_t timer_id); - -#define lock_timer (tid) \ -({ struct k_itimer *__timr; \ - __cond_lock(&__timr->it_lock, __timr = __lock_timer(tid)); \ - __timr; \ -}) - +static struct k_itimer *lock_timer (timer_t timer_id);static inline void unlock_timer (struct k_itimer *timr) {if (likely ((timr)))
@@ -85,7 +78,7 @@ static inline void unlock_timer(struct k_itimer *timr)#define scoped_timer (scope) -DEFINE_CLASS(lock_timer, struct k_itimer *, unlock_timer(_T), __lock_timer(id), timer_t id); +DEFINE_CLASS(lock_timer, struct k_itimer *, unlock_timer(_T), lock_timer(id), timer_t id);DEFINE_CLASS_IS_COND_GUARD (lock_timer);static struct timer_hash_bucket *hash_bucket (struct signal_struct *sig,unsigned int nr)
@@ -600,7 +593,7 @@ COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock, }#endif -static struct k_itimer *__lock_timer (timer_t timer_id) +static struct k_itimer *lock_timer (timer_t timer_id) {struct k_itimer *timr;
lib/dec_and_lock.c +4 -4
@@ -18,7 +18,7 @@* because the spin-lock and the decrement must be * "atomic". */ -int _atomic_dec_and_lock (atomic_t *atomic,spinlock_t *lock) +int atomic_dec_and_lock (atomic_t *atomic,spinlock_t *lock) {/* Subtract 1 from counter unless that drops it to 0 (ie. it was 1) */ if (atomic_add_unless (atomic,-1 ,1 ))
@@ -32,7 +32,7 @@ int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)return 0 ; } -EXPORT_SYMBOL (_atomic_dec_and_lock); +EXPORT_SYMBOL (atomic_dec_and_lock);int _atomic_dec_and_lock_irqsave (atomic_t *atomic,spinlock_t *lock,unsigned long *flags)
@@ -50,7 +50,7 @@ int _atomic_dec_and_lock_irqsave(atomic_t *atomic, spinlock_t *lock, }EXPORT_SYMBOL (_atomic_dec_and_lock_irqsave); -int _atomic_dec_and_raw_lock (atomic_t *atomic,raw_spinlock_t *lock) +int atomic_dec_and_raw_lock (atomic_t *atomic,raw_spinlock_t *lock) {/* Subtract 1 from counter unless that drops it to 0 (ie. it was 1) */ if (atomic_add_unless (atomic,-1 ,1 ))
@@ -63,7 +63,7 @@ int _atomic_dec_and_raw_lock(atomic_t *atomic, raw_spinlock_t *lock)raw_spin_unlock (lock);return 0 ; } -EXPORT_SYMBOL (_atomic_dec_and_raw_lock); +EXPORT_SYMBOL (atomic_dec_and_raw_lock);int _atomic_dec_and_raw_lock_irqsave (atomic_t *atomic,raw_spinlock_t *lock,unsigned long *flags)
lib/lockref.c +0 -1
@@ -105,7 +105,6 @@ EXPORT_SYMBOL(lockref_put_return);* @lockref: pointer to lockref structure * Return: 1 if count updated successfully or 0 if count <= 1 and lock taken */ -#undef lockref_put_or_lockbool lockref_put_or_lock (struct lockref *lockref) { CMPXCHG_LOOP(
mm/memory.c +2 -2
@@ -2210,8 +2210,8 @@ static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)return pmd; } -pte_t *__get_locked_pte (struct mm_struct *mm,unsigned long addr, -spinlock_t **ptl) +pte_t *get_locked_pte (struct mm_struct *mm,unsigned long addr, +spinlock_t **ptl) {pmd_t *pmd =walk_to_pmd (mm, addr);
mm/pgtable-generic.c +9 -10
@@ -280,7 +280,7 @@ static unsigned long pmdp_get_lockless_start(void) { return 0; }static void pmdp_get_lockless_end (unsigned long irqflags) { }#endif -pte_t *___pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp) +pte_t *__pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp) {unsigned long irqflags;pmd_t pmdval;
@@ -332,13 +332,12 @@ pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd, }/* -* pte_offset_map_lock(mm, pmd, addr, ptlp), and its internal implementation -* __pte_offset_map_lock() below, is usually called with the pmd pointer for -* addr, reached by walking down the mm's pgd, p4d, pud for addr: either while -* holding mmap_lock or vma lock for read or for write; or in truncate or rmap -* context, while holding file's i_mmap_lock or anon_vma lock for read (or for -* write). In a few cases, it may be used with pmd pointing to a pmd_t already -* copied to or constructed on the stack. +* pte_offset_map_lock(mm, pmd, addr, ptlp) is usually called with the pmd +* pointer for addr, reached by walking down the mm's pgd, p4d, pud for addr: +* either while holding mmap_lock or vma lock for read or for write; or in +* truncate or rmap context, while holding file's i_mmap_lock or anon_vma lock +* for read (or for write). In a few cases, it may be used with pmd pointing to +* a pmd_t already copied to or constructed on the stack. * * When successful, it returns the pte pointer for addr, with its page table * kmapped if necessary (when CONFIG_HIGHPTE), and locked against concurrent
@@ -389,8 +388,8 @@ pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd,* table, and may not use RCU at all: "outsiders" like khugepaged should avoid * pte_offset_map() and co once the vma is detached from mm or mm_users is zero. */ -pte_t *__pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, -unsigned long addr,spinlock_t **ptlp) +pte_t *pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, +unsigned long addr,spinlock_t **ptlp) {spinlock_t *ptl;pmd_t pmdval;
tools/include/linux/compiler_types.h +0 -2
@@ -20,7 +20,6 @@# define __releases (x) __attribute__((context(x,1,0)))# define __acquire (x) __context__(x,1)# define __release (x) __context__(x,-1) -# define __cond_lock (x,c) ((c) ? ({ __acquire(x); 1; }) : 0)#else /* __CHECKER__ */ /* context/locking */ # define __must_hold (x)
@@ -28,7 +27,6 @@# define __releases (x)# define __acquire (x) (void)0# define __release (x) (void)0 -# define __cond_lock (x,c) (c)#endif /* __CHECKER__ */ /* Compiler specific macros. */
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
Re: [PATCH v5 24/36] compiler-context-analysis: Remove __cond_lock() function-like helper
Quoted 16 lines · Marco Elver
Documentation/dev-tools/context-analysis.rst | 2 - Documentation/mm/process_addrs.rst | 6 +- .../net/wireless/intel/iwlwifi/iwl-trans.c | 4 +- .../net/wireless/intel/iwlwifi/iwl-trans.h | 6 +- .../intel/iwlwifi/pcie/gen1_2/internal.h | 5 +- .../intel/iwlwifi/pcie/gen1_2/trans.c | 4 +- include/linux/compiler-context-analysis.h | 31 ---------- include/linux/lockref.h | 4 +- include/linux/mm.h | 33 ++-------- include/linux/rwlock.h | 11 +--- include/linux/rwlock_api_smp.h | 14 ++++- include/linux/rwlock_rt.h | 21 ++++--- include/linux/sched/signal.h | 14 +---- include/linux/spinlock.h | 45 +++++--------- include/linux/spinlock_api_smp.h | 20 ++++++ include/linux/spinlock_api_up.h | 61 ++++++++++++++++---
Quoted 8 lines
include/linux/spinlock_rt.h | 26 ++++---- kernel/signal.c | 4 +- kernel/time/posix-timers.c | 13 +--- lib/dec_and_lock.c | 8 +-- lib/lockref.c | 1 - mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +++--- tools/include/linux/compiler_types.h | 2 -
This patch should be split into one patch per subsystem or driver. E.g. one patch for the iwlwifi driver, another patch for the mm subsystem, one patch for the rwlock primitive, one patch for the spinlock primitive, etc.
The tools/include/linux/compiler_types.h change probably should be left out because it is user space code instead of kernel code and the rest of the series applies to kernel code only.
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v5 24/36] compiler-context-analysis: Remove __cond_lock() function-like helper
Quoted 26 lines · Bart Van Assche
Quoted 16 lines · Marco Elver
Documentation/dev-tools/context-analysis.rst | 2 - Documentation/mm/process_addrs.rst | 6 +- .../net/wireless/intel/iwlwifi/iwl-trans.c | 4 +- .../net/wireless/intel/iwlwifi/iwl-trans.h | 6 +- .../intel/iwlwifi/pcie/gen1_2/internal.h | 5 +- .../intel/iwlwifi/pcie/gen1_2/trans.c | 4 +- include/linux/compiler-context-analysis.h | 31 ---------- include/linux/lockref.h | 4 +- include/linux/mm.h | 33 ++-------- include/linux/rwlock.h | 11 +--- include/linux/rwlock_api_smp.h | 14 ++++- include/linux/rwlock_rt.h | 21 ++++--- include/linux/sched/signal.h | 14 +---- include/linux/spinlock.h | 45 +++++--------- include/linux/spinlock_api_smp.h | 20 ++++++ include/linux/spinlock_api_up.h | 61 ++++++++++++++++---Quoted 8 lines
include/linux/spinlock_rt.h | 26 ++++---- kernel/signal.c | 4 +- kernel/time/posix-timers.c | 13 +--- lib/dec_and_lock.c | 8 +-- lib/lockref.c | 1 - mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +++--- tools/include/linux/compiler_types.h | 2 -
Quoted 8 lines
This patch should be split into one patch per subsystem or driver. E.g. one patch for the iwlwifi driver, another patch for the mm subsystem, one patch for the rwlock primitive, one patch for the spinlock primitive, etc.
The
tools/include/linux/compiler_types.hchange probably should be left out because it is user space code instead of kernel code and the rest of the series applies to kernel code only.
AFAIK, the user space version is just a copy of the kernel version to support headers that are used by both. See 4bba4c4bb09ad4a2b70836725e08439c86d8f9e4. The sparse annotations were copied in ab3c0ddb0d71dc214b61d11deb8770196ef46c05.
And there's no point in keeping it around given it's all gone:
% git grep __cond_lock
<nothing>
[tip: locking/core] compiler-context-analysis: Remove __cond_lock() function-like helper
In reply to Marco ElverThe following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: e4588c25c9d122b5847b88e18b184404b6959160 Gitweb: https://git.kernel.org/tip/e4588c25c9d122b5847b88e18b184404b6959160 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:13 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:33 +01:00
compiler-context-analysis: Remove __cond_lock() function-like helper
As discussed in [1], removing __cond_lock() will improve the readability of trylock code. Now that Sparse context tracking support has been removed, we can also remove __cond_lock().
Change existing APIs to either drop __cond_lock() completely, or make use of the __cond_acquires() function attribute instead.
In particular, spinlock and rwlock implementations required switching over to inline helpers rather than statement-expressions for their trylock_* variants.
--- Documentation/dev-tools/context-analysis.rst | 2 +- Documentation/mm/process_addrs.rst | 6 +- drivers/net/wireless/intel/iwlwifi/iwl-trans.c | 4 +- drivers/net/wireless/intel/iwlwifi/iwl-trans.h | 6 +- drivers/net/wireless/intel/iwlwifi/pcie/gen1_2/internal.h | 5 +- drivers/net/wireless/intel/iwlwifi/pcie/gen1_2/trans.c | 4 +- include/linux/compiler-context-analysis.h | 31 +---- include/linux/lockref.h | 4 +- include/linux/mm.h | 33 +---- include/linux/rwlock.h | 11 +- include/linux/rwlock_api_smp.h | 14 +- include/linux/rwlock_rt.h | 21 +- include/linux/sched/signal.h | 14 +-- include/linux/spinlock.h | 45 +---- include/linux/spinlock_api_smp.h | 20 ++- include/linux/spinlock_api_up.h | 61 +++++-- include/linux/spinlock_rt.h | 26 +-- kernel/signal.c | 4 +- kernel/time/posix-timers.c | 13 +- lib/dec_and_lock.c | 8 +- lib/lockref.c | 1 +- mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +-- tools/include/linux/compiler_types.h | 2 +- 24 files changed, 163 insertions(+), 195 deletions(-)
Documentation/dev-tools/context-analysis.rst +0 -2
@@ -112,10 +112,8 @@ Keywords __releases_shared __acquire __release - __cond_lock __acquire_shared __release_shared - __cond_lock_shared __acquire_ret __acquire_shared_ret context_unsafe
Documentation/mm/process_addrs.rst +3 -3
@@ -583,7 +583,7 @@ To access PTE-level page tables, a helper like :c:func:`!pte_offset_map_lock` or :c:func:`!pte_offset_map` can be used depending on stability requirements. These map the page table into kernel memory if required, take the RCU lock, and depending on variant, may also look up or acquire the PTE lock. -See the comment on :c:func:`!__pte_offset_map_lock`. +See the comment on :c:func:`!pte_offset_map_lock`. Atomicity ^^^^^^^^^
@@ -667,7 +667,7 @@ must be released via :c:func:`!pte_unmap_unlock`. .. note:: There are some variants on this, such as :c:func:`!pte_offset_map_rw_nolock` when we know we hold the PTE stable but for brevity we do not explore this. See the comment for - :c:func:`!__pte_offset_map_lock` for more details. + :c:func:`!pte_offset_map_lock` for more details. When modifying data in ranges we typically only wish to allocate higher page tables as necessary, using these locks to avoid races or overwriting anything,
@@ -686,7 +686,7 @@ At the leaf page table, that is the PTE, we can't entirely rely on this pattern as we have separate PMD and PTE locks and a THP collapse for instance might have eliminated the PMD entry as well as the PTE from under us. -This is why :c:func:`!__pte_offset_map_lock` locklessly retrieves the PMD entry +This is why :c:func:`!pte_offset_map_lock` locklessly retrieves the PMD entry for the PTE, carefully checking it is as expected, before acquiring the PTE-specific lock, and then *again* checking that the PMD entry is as expected.
drivers/net/wireless/intel/iwlwifi/iwl-trans.c +2 -2
@@ -548,11 +548,11 @@ int iwl_trans_read_config32(struct iwl_trans *trans, u32 ofs,return iwl_trans_pcie_read_config32 (trans, ofs, val); } -bool _iwl_trans_grab_nic_access (struct iwl_trans *trans) +bool iwl_trans_grab_nic_access (struct iwl_trans *trans) {return iwl_trans_pcie_grab_nic_access (trans); } -IWL_EXPORT_SYMBOL (_iwl_trans_grab_nic_access); +IWL_EXPORT_SYMBOL (iwl_trans_grab_nic_access); void __releases(nic_access) iwl_trans_release_nic_access(struct iwl_trans *trans)
drivers/net/wireless/intel/iwlwifi/iwl-trans.h +1 -5
@@ -1063,11 +1063,7 @@ int iwl_trans_sw_reset(struct iwl_trans *trans);void iwl_trans_set_bits_mask (struct iwl_trans *trans,u32 reg,u32 mask,u32 value); -bool _iwl_trans_grab_nic_access (struct iwl_trans *trans); - -#define iwl_trans_grab_nic_access (trans) \ - __cond_lock(nic_access, \ - likely(_iwl_trans_grab_nic_access(trans))) +bool iwl_trans_grab_nic_access (struct iwl_trans *trans); void __releases(nic_access) iwl_trans_release_nic_access(struct iwl_trans *trans);
drivers/net/wireless/intel/iwlwifi/pcie/gen1_2/internal.h +1 -4
@@ -553,10 +553,7 @@ void iwl_trans_pcie_free(struct iwl_trans *trans);void iwl_trans_pcie_free_pnvm_dram_regions (struct iwl_dram_regions *dram_regions,struct device *dev); -bool __iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent); -#define _iwl_trans_pcie_grab_nic_access (trans, silent) \ - __cond_lock(nic_access_nobh, \ - likely(__iwl_trans_pcie_grab_nic_access(trans, silent))) +bool _iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent);void iwl_trans_pcie_check_product_reset_status (struct pci_dev *pdev);void iwl_trans_pcie_check_product_reset_mode (struct pci_dev *pdev);
drivers/net/wireless/intel/iwlwifi/pcie/gen1_2/trans.c +2 -2
@@ -2327,7 +2327,7 @@ EXPORT_SYMBOL(iwl_trans_pcie_reset);* This version doesn't disable BHs but rather assumes they're * already disabled. */ -bool __iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent) +bool _iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans,bool silent) {int ret;struct iwl_trans_pcie *trans_pcie =IWL_TRANS_GET_PCIE_TRANS (trans);
@@ -2415,7 +2415,7 @@ bool iwl_trans_pcie_grab_nic_access(struct iwl_trans *trans)bool ret;local_bh_disable (); - ret =__iwl_trans_pcie_grab_nic_access (trans, false); + ret =_iwl_trans_pcie_grab_nic_access (trans, false);if (ret) {/* keep BHs disabled until iwl_trans_pcie_release_nic_access */ return ret;
include/linux/compiler-context-analysis.h +0 -31
@@ -342,24 +342,6 @@ static inline void _context_unsafe_alias(void **p) { }#define __release (x) __release_ctx_lock(x)/** -* __cond_lock() - function that conditionally acquires a context lock -* exclusively -* @x: context lock instance pinter -* @c: boolean expression -* -* Return: result of @c -* -* No-op function that conditionally acquires context lock instance @x -* exclusively, if the boolean expression @c is true. The result of @c is the -* return value; for example: -* -* .. code-block:: c -* -* #define spin_trylock(l) __cond_lock(&lock, _spin_trylock(&lock)) -*/ -#define __cond_lock (x, c) __try_acquire_ctx_lock(x, c) - -/** * __must_hold_shared() - function attribute, caller must hold shared context lock * * Function attribute declaring that the caller must hold the given context
@@ -418,19 +400,6 @@ static inline void _context_unsafe_alias(void **p) { }#define __release_shared (x) __release_shared_ctx_lock(x)/** -* __cond_lock_shared() - function that conditionally acquires a context lock shared -* @x: context lock instance pinter -* @c: boolean expression -* -* Return: result of @c -* -* No-op function that conditionally acquires context lock instance @x with -* shared access, if the boolean expression @c is true. The result of @c is the -* return value. -*/ -#define __cond_lock_shared (x, c) __try_acquire_shared_ctx_lock(x, c) - -/** * __acquire_ret() - helper to acquire context lock of return value * @call: call expression * @ret_expr: acquire expression that uses __ret
include/linux/lockref.h +1 -3
@@ -49,9 +49,7 @@ static inline void lockref_init(struct lockref *lockref)void lockref_get (struct lockref *lockref);int lockref_put_return (struct lockref *lockref);bool lockref_get_not_zero (struct lockref *lockref); -bool lockref_put_or_lock (struct lockref *lockref); -#define lockref_put_or_lock (_lockref) \ - (!__cond_lock((_lockref)->lock, !lockref_put_or_lock(_lockref))) +bool lockref_put_or_lock(struct lockref *lockref) __cond_acquires(false, &lockref->lock);void lockref_mark_dead (struct lockref *lockref);bool lockref_get_not_dead (struct lockref *lockref);
include/linux/mm.h +5 -28
@@ -2975,15 +2975,8 @@ static inline pud_t pud_mkspecial(pud_t pud) }#endif /* CONFIG_ARCH_SUPPORTS_PUD_PFNMAP */ -extern pte_t *__get_locked_pte (struct mm_struct *mm,unsigned long addr, -spinlock_t **ptl); -static inline pte_t *get_locked_pte (struct mm_struct *mm,unsigned long addr, -spinlock_t **ptl) -{ -pte_t *ptep; -__cond_lock (*ptl, ptep =__get_locked_pte (mm, addr, ptl)); -return ptep; -} +extern pte_t *get_locked_pte (struct mm_struct *mm,unsigned long addr, +spinlock_t **ptl);#ifdef __PAGETABLE_P4D_FOLDED static inline int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd,
@@ -3337,31 +3330,15 @@ static inline bool pagetable_pte_ctor(struct mm_struct *mm,return true; } -pte_t *___pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp); -static inline pte_t *__pte_offset_map (pmd_t *pmd,unsigned long addr, -pmd_t *pmdvalp) -{ -pte_t *pte; +pte_t *__pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp); -__cond_lock (RCU , pte =___pte_offset_map (pmd, addr, pmdvalp)); -return pte; -}static inline pte_t *pte_offset_map (pmd_t *pmd,unsigned long addr) {return __pte_offset_map (pmd, addr,NULL ); } -pte_t *__pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, -unsigned long addr,spinlock_t **ptlp); -static inline pte_t *pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, -unsigned long addr,spinlock_t **ptlp) -{ -pte_t *pte; - -__cond_lock (RCU ,__cond_lock (*ptlp, - pte =__pte_offset_map_lock (mm, pmd, addr, ptlp))); -return pte; -} +pte_t *pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, +unsigned long addr,spinlock_t **ptlp);pte_t *pte_offset_map_ro_nolock (struct mm_struct *mm,pmd_t *pmd,unsigned long addr,spinlock_t **ptlp);
include/linux/rwlock.h +3 -8
@@ -50,8 +50,8 @@ do { \* regardless of whether CONFIG_SMP or CONFIG_PREEMPT are set. The various * methods are defined as nops in the case they are not required. */ -#define read_trylock (lock) __cond_lock_shared(lock, _raw_read_trylock(lock)) -#define write_trylock (lock) __cond_lock(lock, _raw_write_trylock(lock)) +#define read_trylock (lock) _raw_read_trylock(lock) +#define write_trylock (lock) _raw_write_trylock(lock)#define write_lock (lock) _raw_write_lock(lock)#define read_lock (lock) _raw_read_lock(lock)
@@ -113,12 +113,7 @@ do { \ } while (0)#define write_unlock_bh (lock) _raw_write_unlock_bh(lock) -#define write_trylock_irqsave (lock, flags) \ - __cond_lock(lock, ({ \ - local_irq_save(flags); \ - _raw_write_trylock(lock) ? \ - 1 : ({ local_irq_restore(flags); 0; }); \ - })) +#define write_trylock_irqsave (lock, flags) _raw_write_trylock_irqsave(lock, &(flags))#ifdef arch_rwlock_is_contended#define rwlock_is_contended (lock) \
include/linux/rwlock_api_smp.h +12 -2
@@ -26,8 +26,8 @@ unsigned long __lockfunc _raw_read_lock_irqsave(rwlock_t *lock)__acquires (lock); unsigned long __lockfunc _raw_write_lock_irqsave(rwlock_t *lock) __acquires(lock); -int __lockfunc _raw_read_trylock(rwlock_t *lock); -int __lockfunc _raw_write_trylock(rwlock_t *lock); +int __lockfunc _raw_read_trylock(rwlock_t *lock) __cond_acquires_shared(true, lock); +int __lockfunc _raw_write_trylock(rwlock_t *lock) __cond_acquires(true, lock); void __lockfunc _raw_read_unlock(rwlock_t *lock) __releases_shared(lock); void __lockfunc _raw_write_unlock(rwlock_t *lock) __releases(lock); void __lockfunc _raw_read_unlock_bh(rwlock_t *lock) __releases_shared(lock);
@@ -41,6 +41,16 @@ void __lockfunc _raw_write_unlock_irqrestore(rwlock_t *lock, unsigned long flags)__releases (lock); +static inline bool _raw_write_trylock_irqsave (rwlock_t *lock,unsigned long *flags) +__cond_acquires (true, lock) +{ +local_irq_save (*flags); +if (_raw_write_trylock (lock)) +return true; +local_irq_restore (*flags); +return false; +} +#ifdef CONFIG_INLINE_READ_LOCK #define _raw_read_lock (lock) __raw_read_lock(lock)#endif
include/linux/rwlock_rt.h +11 -10
@@ -26,11 +26,11 @@ do { \ }while (0 ) extern void rt_read_lock(rwlock_t *rwlock) __acquires_shared(rwlock); -extern int rt_read_trylock (rwlock_t *rwlock); +extern int rt_read_trylock(rwlock_t *rwlock) __cond_acquires_shared(true, rwlock); extern void rt_read_unlock(rwlock_t *rwlock) __releases_shared(rwlock); extern void rt_write_lock(rwlock_t *rwlock) __acquires(rwlock); extern void rt_write_lock_nested(rwlock_t *rwlock, int subclass) __acquires(rwlock); -extern int rt_write_trylock (rwlock_t *rwlock); +extern int rt_write_trylock(rwlock_t *rwlock) __cond_acquires(true, rwlock); extern void rt_write_unlock(rwlock_t *rwlock) __releases(rwlock); static __always_inline void read_lock(rwlock_t *rwlock)
@@ -59,7 +59,7 @@ static __always_inline void read_lock_irq(rwlock_t *rwlock) flags =0 ; \ } while (0) -#define read_trylock (lock) __cond_lock_shared(lock, rt_read_trylock(lock)) +#define read_trylock (lock) rt_read_trylock(lock) static __always_inline void read_unlock(rwlock_t *rwlock) __releases_shared(rwlock)
@@ -123,14 +123,15 @@ static __always_inline void write_lock_irq(rwlock_t *rwlock) flags =0 ; \ } while (0) -#define write_trylock (lock) __cond_lock(lock, rt_write_trylock(lock)) +#define write_trylock (lock) rt_write_trylock(lock) -#define write_trylock_irqsave (lock, flags) \ - __cond_lock(lock, ({ \ - typecheck(unsigned long, flags); \ - flags = 0; \ - rt_write_trylock(lock); \ - })) +static __always_inline bool _write_trylock_irqsave(rwlock_t *rwlock, unsigned long *flags) +__cond_acquires (true, rwlock) +{ + *flags =0 ; +return rt_write_trylock (rwlock); +} +#define write_trylock_irqsave (lock, flags) _write_trylock_irqsave(lock, &(flags)) static __always_inline void write_unlock(rwlock_t *rwlock) __releases(rwlock)
include/linux/sched/signal.h +2 -12
@@ -737,18 +737,8 @@ static inline int thread_group_empty(struct task_struct *p)#define delay_group_leader (p) \ (thread_group_leader(p) && !thread_group_empty(p)) -extern struct sighand_struct *__lock_task_sighand (struct task_struct *task, -unsigned long *flags); - -static inline struct sighand_struct *lock_task_sighand (struct task_struct *task, -unsigned long *flags) -{ -struct sighand_struct *ret; - - ret =__lock_task_sighand (task, flags); - (void )__cond_lock (&task->sighand->siglock, ret); -return ret; -} +extern struct sighand_struct *lock_task_sighand (struct task_struct *task, +unsigned long *flags);static inline void unlock_task_sighand (struct task_struct *task,unsigned long *flags)
include/linux/spinlock.h +16 -29
76 lines not on this page · raw message
include/linux/spinlock_api_smp.h +20 -0
@@ -95,6 +95,26 @@ static inline int __raw_spin_trylock(raw_spinlock_t *lock)return 0 ; } +static __always_inline bool _raw_spin_trylock_irq(raw_spinlock_t *lock) +__cond_acquires (true, lock) +{ +local_irq_disable (); +if (_raw_spin_trylock (lock)) +return true; +local_irq_enable (); +return false; +} + +static __always_inline bool _raw_spin_trylock_irqsave(raw_spinlock_t *lock, unsigned long *flags) +__cond_acquires (true, lock) +{ +local_irq_save (*flags); +if (_raw_spin_trylock (lock)) +return true; +local_irq_restore (*flags); +return false; +} +/* * If lockdep is enabled then we use the non-preemption spin-ops * even on CONFIG_PREEMPTION, because lockdep assumes that interrupts are
include/linux/spinlock_api_up.h +52 -9
76 lines not on this page · raw message
include/linux/spinlock_rt.h +12 -14
@@ -37,8 +37,8 @@ extern void rt_spin_lock_nested(spinlock_t *lock, int subclass) __acquires(lock) extern void rt_spin_lock_nest_lock(spinlock_t *lock, struct lockdep_map *nest_lock) __acquires(lock); extern void rt_spin_unlock(spinlock_t *lock) __releases(lock);extern void rt_spin_lock_unlock (spinlock_t *lock); -extern int rt_spin_trylock_bh (spinlock_t *lock); -extern int rt_spin_trylock (spinlock_t *lock); +extern int rt_spin_trylock_bh(spinlock_t *lock) __cond_acquires(true, lock); +extern int rt_spin_trylock(spinlock_t *lock) __cond_acquires(true, lock); static __always_inline void spin_lock(spinlock_t *lock) __acquires(lock)
@@ -130,21 +130,19 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock,rt_spin_unlock (lock); } -#define spin_trylock (lock) \ - __cond_lock(lock, rt_spin_trylock(lock)) +#define spin_trylock (lock) rt_spin_trylock(lock) -#define spin_trylock_bh (lock) \ - __cond_lock(lock, rt_spin_trylock_bh(lock)) +#define spin_trylock_bh (lock) rt_spin_trylock_bh(lock) -#define spin_trylock_irq (lock) \ - __cond_lock(lock, rt_spin_trylock(lock)) +#define spin_trylock_irq (lock) rt_spin_trylock(lock) -#define spin_trylock_irqsave (lock, flags) \ - __cond_lock(lock, ({ \ - typecheck(unsigned long, flags); \ - flags = 0; \ - rt_spin_trylock(lock); \ - })) +static __always_inline bool _spin_trylock_irqsave(spinlock_t *lock, unsigned long *flags) +__cond_acquires (true, lock) +{ + *flags =0 ; +return rt_spin_trylock (lock); +} +#define spin_trylock_irqsave (lock, flags) _spin_trylock_irqsave(lock, &(flags))#define spin_is_contended (lock) (((void)(lock), 0))
kernel/signal.c +2 -2
@@ -1355,8 +1355,8 @@ int zap_other_threads(struct task_struct *p)return count; } -struct sighand_struct *__lock_task_sighand (struct task_struct *tsk, -unsigned long *flags) +struct sighand_struct *lock_task_sighand (struct task_struct *tsk, +unsigned long *flags) {struct sighand_struct *sighand;
kernel/time/posix-timers.c +3 -10
@@ -66,14 +66,7 @@ static const struct k_clock clock_realtime, clock_monotonic;#error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"#endif -static struct k_itimer *__lock_timer (timer_t timer_id); - -#define lock_timer (tid) \ -({ struct k_itimer *__timr; \ - __cond_lock(&__timr->it_lock, __timr = __lock_timer(tid)); \ - __timr; \ -}) - +static struct k_itimer *lock_timer (timer_t timer_id);static inline void unlock_timer (struct k_itimer *timr) {if (likely ((timr)))
@@ -85,7 +78,7 @@ static inline void unlock_timer(struct k_itimer *timr)#define scoped_timer (scope) -DEFINE_CLASS(lock_timer, struct k_itimer *, unlock_timer(_T), __lock_timer(id), timer_t id); +DEFINE_CLASS(lock_timer, struct k_itimer *, unlock_timer(_T), lock_timer(id), timer_t id);DEFINE_CLASS_IS_COND_GUARD (lock_timer);static struct timer_hash_bucket *hash_bucket (struct signal_struct *sig,unsigned int nr)
@@ -600,7 +593,7 @@ COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock, }#endif -static struct k_itimer *__lock_timer (timer_t timer_id) +static struct k_itimer *lock_timer (timer_t timer_id) {struct k_itimer *timr;
lib/dec_and_lock.c +4 -4
@@ -18,7 +18,7 @@* because the spin-lock and the decrement must be * "atomic". */ -int _atomic_dec_and_lock (atomic_t *atomic,spinlock_t *lock) +int atomic_dec_and_lock (atomic_t *atomic,spinlock_t *lock) {/* Subtract 1 from counter unless that drops it to 0 (ie. it was 1) */ if (atomic_add_unless (atomic,-1 ,1 ))
@@ -32,7 +32,7 @@ int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)return 0 ; } -EXPORT_SYMBOL (_atomic_dec_and_lock); +EXPORT_SYMBOL (atomic_dec_and_lock);int _atomic_dec_and_lock_irqsave (atomic_t *atomic,spinlock_t *lock,unsigned long *flags)
@@ -50,7 +50,7 @@ int _atomic_dec_and_lock_irqsave(atomic_t *atomic, spinlock_t *lock, }EXPORT_SYMBOL (_atomic_dec_and_lock_irqsave); -int _atomic_dec_and_raw_lock (atomic_t *atomic,raw_spinlock_t *lock) +int atomic_dec_and_raw_lock (atomic_t *atomic,raw_spinlock_t *lock) {/* Subtract 1 from counter unless that drops it to 0 (ie. it was 1) */ if (atomic_add_unless (atomic,-1 ,1 ))
@@ -63,7 +63,7 @@ int _atomic_dec_and_raw_lock(atomic_t *atomic, raw_spinlock_t *lock)raw_spin_unlock (lock);return 0 ; } -EXPORT_SYMBOL (_atomic_dec_and_raw_lock); +EXPORT_SYMBOL (atomic_dec_and_raw_lock);int _atomic_dec_and_raw_lock_irqsave (atomic_t *atomic,raw_spinlock_t *lock,unsigned long *flags)
lib/lockref.c +0 -1
@@ -105,7 +105,6 @@ EXPORT_SYMBOL(lockref_put_return);* @lockref: pointer to lockref structure * Return: 1 if count updated successfully or 0 if count <= 1 and lock taken */ -#undef lockref_put_or_lockbool lockref_put_or_lock (struct lockref *lockref) { CMPXCHG_LOOP(
mm/memory.c +2 -2
@@ -2210,8 +2210,8 @@ static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)return pmd; } -pte_t *__get_locked_pte (struct mm_struct *mm,unsigned long addr, -spinlock_t **ptl) +pte_t *get_locked_pte (struct mm_struct *mm,unsigned long addr, +spinlock_t **ptl) {pmd_t *pmd =walk_to_pmd (mm, addr);
mm/pgtable-generic.c +9 -10
@@ -280,7 +280,7 @@ static unsigned long pmdp_get_lockless_start(void) { return 0; }static void pmdp_get_lockless_end (unsigned long irqflags) { }#endif -pte_t *___pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp) +pte_t *__pte_offset_map (pmd_t *pmd,unsigned long addr,pmd_t *pmdvalp) {unsigned long irqflags;pmd_t pmdval;
@@ -332,13 +332,12 @@ pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd, }/* -* pte_offset_map_lock(mm, pmd, addr, ptlp), and its internal implementation -* __pte_offset_map_lock() below, is usually called with the pmd pointer for -* addr, reached by walking down the mm's pgd, p4d, pud for addr: either while -* holding mmap_lock or vma lock for read or for write; or in truncate or rmap -* context, while holding file's i_mmap_lock or anon_vma lock for read (or for -* write). In a few cases, it may be used with pmd pointing to a pmd_t already -* copied to or constructed on the stack. +* pte_offset_map_lock(mm, pmd, addr, ptlp) is usually called with the pmd +* pointer for addr, reached by walking down the mm's pgd, p4d, pud for addr: +* either while holding mmap_lock or vma lock for read or for write; or in +* truncate or rmap context, while holding file's i_mmap_lock or anon_vma lock +* for read (or for write). In a few cases, it may be used with pmd pointing to +* a pmd_t already copied to or constructed on the stack. * * When successful, it returns the pte pointer for addr, with its page table * kmapped if necessary (when CONFIG_HIGHPTE), and locked against concurrent
@@ -389,8 +388,8 @@ pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd,* table, and may not use RCU at all: "outsiders" like khugepaged should avoid * pte_offset_map() and co once the vma is detached from mm or mm_users is zero. */ -pte_t *__pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, -unsigned long addr,spinlock_t **ptlp) +pte_t *pte_offset_map_lock (struct mm_struct *mm,pmd_t *pmd, +unsigned long addr,spinlock_t **ptlp) {spinlock_t *ptl;pmd_t pmdval;
tools/include/linux/compiler_types.h +0 -2
@@ -20,7 +20,6 @@# define __releases (x) __attribute__((context(x,1,0)))# define __acquire (x) __context__(x,1)# define __release (x) __context__(x,-1) -# define __cond_lock (x,c) ((c) ? ({ __acquire(x); 1; }) : 0)#else /* __CHECKER__ */ /* context/locking */ # define __must_hold (x)
@@ -28,7 +27,6 @@# define __releases (x)# define __acquire (x) (void)0# define __release (x) (void)0 -# define __cond_lock (x,c) (c)#endif /* __CHECKER__ */ /* Compiler specific macros. */
Marco Elver
maintainerPATCH v5 25/36 compiler-context-analysis: Introduce header suppressions
In reply to Marco ElverWhile we can opt in individual subsystems which add the required annotations, such subsystems inevitably include headers from other subsystems which may not yet have the right annotations, which then result in false positive warnings.
Making compatible by adding annotations across all common headers currently requires an excessive number of __no_context_analysis annotations, or carefully analyzing non-trivial cases to add the correct annotations. While this is desirable long-term, providing an incremental path causes less churn and headaches for maintainers not yet interested in dealing with such warnings.
Rather than clutter headers unnecessary and mandate all subsystem maintainers to keep their headers working with context analysis, suppress all -Wthread-safety warnings in headers. Explicitly opt in headers with context-enabled primitives.
With this in place, we can start enabling the analysis on more complex subsystems in subsequent changes.
---
v4:
* Rename capability -> context analysis.
--- scripts/Makefile.context-analysis | 4 +++ scripts/context-analysis-suppression.txt | 32 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 scripts/context-analysis-suppression.txt
scripts/Makefile.context-analysis +4 -0
@@ -4,4 +4,8 @@ context-analysis-cflags := -DWARN_CONTEXT_ANALYSIS \ -fexperimental-late-parse-attributes -Wthread-safety \ -Wthread-safety-pointer -Wthread-safety-beta +ifndef CONFIG_WARN_CONTEXT_ANALYSIS_ALL +context-analysis-cflags += --warning-suppression-mappings=$(srctree)/scripts/context-analysis-suppression.txt +endif + export CFLAGS_CONTEXT_ANALYSIS := $(context-analysis-cflags)
scripts/context-analysis-suppression.txt new file +32 -0
@@ -0,0 +1,32 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# The suppressions file should only match common paths such as header files. +# For individual subsytems use Makefile directive CONTEXT_ANALYSIS := [yn]. +# +# The suppressions are ignored when CONFIG_WARN_CONTEXT_ANALYSIS_ALL is +# selected. + +[thread-safety] +src:*arch/*/include/* +src:*include/acpi/* +src:*include/asm-generic/* +src:*include/linux/* +src:*include/net/* + +# Opt-in headers: +src:*include/linux/bit_spinlock.h=emit +src:*include/linux/cleanup.h=emit +src:*include/linux/kref.h=emit +src:*include/linux/list*.h=emit +src:*include/linux/local_lock*.h=emit +src:*include/linux/lockdep.h=emit +src:*include/linux/mutex*.h=emit +src:*include/linux/rcupdate.h=emit +src:*include/linux/refcount.h=emit +src:*include/linux/rhashtable.h=emit +src:*include/linux/rwlock*.h=emit +src:*include/linux/rwsem.h=emit +src:*include/linux/seqlock*.h=emit +src:*include/linux/spinlock*.h=emit +src:*include/linux/srcu*.h=emit +src:*include/linux/ww_mutex.h=emit
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] compiler-context-analysis: Introduce header suppressions
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: c237f1ceeef56fa101c2b599a00307b3d690801a Gitweb: https://git.kernel.org/tip/c237f1ceeef56fa101c2b599a00307b3d690801a Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:14 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:33 +01:00
compiler-context-analysis: Introduce header suppressions
While we can opt in individual subsystems which add the required annotations, such subsystems inevitably include headers from other subsystems which may not yet have the right annotations, which then result in false positive warnings.
Making compatible by adding annotations across all common headers currently requires an excessive number of __no_context_analysis annotations, or carefully analyzing non-trivial cases to add the correct annotations. While this is desirable long-term, providing an incremental path causes less churn and headaches for maintainers not yet interested in dealing with such warnings.
Rather than clutter headers unnecessary and mandate all subsystem maintainers to keep their headers working with context analysis, suppress all -Wthread-safety warnings in headers. Explicitly opt in headers with context-enabled primitives.
With this in place, we can start enabling the analysis on more complex subsystems in subsequent changes.
--- scripts/Makefile.context-analysis | 4 +++- scripts/context-analysis-suppression.txt | 32 +++++++++++++++++++++++- 2 files changed, 36 insertions(+) create mode 100644 scripts/context-analysis-suppression.txt
scripts/Makefile.context-analysis +4 -0
@@ -4,4 +4,8 @@ context-analysis-cflags := -DWARN_CONTEXT_ANALYSIS \ -fexperimental-late-parse-attributes -Wthread-safety \ -Wthread-safety-pointer -Wthread-safety-beta +ifndef CONFIG_WARN_CONTEXT_ANALYSIS_ALL +context-analysis-cflags += --warning-suppression-mappings=$(srctree)/scripts/context-analysis-suppression.txt +endif + export CFLAGS_CONTEXT_ANALYSIS := $(context-analysis-cflags)
scripts/context-analysis-suppression.txt new file +32 -0
@@ -0,0 +1,32 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# The suppressions file should only match common paths such as header files. +# For individual subsytems use Makefile directive CONTEXT_ANALYSIS := [yn]. +# +# The suppressions are ignored when CONFIG_WARN_CONTEXT_ANALYSIS_ALL is +# selected. + +[thread-safety] +src:*arch/*/include/* +src:*include/acpi/* +src:*include/asm-generic/* +src:*include/linux/* +src:*include/net/* + +# Opt-in headers: +src:*include/linux/bit_spinlock.h=emit +src:*include/linux/cleanup.h=emit +src:*include/linux/kref.h=emit +src:*include/linux/list*.h=emit +src:*include/linux/local_lock*.h=emit +src:*include/linux/lockdep.h=emit +src:*include/linux/mutex*.h=emit +src:*include/linux/rcupdate.h=emit +src:*include/linux/refcount.h=emit +src:*include/linux/rhashtable.h=emit +src:*include/linux/rwlock*.h=emit +src:*include/linux/rwsem.h=emit +src:*include/linux/seqlock*.h=emit +src:*include/linux/spinlock*.h=emit +src:*include/linux/srcu*.h=emit +src:*include/linux/ww_mutex.h=emit
Marco Elver
maintainerPATCH v5 26/36 compiler: Let data_race() imply disabled context analysis
In reply to Marco ElverMany patterns that involve data-racy accesses often deliberately ignore normal synchronization rules to avoid taking a lock.
If we have a lock-guarded variable on which we do a lock-less data-racy access, rather than having to write context_unsafe(data_race(..)), simply make the data_race(..) macro imply context-unsafety. The data_race() macro already denotes the intent that something subtly unsafe is about to happen, so it should be clear enough as-is.
---
v4:
* Rename capability -> context analysis.
v2:
* New patch.
--- include/linux/compiler.h | 2 ++ lib/test_context-analysis.c | 2 ++ 2 files changed, 4 insertions(+)
include/linux/compiler.h +2 -0
@@ -190,7 +190,9 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val,#define data_race (expr) \ ({ \ __kcsan_disable_current(); \ + disable_context_analysis(); \ auto __v = (expr); \ + enable_context_analysis(); \ __kcsan_enable_current(); \ __v; \ })
lib/test_context-analysis.c +2 -0
@@ -92,6 +92,8 @@ static void __used test_raw_spinlock_trylock_extra(struct test_raw_spinlock_data {unsigned long flags; +data_race (d->counter++);/* no warning */ +if (raw_spin_trylock_irq (&d->lock)) { d->counter++;raw_spin_unlock_irq (&d->lock);
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] compiler: Let data_race() imply disabled context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 3635ad878242487fc3e8165d0329aedb118e4608 Gitweb: https://git.kernel.org/tip/3635ad878242487fc3e8165d0329aedb118e4608 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:15 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:34 +01:00
compiler: Let data_race() imply disabled context analysis
Many patterns that involve data-racy accesses often deliberately ignore normal synchronization rules to avoid taking a lock.
If we have a lock-guarded variable on which we do a lock-less data-racy access, rather than having to write context_unsafe(data_race(..)), simply make the data_race(..) macro imply context-unsafety. The data_race() macro already denotes the intent that something subtly unsafe is about to happen, so it should be clear enough as-is.
--- include/linux/compiler.h | 2 ++ lib/test_context-analysis.c | 2 ++ 2 files changed, 4 insertions(+)
include/linux/compiler.h +2 -0
@@ -190,7 +190,9 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val,#define data_race (expr) \ ({ \ __kcsan_disable_current(); \ + disable_context_analysis(); \ auto __v = (expr); \ + enable_context_analysis(); \ __kcsan_enable_current(); \ __v; \ })
lib/test_context-analysis.c +2 -0
@@ -92,6 +92,8 @@ static void __used test_raw_spinlock_trylock_extra(struct test_raw_spinlock_data {unsigned long flags; +data_race (d->counter++);/* no warning */ +if (raw_spin_trylock_irq (&d->lock)) { d->counter++;raw_spin_unlock_irq (&d->lock);
Marco Elver
maintainerPATCH v5 27/36 MAINTAINERS: Add entry for Context Analysis
In reply to Marco ElverAdd entry for all new files added for Clang's context analysis.
---
v4:
* Rename capability -> context analysis.
--- MAINTAINERS | 11 +++++++++++ 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
@@ -6132,6 +6132,17 @@ M: Nelson Escobar <[email protected]> S: Supported F: drivers/infiniband/hw/usnic/ +CLANG CONTEXT ANALYSIS +M: Marco Elver <[email protected]> +R: Bart Van Assche <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/dev-tools/context-analysis.rst +F: include/linux/compiler-context-analysis.h +F: lib/test_context-analysis.c +F: scripts/Makefile.context-analysis +F: scripts/context-analysis-suppression.txt + CLANG CONTROL FLOW INTEGRITY SUPPORT M: Sami Tolvanen <[email protected]> M: Kees Cook <[email protected]>
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] MAINTAINERS: Add entry for Context Analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 48eb4b9a3d5c305f93d3cfd0eddffa305884597f Gitweb: https://git.kernel.org/tip/48eb4b9a3d5c305f93d3cfd0eddffa305884597f Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:16 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:34 +01:00
MAINTAINERS: Add entry for Context Analysis
Add entry for all new files added for Clang's context analysis.
--- MAINTAINERS | 11 +++++++++++ 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
@@ -6132,6 +6132,17 @@ M: Nelson Escobar <[email protected]> S: Supported F: drivers/infiniband/hw/usnic/ +CLANG CONTEXT ANALYSIS +M: Marco Elver <[email protected]> +R: Bart Van Assche <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/dev-tools/context-analysis.rst +F: include/linux/compiler-context-analysis.h +F: lib/test_context-analysis.c +F: scripts/Makefile.context-analysis +F: scripts/context-analysis-suppression.txt + CLANG CONTROL FLOW INTEGRITY SUPPORT M: Sami Tolvanen <[email protected]> M: Kees Cook <[email protected]>
Marco Elver
maintainerPATCH v5 28/36 kfence: Enable context analysis
In reply to Marco ElverEnable context analysis for the KFENCE subsystem.
Notable, kfence_handle_page_fault() required minor restructure, which also fixed a subtle race; arguably that function is more readable now.
---
v4:
* Rename capability -> context analysis.
v2:
* Remove disable/enable_context_analysis() around headers.
* Use __context_unsafe() instead of __no_context_analysis.
--- mm/kfence/Makefile | 2 ++ mm/kfence/core.c | 20 +++++++++++++------- mm/kfence/kfence.h | 14 ++++++++------ mm/kfence/report.c | 4 ++-- 4 files changed, 25 insertions(+), 15 deletions(-)
mm/kfence/Makefile +2 -0
@@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 +CONTEXT_ANALYSIS := y + obj-y := core.o report.o CFLAGS_kfence_test.o := -fno-omit-frame-pointer -fno-optimize-sibling-calls
mm/kfence/core.c +13 -7
@@ -133,8 +133,8 @@ struct kfence_metadata *kfence_metadata __read_mostly;static struct kfence_metadata *kfence_metadata_init__read_mostly ;/* Freelist with available objects. */ -static struct list_head kfence_freelist =LIST_HEAD_INIT (kfence_freelist); -static DEFINE_RAW_SPINLOCK (kfence_freelist_lock);/* Lock protecting freelist. */ +DEFINE_RAW_SPINLOCK (kfence_freelist_lock);/* Lock protecting freelist. */ +static struct list_head kfence_freelist __guarded_by(&kfence_freelist_lock) = LIST_HEAD_INIT(kfence_freelist);/* * The static key to set up a KFENCE allocation; or if static keys are not used
@@ -254,6 +254,7 @@ static bool kfence_unprotect(unsigned long addr) }static inline unsigned long metadata_to_pageaddr (const struct kfence_metadata *meta) + __must_hold(&meta->lock) {unsigned long offset = (meta - kfence_metadata +1 ) *PAGE_SIZE *2 ;unsigned long pageaddr = (unsigned long )&__kfence_pool[offset];
@@ -289,6 +290,7 @@ static inline bool kfence_obj_allocated(const struct kfence_metadata *meta) static noinline voidmetadata_update_state (struct kfence_metadata *meta,enum kfence_object_state next,unsigned long *stack_entries,size_t num_stack_entries) + __must_hold(&meta->lock) {struct kfence_track *track = next ==KFENCE_OBJECT_ALLOCATED ? &meta->alloc_track : &meta->free_track;
@@ -486,7 +488,7 @@ static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t galloc_covered_add (alloc_stack_hash,1 );/* Set required slab fields. */ - slab =virt_to_slab ((void *)meta->addr); + slab =virt_to_slab (addr); slab->slab_cache = cache; slab->objects =1 ;
@@ -515,6 +517,7 @@ static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t gstatic void kfence_guarded_free (void *addr,struct kfence_metadata *meta,bool zombie) {struct kcsan_scoped_access assert_page_exclusive; +u32 alloc_stack_hash;unsigned long flags;bool init;
@@ -547,9 +550,10 @@ static void kfence_guarded_free(void *addr, struct kfence_metadata *meta, bool z/* Mark the object as freed. */ metadata_update_state (meta,KFENCE_OBJECT_FREED ,NULL ,0 ); init =slab_want_init_on_free (meta->cache); + alloc_stack_hash = meta->alloc_stack_hash;raw_spin_unlock_irqrestore (&meta->lock, flags); -alloc_covered_add (meta->alloc_stack_hash,-1 ); +alloc_covered_add (alloc_stack_hash,-1 );/* Check canary bytes for memory corruption. */ check_canary (meta);
@@ -594,6 +598,7 @@ static void rcu_guarded_free(struct rcu_head *h)* which partial initialization succeeded. */ static unsigned long kfence_init_pool (void ) +__context_unsafe (/* constructor */ ) {unsigned long addr, start_pfn;int i;
@@ -1220,6 +1225,7 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs {const int page_index = (addr - (unsigned long )__kfence_pool) /PAGE_SIZE ;struct kfence_metadata *to_report =NULL ; +unsigned long unprotected_page =0 ;enum kfence_error_type error_type;unsigned long flags;
@@ -1253,9 +1259,8 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regsif (!to_report) goto out; -raw_spin_lock_irqsave (&to_report->lock, flags); - to_report->unprotected_page = addr; error_type =KFENCE_ERROR_OOB ; + unprotected_page = addr;/* * If the object was freed before we took the look we can still
@@ -1267,7 +1272,6 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regsif (!to_report) goto out; -raw_spin_lock_irqsave (&to_report->lock, flags); error_type =KFENCE_ERROR_UAF ;/* * We may race with __kfence_alloc(), and it is possible that a
@@ -1279,6 +1283,8 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs out:if (to_report) { +raw_spin_lock_irqsave (&to_report->lock, flags); + to_report->unprotected_page = unprotected_page;kfence_report_error (addr, is_write, regs, to_report, error_type);raw_spin_unlock_irqrestore (&to_report->lock, flags); }else {
mm/kfence/kfence.h +8 -6
@@ -34,6 +34,8 @@/* Maximum stack depth for reports. */ #define KFENCE_STACK_DEPTH 64 +extern raw_spinlock_t kfence_freelist_lock; +/* KFENCE object states. */ enum kfence_object_state {KFENCE_OBJECT_UNUSED ,/* Object is unused. */
@@ -53,7 +55,7 @@ struct kfence_track {/* KFENCE metadata per guarded allocation. */ struct kfence_metadata { -struct list_head list;/* Freelist node; access under kfence_freelist_lock. */ + struct list_head list __guarded_by(&kfence_freelist_lock); /* Freelist node. */struct rcu_head rcu_head;/* For delayed freeing. */ /*
@@ -91,13 +93,13 @@ struct kfence_metadata {* In case of an invalid access, the page that was unprotected; we * optimistically only store one address. */ -unsigned long unprotected_page; + unsigned long unprotected_page __guarded_by(&lock);/* Allocation and free stack information. */ -struct kfence_track alloc_track; -struct kfence_track free_track; + struct kfence_track alloc_track __guarded_by(&lock); + struct kfence_track free_track __guarded_by(&lock);/* For updating alloc_covered on frees. */ -u32 alloc_stack_hash; + u32 alloc_stack_hash __guarded_by(&lock);#ifdef CONFIG_MEMCG struct slabobj_ext obj_exts;#endif
@@ -141,6 +143,6 @@ enum kfence_error_type {void kfence_report_error (unsigned long address,bool is_write,struct pt_regs *regs,const struct kfence_metadata *meta,enum kfence_error_type type); -void kfence_print_object (struct seq_file *seq,const struct kfence_metadata *meta); +void kfence_print_object(struct seq_file *seq, const struct kfence_metadata *meta) __must_hold(&meta->lock);#endif /* MM_KFENCE_KFENCE_H */
mm/kfence/report.c +2 -2
@@ -106,6 +106,7 @@ static int get_stack_skipnr(const unsigned long stack_entries[], int num_entriesstatic void kfence_print_stack (struct seq_file *seq,const struct kfence_metadata *meta,bool show_alloc) + __must_hold(&meta->lock) {const struct kfence_track *track = show_alloc ? &meta->alloc_track : &meta->free_track;u64 ts_sec = track->ts_nsec;
@@ -207,8 +208,6 @@ void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *rif (WARN_ON (type !=KFENCE_ERROR_INVALID && !meta))return ; -if (meta) -lockdep_assert_held (&meta->lock);/* * Because we may generate reports in printk-unfriendly parts of the * kernel, such as scheduler code, the use of printk() could deadlock.
@@ -263,6 +262,7 @@ void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *rstack_trace_print (stack_entries + skipnr, num_stack_entries - skipnr,0 );if (meta) { +lockdep_assert_held (&meta->lock);pr_err ("\n" );kfence_print_object (NULL , meta); }
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] kfence: Enable context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 0f5d764862aa7f50d77b8ea2b4f75a48a630487a Gitweb: https://git.kernel.org/tip/0f5d764862aa7f50d77b8ea2b4f75a48a630487a Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:17 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:34 +01:00
kfence: Enable context analysis
Enable context analysis for the KFENCE subsystem.
Notable, kfence_handle_page_fault() required minor restructure, which also fixed a subtle race; arguably that function is more readable now.
--- mm/kfence/Makefile | 2 ++ mm/kfence/core.c | 20 +++++++++++++------- mm/kfence/kfence.h | 14 ++++++++------ mm/kfence/report.c | 4 ++-- 4 files changed, 25 insertions(+), 15 deletions(-)
mm/kfence/Makefile +2 -0
@@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 +CONTEXT_ANALYSIS := y + obj-y := core.o report.o CFLAGS_kfence_test.o := -fno-omit-frame-pointer -fno-optimize-sibling-calls
mm/kfence/core.c +13 -7
@@ -133,8 +133,8 @@ struct kfence_metadata *kfence_metadata __read_mostly;static struct kfence_metadata *kfence_metadata_init__read_mostly ;/* Freelist with available objects. */ -static struct list_head kfence_freelist =LIST_HEAD_INIT (kfence_freelist); -static DEFINE_RAW_SPINLOCK (kfence_freelist_lock);/* Lock protecting freelist. */ +DEFINE_RAW_SPINLOCK (kfence_freelist_lock);/* Lock protecting freelist. */ +static struct list_head kfence_freelist __guarded_by(&kfence_freelist_lock) = LIST_HEAD_INIT(kfence_freelist);/* * The static key to set up a KFENCE allocation; or if static keys are not used
@@ -254,6 +254,7 @@ static bool kfence_unprotect(unsigned long addr) }static inline unsigned long metadata_to_pageaddr (const struct kfence_metadata *meta) + __must_hold(&meta->lock) {unsigned long offset = (meta - kfence_metadata +1 ) *PAGE_SIZE *2 ;unsigned long pageaddr = (unsigned long )&__kfence_pool[offset];
@@ -289,6 +290,7 @@ static inline bool kfence_obj_allocated(const struct kfence_metadata *meta) static noinline voidmetadata_update_state (struct kfence_metadata *meta,enum kfence_object_state next,unsigned long *stack_entries,size_t num_stack_entries) + __must_hold(&meta->lock) {struct kfence_track *track = next ==KFENCE_OBJECT_ALLOCATED ? &meta->alloc_track : &meta->free_track;
@@ -486,7 +488,7 @@ static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t galloc_covered_add (alloc_stack_hash,1 );/* Set required slab fields. */ - slab =virt_to_slab ((void *)meta->addr); + slab =virt_to_slab (addr); slab->slab_cache = cache; slab->objects =1 ;
@@ -515,6 +517,7 @@ static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t gstatic void kfence_guarded_free (void *addr,struct kfence_metadata *meta,bool zombie) {struct kcsan_scoped_access assert_page_exclusive; +u32 alloc_stack_hash;unsigned long flags;bool init;
@@ -547,9 +550,10 @@ static void kfence_guarded_free(void *addr, struct kfence_metadata *meta, bool z/* Mark the object as freed. */ metadata_update_state (meta,KFENCE_OBJECT_FREED ,NULL ,0 ); init =slab_want_init_on_free (meta->cache); + alloc_stack_hash = meta->alloc_stack_hash;raw_spin_unlock_irqrestore (&meta->lock, flags); -alloc_covered_add (meta->alloc_stack_hash,-1 ); +alloc_covered_add (alloc_stack_hash,-1 );/* Check canary bytes for memory corruption. */ check_canary (meta);
@@ -594,6 +598,7 @@ static void rcu_guarded_free(struct rcu_head *h)* which partial initialization succeeded. */ static unsigned long kfence_init_pool (void ) +__context_unsafe (/* constructor */ ) {unsigned long addr, start_pfn;int i;
@@ -1220,6 +1225,7 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs {const int page_index = (addr - (unsigned long )__kfence_pool) /PAGE_SIZE ;struct kfence_metadata *to_report =NULL ; +unsigned long unprotected_page =0 ;enum kfence_error_type error_type;unsigned long flags;
@@ -1253,9 +1259,8 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regsif (!to_report) goto out; -raw_spin_lock_irqsave (&to_report->lock, flags); - to_report->unprotected_page = addr; error_type =KFENCE_ERROR_OOB ; + unprotected_page = addr;/* * If the object was freed before we took the look we can still
@@ -1267,7 +1272,6 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regsif (!to_report) goto out; -raw_spin_lock_irqsave (&to_report->lock, flags); error_type =KFENCE_ERROR_UAF ;/* * We may race with __kfence_alloc(), and it is possible that a
@@ -1279,6 +1283,8 @@ bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs out:if (to_report) { +raw_spin_lock_irqsave (&to_report->lock, flags); + to_report->unprotected_page = unprotected_page;kfence_report_error (addr, is_write, regs, to_report, error_type);raw_spin_unlock_irqrestore (&to_report->lock, flags); }else {
mm/kfence/kfence.h +8 -6
@@ -34,6 +34,8 @@/* Maximum stack depth for reports. */ #define KFENCE_STACK_DEPTH 64 +extern raw_spinlock_t kfence_freelist_lock; +/* KFENCE object states. */ enum kfence_object_state {KFENCE_OBJECT_UNUSED ,/* Object is unused. */
@@ -53,7 +55,7 @@ struct kfence_track {/* KFENCE metadata per guarded allocation. */ struct kfence_metadata { -struct list_head list;/* Freelist node; access under kfence_freelist_lock. */ + struct list_head list __guarded_by(&kfence_freelist_lock); /* Freelist node. */struct rcu_head rcu_head;/* For delayed freeing. */ /*
@@ -91,13 +93,13 @@ struct kfence_metadata {* In case of an invalid access, the page that was unprotected; we * optimistically only store one address. */ -unsigned long unprotected_page; + unsigned long unprotected_page __guarded_by(&lock);/* Allocation and free stack information. */ -struct kfence_track alloc_track; -struct kfence_track free_track; + struct kfence_track alloc_track __guarded_by(&lock); + struct kfence_track free_track __guarded_by(&lock);/* For updating alloc_covered on frees. */ -u32 alloc_stack_hash; + u32 alloc_stack_hash __guarded_by(&lock);#ifdef CONFIG_MEMCG struct slabobj_ext obj_exts;#endif
@@ -141,6 +143,6 @@ enum kfence_error_type {void kfence_report_error (unsigned long address,bool is_write,struct pt_regs *regs,const struct kfence_metadata *meta,enum kfence_error_type type); -void kfence_print_object (struct seq_file *seq,const struct kfence_metadata *meta); +void kfence_print_object(struct seq_file *seq, const struct kfence_metadata *meta) __must_hold(&meta->lock);#endif /* MM_KFENCE_KFENCE_H */
mm/kfence/report.c +2 -2
@@ -106,6 +106,7 @@ found:static void kfence_print_stack (struct seq_file *seq,const struct kfence_metadata *meta,bool show_alloc) + __must_hold(&meta->lock) {const struct kfence_track *track = show_alloc ? &meta->alloc_track : &meta->free_track;u64 ts_sec = track->ts_nsec;
@@ -207,8 +208,6 @@ void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *rif (WARN_ON (type !=KFENCE_ERROR_INVALID && !meta))return ; -if (meta) -lockdep_assert_held (&meta->lock);/* * Because we may generate reports in printk-unfriendly parts of the * kernel, such as scheduler code, the use of printk() could deadlock.
@@ -263,6 +262,7 @@ void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *rstack_trace_print (stack_entries + skipnr, num_stack_entries - skipnr,0 );if (meta) { +lockdep_assert_held (&meta->lock);pr_err ("\n" );kfence_print_object (NULL , meta); }
Marco Elver
maintainerPATCH v5 29/36 kcov: Enable context analysis
In reply to Marco ElverEnable context analysis for the KCOV subsystem.
---
v4:
* Fix new temporary variable type.
* Rename capability -> context analysis.
v2:
* Remove disable/enable_context_analysis() around headers.
--- kernel/Makefile | 2 ++ kernel/kcov.c | 36 +++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-)
kernel/Makefile +2 -0
@@ -43,6 +43,8 @@ KASAN_SANITIZE_kcov.o := n KCSAN_SANITIZE_kcov.o := n UBSAN_SANITIZE_kcov.o := n KMSAN_SANITIZE_kcov.o := n + +CONTEXT_ANALYSIS_kcov.o := y CFLAGS_kcov.o := $(call cc-option, -fno-conserve-stack) -fno-stack-protector obj-y += sched/
kernel/kcov.c +25 -11
@@ -55,13 +55,13 @@ struct kcov {refcount_t refcount;/* The lock protects mode, size, area and t. */ spinlock_t lock; -enum kcov_mode mode; + enum kcov_mode mode __guarded_by(&lock);/* Size of arena (in long's). */ -unsigned int size; + unsigned int size __guarded_by(&lock);/* Coverage buffer shared with user space. */ -void *area; + void *area __guarded_by(&lock);/* Task for which we collect coverage, or NULL. */ -struct task_struct *t; + struct task_struct *t __guarded_by(&lock);/* Collecting coverage from remote (background) threads. */ bool remote;/* Size of remote area (in long's). */
@@ -391,6 +391,7 @@ void kcov_task_init(struct task_struct *t) }static void kcov_reset (struct kcov *kcov) + __must_hold(&kcov->lock) { kcov->t =NULL ; kcov->mode =KCOV_MODE_INIT ;
@@ -400,6 +401,7 @@ static void kcov_reset(struct kcov *kcov) }static void kcov_remote_reset (struct kcov *kcov) + __must_hold(&kcov->lock) {int bkt;struct kcov_remote *remote;
@@ -419,6 +421,7 @@ static void kcov_remote_reset(struct kcov *kcov) }static void kcov_disable (struct task_struct *t,struct kcov *kcov) + __must_hold(&kcov->lock) {kcov_task_reset (t);if (kcov->remote)
@@ -435,8 +438,11 @@ static void kcov_get(struct kcov *kcov)static void kcov_put (struct kcov *kcov) {if (refcount_dec_and_test (&kcov->refcount)) { -kcov_remote_reset (kcov); -vfree (kcov->area); +/* Context-safety: no references left, object being destroyed. */ +context_unsafe ( + kcov_remote_reset(kcov); +vfree (kcov->area); + );kfree (kcov); } }
@@ -491,6 +497,7 @@ static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)unsigned long size, off;struct page *page;unsigned long flags; +void *area;spin_lock_irqsave (&kcov->lock, flags); size = kcov->size *sizeof (unsigned long );
@@ -499,10 +506,11 @@ static int kcov_mmap(struct file *filep, struct vm_area_struct *vma) res = -EINVAL ; goto exit; } + area = kcov->area;spin_unlock_irqrestore (&kcov->lock, flags);vm_flags_set (vma,VM_DONTEXPAND );for (off =0 ; off < size; off +=PAGE_SIZE ) { - page =vmalloc_to_page (kcov->area + off); + page =vmalloc_to_page (area + off); res =vm_insert_page (vma, vma->vm_start + off, page);if (res) {pr_warn_once ("kcov: vm_insert_page() failed\n" );
@@ -522,10 +530,10 @@ static int kcov_open(struct inode *inode, struct file *filep) kcov =kzalloc (sizeof (*kcov),GFP_KERNEL );if (!kcov)return -ENOMEM ; +spin_lock_init (&kcov->lock); kcov->mode =KCOV_MODE_DISABLED ; kcov->sequence =1 ;refcount_set (&kcov->refcount,1 ); -spin_lock_init (&kcov->lock); filep->private_data = kcov;return nonseekable_open (inode, filep); }
@@ -556,6 +564,7 @@ static int kcov_get_mode(unsigned long arg)* vmalloc fault handling path is instrumented. */ static void kcov_fault_in_area (struct kcov *kcov) + __must_hold(&kcov->lock) {unsigned long stride =PAGE_SIZE /sizeof (unsigned long );unsigned long *area = kcov->area;
@@ -584,6 +593,7 @@ static inline bool kcov_check_handle(u64 handle, bool common_valid,static int kcov_ioctl_locked (struct kcov *kcov,unsigned int cmd,unsigned long arg) + __must_hold(&kcov->lock) {struct task_struct *t;unsigned long flags, unused;
@@ -814,6 +824,7 @@ static inline bool kcov_mode_enabled(unsigned int mode) }static void kcov_remote_softirq_start (struct task_struct *t) + __must_hold(&kcov_percpu_data.lock) {struct kcov_percpu_data *data =this_cpu_ptr (&kcov_percpu_data);unsigned int mode;
@@ -831,6 +842,7 @@ static void kcov_remote_softirq_start(struct task_struct *t) }static void kcov_remote_softirq_stop (struct task_struct *t) + __must_hold(&kcov_percpu_data.lock) {struct kcov_percpu_data *data =this_cpu_ptr (&kcov_percpu_data);
@@ -896,10 +908,12 @@ void kcov_remote_start(u64 handle)/* Put in kcov_remote_stop(). */ kcov_get (kcov);/* -* Read kcov fields before unlock to prevent races with -* KCOV_DISABLE / kcov_remote_reset(). +* Read kcov fields before unlocking kcov_remote_lock to prevent races +* with KCOV_DISABLE and kcov_remote_reset(); cannot acquire kcov->lock +* here, because it might lead to deadlock given kcov_remote_lock is +* acquired _after_ kcov->lock elsewhere. */ - mode = kcov->mode; + mode =context_unsafe (kcov->mode); sequence = kcov->sequence;if (in_task ()) { size = kcov->remote_size;
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] kcov: Enable context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 6556fde265a7bd408ad8ff15ec08970f99f6201c Gitweb: https://git.kernel.org/tip/6556fde265a7bd408ad8ff15ec08970f99f6201c Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:18 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:34 +01:00
kcov: Enable context analysis
Enable context analysis for the KCOV subsystem.
--- kernel/Makefile | 2 ++ kernel/kcov.c | 36 +++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-)
kernel/Makefile +2 -0
@@ -43,6 +43,8 @@ KASAN_SANITIZE_kcov.o := n KCSAN_SANITIZE_kcov.o := n UBSAN_SANITIZE_kcov.o := n KMSAN_SANITIZE_kcov.o := n + +CONTEXT_ANALYSIS_kcov.o := y CFLAGS_kcov.o := $(call cc-option, -fno-conserve-stack) -fno-stack-protector obj-y += sched/
kernel/kcov.c +25 -11
@@ -55,13 +55,13 @@ struct kcov {refcount_t refcount;/* The lock protects mode, size, area and t. */ spinlock_t lock; -enum kcov_mode mode; + enum kcov_mode mode __guarded_by(&lock);/* Size of arena (in long's). */ -unsigned int size; + unsigned int size __guarded_by(&lock);/* Coverage buffer shared with user space. */ -void *area; + void *area __guarded_by(&lock);/* Task for which we collect coverage, or NULL. */ -struct task_struct *t; + struct task_struct *t __guarded_by(&lock);/* Collecting coverage from remote (background) threads. */ bool remote;/* Size of remote area (in long's). */
@@ -391,6 +391,7 @@ void kcov_task_init(struct task_struct *t) }static void kcov_reset (struct kcov *kcov) + __must_hold(&kcov->lock) { kcov->t =NULL ; kcov->mode =KCOV_MODE_INIT ;
@@ -400,6 +401,7 @@ static void kcov_reset(struct kcov *kcov) }static void kcov_remote_reset (struct kcov *kcov) + __must_hold(&kcov->lock) {int bkt;struct kcov_remote *remote;
@@ -419,6 +421,7 @@ static void kcov_remote_reset(struct kcov *kcov) }static void kcov_disable (struct task_struct *t,struct kcov *kcov) + __must_hold(&kcov->lock) {kcov_task_reset (t);if (kcov->remote)
@@ -435,8 +438,11 @@ static void kcov_get(struct kcov *kcov)static void kcov_put (struct kcov *kcov) {if (refcount_dec_and_test (&kcov->refcount)) { -kcov_remote_reset (kcov); -vfree (kcov->area); +/* Context-safety: no references left, object being destroyed. */ +context_unsafe ( + kcov_remote_reset(kcov); +vfree (kcov->area); + );kfree (kcov); } }
@@ -491,6 +497,7 @@ static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)unsigned long size, off;struct page *page;unsigned long flags; +void *area;spin_lock_irqsave (&kcov->lock, flags); size = kcov->size *sizeof (unsigned long );
@@ -499,10 +506,11 @@ static int kcov_mmap(struct file *filep, struct vm_area_struct *vma) res = -EINVAL ; goto exit; } + area = kcov->area;spin_unlock_irqrestore (&kcov->lock, flags);vm_flags_set (vma,VM_DONTEXPAND );for (off =0 ; off < size; off +=PAGE_SIZE ) { - page =vmalloc_to_page (kcov->area + off); + page =vmalloc_to_page (area + off); res =vm_insert_page (vma, vma->vm_start + off, page);if (res) {pr_warn_once ("kcov: vm_insert_page() failed\n" );
@@ -522,10 +530,10 @@ static int kcov_open(struct inode *inode, struct file *filep) kcov =kzalloc (sizeof (*kcov),GFP_KERNEL );if (!kcov)return -ENOMEM ; +spin_lock_init (&kcov->lock); kcov->mode =KCOV_MODE_DISABLED ; kcov->sequence =1 ;refcount_set (&kcov->refcount,1 ); -spin_lock_init (&kcov->lock); filep->private_data = kcov;return nonseekable_open (inode, filep); }
@@ -556,6 +564,7 @@ static int kcov_get_mode(unsigned long arg)* vmalloc fault handling path is instrumented. */ static void kcov_fault_in_area (struct kcov *kcov) + __must_hold(&kcov->lock) {unsigned long stride =PAGE_SIZE /sizeof (unsigned long );unsigned long *area = kcov->area;
@@ -584,6 +593,7 @@ static inline bool kcov_check_handle(u64 handle, bool common_valid,static int kcov_ioctl_locked (struct kcov *kcov,unsigned int cmd,unsigned long arg) + __must_hold(&kcov->lock) {struct task_struct *t;unsigned long flags, unused;
@@ -814,6 +824,7 @@ static inline bool kcov_mode_enabled(unsigned int mode) }static void kcov_remote_softirq_start (struct task_struct *t) + __must_hold(&kcov_percpu_data.lock) {struct kcov_percpu_data *data =this_cpu_ptr (&kcov_percpu_data);unsigned int mode;
@@ -831,6 +842,7 @@ static void kcov_remote_softirq_start(struct task_struct *t) }static void kcov_remote_softirq_stop (struct task_struct *t) + __must_hold(&kcov_percpu_data.lock) {struct kcov_percpu_data *data =this_cpu_ptr (&kcov_percpu_data);
@@ -896,10 +908,12 @@ void kcov_remote_start(u64 handle)/* Put in kcov_remote_stop(). */ kcov_get (kcov);/* -* Read kcov fields before unlock to prevent races with -* KCOV_DISABLE / kcov_remote_reset(). +* Read kcov fields before unlocking kcov_remote_lock to prevent races +* with KCOV_DISABLE and kcov_remote_reset(); cannot acquire kcov->lock +* here, because it might lead to deadlock given kcov_remote_lock is +* acquired _after_ kcov->lock elsewhere. */ - mode = kcov->mode; + mode =context_unsafe (kcov->mode); sequence = kcov->sequence;if (in_task ()) { size = kcov->remote_size;
Marco Elver
maintainerPATCH v5 30/36 kcsan: Enable context analysis
In reply to Marco ElverEnable context analysis for the KCSAN subsystem.
---
v4:
* Rename capability -> context analysis.
v3:
* New patch.
--- kernel/kcsan/Makefile | 2 ++ kernel/kcsan/report.c | 11 ++++++++--- 2 files changed, 10 insertions(+), 3 deletions(-)
kernel/kcsan/Makefile +2 -0
@@ -1,4 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 +CONTEXT_ANALYSIS := y + KCSAN_SANITIZE := n KCOV_INSTRUMENT := n UBSAN_SANITIZE := n
kernel/kcsan/report.c +8 -3
@@ -116,6 +116,7 @@ static DEFINE_RAW_SPINLOCK(report_lock);* been reported since (now - KCSAN_REPORT_ONCE_IN_MS). */ static bool rate_limit_report (unsigned long frame1,unsigned long frame2) + __must_hold(&report_lock) {struct report_time *use_entry = &report_times[0 ];unsigned long invalid_before;
@@ -366,6 +367,7 @@ static int sym_strcmp(void *addr1, void *addr2)static void print_stack_trace (unsigned long stack_entries[],int num_entries,unsigned long reordered_to) + __must_hold(&report_lock) {stack_trace_print (stack_entries, num_entries,0 );if (reordered_to)
@@ -373,6 +375,7 @@ print_stack_trace(unsigned long stack_entries[], int num_entries, unsigned long }static void print_verbose_info (struct task_struct *task) + __must_hold(&report_lock) {if (!task)return ;
@@ -389,6 +392,7 @@ static void print_report(enum kcsan_value_change value_change,const struct access_info *ai, struct other_info *other_info, u64 old, u64 new, u64 mask) + __must_hold(&report_lock) { unsigned long reordered_to = 0;unsigned long stack_entries[NUM_STACK_ENTRIES ] = {0 };
@@ -496,6 +500,7 @@ static void print_report(enum kcsan_value_change value_change, }static void release_report (unsigned long *flags,struct other_info *other_info) + __releases(&report_lock) {/* * Use size to denote valid/invalid, since KCSAN entirely ignores
@@ -507,13 +512,11 @@ static void release_report(unsigned long *flags, struct other_info *other_info)/* * Sets @other_info->task and awaits consumption of @other_info. -* -* Precondition: report_lock is held. -* Postcondition: report_lock is held. */ static void set_other_info_task_blocking (unsigned long *flags,const struct access_info *ai,struct other_info *other_info) + __must_hold(&report_lock) {/* * We may be instrumenting a code-path where current->state is already
@@ -572,6 +575,7 @@ static void set_other_info_task_blocking(unsigned long *flags,static void prepare_report_producer (unsigned long *flags,const struct access_info *ai,struct other_info *other_info) + __must_not_hold(&report_lock) {raw_spin_lock_irqsave (&report_lock, *flags);
@@ -603,6 +607,7 @@ static void prepare_report_producer(unsigned long *flags,static bool prepare_report_consumer (unsigned long *flags,const struct access_info *ai,struct other_info *other_info) + __cond_acquires(true, &report_lock) {raw_spin_lock_irqsave (&report_lock, *flags);
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] kcsan: Enable context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 0eaa911f890812a7868a44bbfd656636b2c7caf8 Gitweb: https://git.kernel.org/tip/0eaa911f890812a7868a44bbfd656636b2c7caf8 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:19 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:35 +01:00
kcsan: Enable context analysis
Enable context analysis for the KCSAN subsystem.
--- kernel/kcsan/Makefile | 2 ++ kernel/kcsan/report.c | 11 ++++++++--- 2 files changed, 10 insertions(+), 3 deletions(-)
kernel/kcsan/Makefile +2 -0
@@ -1,4 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 +CONTEXT_ANALYSIS := y + KCSAN_SANITIZE := n KCOV_INSTRUMENT := n UBSAN_SANITIZE := n
kernel/kcsan/report.c +8 -3
@@ -116,6 +116,7 @@ static DEFINE_RAW_SPINLOCK(report_lock);* been reported since (now - KCSAN_REPORT_ONCE_IN_MS). */ static bool rate_limit_report (unsigned long frame1,unsigned long frame2) + __must_hold(&report_lock) {struct report_time *use_entry = &report_times[0 ];unsigned long invalid_before;
@@ -366,6 +367,7 @@ static int sym_strcmp(void *addr1, void *addr2)static void print_stack_trace (unsigned long stack_entries[],int num_entries,unsigned long reordered_to) + __must_hold(&report_lock) {stack_trace_print (stack_entries, num_entries,0 );if (reordered_to)
@@ -373,6 +375,7 @@ print_stack_trace(unsigned long stack_entries[], int num_entries, unsigned long }static void print_verbose_info (struct task_struct *task) + __must_hold(&report_lock) {if (!task)return ;
@@ -389,6 +392,7 @@ static void print_report(enum kcsan_value_change value_change,const struct access_info *ai, struct other_info *other_info, u64 old, u64 new, u64 mask) + __must_hold(&report_lock) { unsigned long reordered_to = 0;unsigned long stack_entries[NUM_STACK_ENTRIES ] = {0 };
@@ -496,6 +500,7 @@ static void print_report(enum kcsan_value_change value_change, }static void release_report (unsigned long *flags,struct other_info *other_info) + __releases(&report_lock) {/* * Use size to denote valid/invalid, since KCSAN entirely ignores
@@ -507,13 +512,11 @@ static void release_report(unsigned long *flags, struct other_info *other_info)/* * Sets @other_info->task and awaits consumption of @other_info. -* -* Precondition: report_lock is held. -* Postcondition: report_lock is held. */ static void set_other_info_task_blocking (unsigned long *flags,const struct access_info *ai,struct other_info *other_info) + __must_hold(&report_lock) {/* * We may be instrumenting a code-path where current->state is already
@@ -572,6 +575,7 @@ static void set_other_info_task_blocking(unsigned long *flags,static void prepare_report_producer (unsigned long *flags,const struct access_info *ai,struct other_info *other_info) + __must_not_hold(&report_lock) {raw_spin_lock_irqsave (&report_lock, *flags);
@@ -603,6 +607,7 @@ static void prepare_report_producer(unsigned long *flags,static bool prepare_report_consumer (unsigned long *flags,const struct access_info *ai,struct other_info *other_info) + __cond_acquires(true, &report_lock) {raw_spin_lock_irqsave (&report_lock, *flags);
Marco Elver
maintainerPATCH v5 31/36 stackdepot: Enable context analysis
In reply to Marco ElverEnable context analysis for stackdepot.
---
v4:
* Rename capability -> context analysis.
v2:
* Remove disable/enable_context_analysis() around headers.
--- lib/Makefile | 1 + lib/stackdepot.c | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-)
lib/Makefile +1 -0
@@ -250,6 +250,7 @@ obj-$(CONFIG_POLYNOMIAL) += polynomial.o # Prevent the compiler from calling builtins like memcmp() or bcmp() from this # file. CFLAGS_stackdepot.o += -fno-builtin +CONTEXT_ANALYSIS_stackdepot.o := y obj-$(CONFIG_STACKDEPOT) += stackdepot.o KASAN_SANITIZE_stackdepot.o := n # In particular, instrumenting stackdepot.c with KMSAN will result in infinite
lib/stackdepot.c +14 -6
@@ -61,18 +61,18 @@ static unsigned int stack_bucket_number_order;/* Hash mask for indexing the table. */ static unsigned int stack_hash_mask; +/* The lock must be held when performing pool or freelist modifications. */ +static DEFINE_RAW_SPINLOCK (pool_lock);/* Array of memory regions that store stack records. */ -static void **stack_pools; +static void **stack_pools __pt_guarded_by(&pool_lock);/* Newly allocated pool that is not yet added to stack_pools. */ static void *new_pool;/* Number of pools in stack_pools. */ static int pools_num;/* Offset to the unused space in the currently used pool. */ -static size_t pool_offset =DEPOT_POOL_SIZE ; +static size_t pool_offset __guarded_by(&pool_lock) = DEPOT_POOL_SIZE;/* Freelist of stack records within stack_pools. */ -static LIST_HEAD (free_stacks); -/* The lock must be held when performing pool or freelist modifications. */ -static DEFINE_RAW_SPINLOCK (pool_lock); +static __guarded_by(&pool_lock) LIST_HEAD(free_stacks);/* Statistics counters for debugfs. */ enum depot_counter_id {
@@ -291,6 +291,7 @@ EXPORT_SYMBOL_GPL(stack_depot_init);* Initializes new stack pool, and updates the list of pools. */ static bool depot_init_pool (void **prealloc) + __must_hold(&pool_lock) {lockdep_assert_held (&pool_lock);
@@ -338,6 +339,7 @@ static bool depot_init_pool(void **prealloc)/* Keeps the preallocated memory to be used for a new stack depot pool. */ static void depot_keep_new_pool (void **prealloc) + __must_hold(&pool_lock) {lockdep_assert_held (&pool_lock);
@@ -357,6 +359,7 @@ static void depot_keep_new_pool(void **prealloc)* the current pre-allocation. */ static struct stack_record *depot_pop_free_pool (void **prealloc,size_t size) + __must_hold(&pool_lock) {struct stack_record *stack;void *current_pool;
@@ -391,6 +394,7 @@ static struct stack_record *depot_pop_free_pool(void **prealloc, size_t size)/* Try to find next free usable entry from the freelist. */ static struct stack_record *depot_pop_free (void ) + __must_hold(&pool_lock) {struct stack_record *stack;
@@ -428,6 +432,7 @@ static inline size_t depot_stack_record_size(struct stack_record *s, unsigned in/* Allocates a new stack in a stack depot pool. */ static struct stack_record *depot_alloc_stack (unsigned long *entries,unsigned int nr_entries,u32 hash,depot_flags_t flags,void **prealloc) + __must_hold(&pool_lock) {struct stack_record *stack =NULL ;size_t record_size;
@@ -486,6 +491,7 @@ depot_alloc_stack(unsigned long *entries, unsigned int nr_entries, u32 hash, dep }static struct stack_record *depot_fetch_stack (depot_stack_handle_t handle) + __must_not_hold(&pool_lock) {const int pools_num_cached =READ_ONCE (pools_num);union handle_parts parts = { .handle = handle };
@@ -502,7 +508,8 @@ static struct stack_record *depot_fetch_stack(depot_stack_handle_t handle)return NULL ; } - pool = stack_pools[pool_index]; +/* @pool_index either valid, or user passed in corrupted value. */ + pool =context_unsafe (stack_pools[pool_index]);if (WARN_ON (!pool))return NULL ;
@@ -515,6 +522,7 @@ static struct stack_record *depot_fetch_stack(depot_stack_handle_t handle)/* Links stack into the freelist. */ static void depot_free_stack (struct stack_record *stack) + __must_not_hold(&pool_lock) {unsigned long flags;
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] stackdepot: Enable context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: c3d3023f1cf3de10f2d2f83b0d011fa7cab16cf0 Gitweb: https://git.kernel.org/tip/c3d3023f1cf3de10f2d2f83b0d011fa7cab16cf0 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:20 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:35 +01:00
stackdepot: Enable context analysis
Enable context analysis for stackdepot.
--- lib/Makefile | 1 + lib/stackdepot.c | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-)
lib/Makefile +1 -0
@@ -250,6 +250,7 @@ obj-$(CONFIG_POLYNOMIAL) += polynomial.o # Prevent the compiler from calling builtins like memcmp() or bcmp() from this # file. CFLAGS_stackdepot.o += -fno-builtin +CONTEXT_ANALYSIS_stackdepot.o := y obj-$(CONFIG_STACKDEPOT) += stackdepot.o KASAN_SANITIZE_stackdepot.o := n # In particular, instrumenting stackdepot.c with KMSAN will result in infinite
lib/stackdepot.c +14 -6
@@ -61,18 +61,18 @@ static unsigned int stack_bucket_number_order;/* Hash mask for indexing the table. */ static unsigned int stack_hash_mask; +/* The lock must be held when performing pool or freelist modifications. */ +static DEFINE_RAW_SPINLOCK (pool_lock);/* Array of memory regions that store stack records. */ -static void **stack_pools; +static void **stack_pools __pt_guarded_by(&pool_lock);/* Newly allocated pool that is not yet added to stack_pools. */ static void *new_pool;/* Number of pools in stack_pools. */ static int pools_num;/* Offset to the unused space in the currently used pool. */ -static size_t pool_offset =DEPOT_POOL_SIZE ; +static size_t pool_offset __guarded_by(&pool_lock) = DEPOT_POOL_SIZE;/* Freelist of stack records within stack_pools. */ -static LIST_HEAD (free_stacks); -/* The lock must be held when performing pool or freelist modifications. */ -static DEFINE_RAW_SPINLOCK (pool_lock); +static __guarded_by(&pool_lock) LIST_HEAD(free_stacks);/* Statistics counters for debugfs. */ enum depot_counter_id {
@@ -291,6 +291,7 @@ EXPORT_SYMBOL_GPL(stack_depot_init);* Initializes new stack pool, and updates the list of pools. */ static bool depot_init_pool (void **prealloc) + __must_hold(&pool_lock) {lockdep_assert_held (&pool_lock);
@@ -338,6 +339,7 @@ static bool depot_init_pool(void **prealloc)/* Keeps the preallocated memory to be used for a new stack depot pool. */ static void depot_keep_new_pool (void **prealloc) + __must_hold(&pool_lock) {lockdep_assert_held (&pool_lock);
@@ -357,6 +359,7 @@ static void depot_keep_new_pool(void **prealloc)* the current pre-allocation. */ static struct stack_record *depot_pop_free_pool (void **prealloc,size_t size) + __must_hold(&pool_lock) {struct stack_record *stack;void *current_pool;
@@ -391,6 +394,7 @@ static struct stack_record *depot_pop_free_pool(void **prealloc, size_t size)/* Try to find next free usable entry from the freelist. */ static struct stack_record *depot_pop_free (void ) + __must_hold(&pool_lock) {struct stack_record *stack;
@@ -428,6 +432,7 @@ static inline size_t depot_stack_record_size(struct stack_record *s, unsigned in/* Allocates a new stack in a stack depot pool. */ static struct stack_record *depot_alloc_stack (unsigned long *entries,unsigned int nr_entries,u32 hash,depot_flags_t flags,void **prealloc) + __must_hold(&pool_lock) {struct stack_record *stack =NULL ;size_t record_size;
@@ -486,6 +491,7 @@ depot_alloc_stack(unsigned long *entries, unsigned int nr_entries, u32 hash, dep }static struct stack_record *depot_fetch_stack (depot_stack_handle_t handle) + __must_not_hold(&pool_lock) {const int pools_num_cached =READ_ONCE (pools_num);union handle_parts parts = { .handle = handle };
@@ -502,7 +508,8 @@ static struct stack_record *depot_fetch_stack(depot_stack_handle_t handle)return NULL ; } - pool = stack_pools[pool_index]; +/* @pool_index either valid, or user passed in corrupted value. */ + pool =context_unsafe (stack_pools[pool_index]);if (WARN_ON (!pool))return NULL ;
@@ -515,6 +522,7 @@ static struct stack_record *depot_fetch_stack(depot_stack_handle_t handle)/* Links stack into the freelist. */ static void depot_free_stack (struct stack_record *stack) + __must_not_hold(&pool_lock) {unsigned long flags;
Marco Elver
maintainerPATCH v5 32/36 rhashtable: Enable context analysis
In reply to Marco ElverEnable context analysis for rhashtable, which was used as an initial test as it contains a combination of RCU, mutex, and bit_spinlock usage.
Users of rhashtable now also benefit from annotations on the API, which will now warn if the RCU read lock is not held where required.
---
v5:
* Fix annotations for recently modified/added functions.
v4:
* Rename capability -> context analysis.
v2:
* Remove disable/enable_context_analysis() around headers.
--- include/linux/rhashtable.h | 16 +++++++++++++--- lib/Makefile | 2 ++ lib/rhashtable.c | 5 +++-- 3 files changed, 18 insertions(+), 5 deletions(-)
include/linux/rhashtable.h +13 -3
@@ -245,16 +245,17 @@ void *rhashtable_insert_slow(struct rhashtable *ht, const void *key,void rhashtable_walk_enter (struct rhashtable *ht,struct rhashtable_iter *iter);void rhashtable_walk_exit (struct rhashtable_iter *iter); -int rhashtable_walk_start_check(struct rhashtable_iter *iter) __acquires(RCU); +int rhashtable_walk_start_check(struct rhashtable_iter *iter) __acquires_shared(RCU);static inline void rhashtable_walk_start (struct rhashtable_iter *iter) +__acquires_shared (RCU ) { (void )rhashtable_walk_start_check (iter); }void *rhashtable_walk_next (struct rhashtable_iter *iter);void *rhashtable_walk_peek (struct rhashtable_iter *iter); -void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases(RCU); +void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases_shared(RCU); void rhashtable_free_and_destroy(struct rhashtable *ht, void (*free_fn)(void *ptr, void *arg),
@@ -325,6 +326,7 @@ static inline struct rhash_lock_head __rcu **rht_bucket_insert(static inline unsigned long rht_lock (struct bucket_table *tbl,struct rhash_lock_head __rcu **bkt) +__acquires (__bitlock (0 , bkt)) {unsigned long flags;
@@ -337,6 +339,7 @@ static inline unsigned long rht_lock(struct bucket_table *tbl,static inline unsigned long rht_lock_nested (struct bucket_table *tbl,struct rhash_lock_head __rcu **bucket,unsigned int subclass) +__acquires (__bitlock (0 , bucket)) {unsigned long flags;
@@ -349,6 +352,7 @@ static inline unsigned long rht_lock_nested(struct bucket_table *tbl,static inline void rht_unlock (struct bucket_table *tbl,struct rhash_lock_head __rcu **bkt,unsigned long flags) +__releases (__bitlock (0 , bkt)) {lock_map_release (&tbl->dep_map);bit_spin_unlock (0 , (unsigned long *)bkt);
@@ -424,13 +428,14 @@ static inline void rht_assign_unlock(struct bucket_table *tbl,struct rhash_lock_head __rcu **bkt, struct rhash_head *obj, unsigned long flags) + __releases(__bitlock(0, bkt)) { if (rht_is_a_nulls(obj)) obj =NULL ;lock_map_release (&tbl->dep_map);rcu_assign_pointer (*bkt, (void *)obj);preempt_enable (); -__release (bitlock); +__release (__bitlock (0 , bkt));local_irq_restore (flags); }
@@ -612,6 +617,7 @@ static __always_inline struct rhash_head *__rhashtable_lookup( struct rhashtable *ht, const void *key, const struct rhashtable_params params, const enum rht_lookup_freq freq) + __must_hold_shared(RCU) { struct rhashtable_compare_arg arg = { .ht = ht,
@@ -666,6 +672,7 @@ static __always_inline struct rhash_head *__rhashtable_lookup( static __always_inline void *rhashtable_lookup(struct rhashtable *ht,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (ht, key, params,RHT_LOOKUP_NORMAL );
@@ -676,6 +683,7 @@ static __always_inline void *rhashtable_lookup( static __always_inline void *rhashtable_lookup_likely(struct rhashtable *ht,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (ht, key, params,RHT_LOOKUP_LIKELY );
@@ -727,6 +735,7 @@ static __always_inline void *rhashtable_lookup_fast( static __always_inline struct rhlist_head *rhltable_lookup(struct rhltable *hlt,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (&hlt->ht, key, params,RHT_LOOKUP_NORMAL );
@@ -737,6 +746,7 @@ static __always_inline struct rhlist_head *rhltable_lookup( static __always_inline struct rhlist_head *rhltable_lookup_likely(struct rhltable *hlt,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (&hlt->ht, key, params,RHT_LOOKUP_LIKELY );
lib/Makefile +2 -0
@@ -50,6 +50,8 @@ lib-$(CONFIG_MIN_HEAP) += min_heap.o lib-y += kobject.o klist.o obj-y += lockref.o +CONTEXT_ANALYSIS_rhashtable.o := y + obj-y += bcd.o sort.o parser.o debug_locks.o random32.o \ bust_spinlocks.o kasprintf.o bitmap.o scatterlist.o \ list_sort.o uuid.o iov_iter.o clz_ctz.o \
lib/rhashtable.c +3 -2
@@ -358,6 +358,7 @@ static int rhashtable_rehash_table(struct rhashtable *ht)static int rhashtable_rehash_alloc (struct rhashtable *ht,struct bucket_table *old_tbl,unsigned int size) + __must_hold(&ht->mutex) {struct bucket_table *new_tbl;int err;
@@ -392,6 +393,7 @@ static int rhashtable_rehash_alloc(struct rhashtable *ht,* bucket locks or concurrent RCU protected lookups and traversals. */ static int rhashtable_shrink (struct rhashtable *ht) + __must_hold(&ht->mutex) {struct bucket_table *old_tbl =rht_dereference (ht->tbl, ht);unsigned int nelems =atomic_read (&ht->nelems);
@@ -724,7 +726,7 @@ EXPORT_SYMBOL_GPL(rhashtable_walk_exit);* resize events and always continue. */ int rhashtable_walk_start_check (struct rhashtable_iter *iter) -__acquires (RCU ) +__acquires_shared (RCU ) {struct rhashtable *ht = iter->ht;bool rhlist = ht->rhlist;
@@ -940,7 +942,6 @@ EXPORT_SYMBOL_GPL(rhashtable_walk_peek);* hash table. */ void rhashtable_walk_stop (struct rhashtable_iter *iter) -__releases (RCU ) {struct rhashtable *ht;struct bucket_table *tbl = iter->walker.tbl;
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog
[tip: locking/core] rhashtable: Enable context analysis
The following commit has been merged into the locking/core branch of tip:
The following commit has been merged into the locking/core branch of tip:
Commit-ID: 322366b8f13a8cafe169dc1dc6f6ec0d82ff8734 Gitweb: https://git.kernel.org/tip/322366b8f13a8cafe169dc1dc6f6ec0d82ff8734 Author: Marco Elver <[email protected]> AuthorDate: Fri, 19 Dec 2025 16:40:21 +01:00 Committer: Peter Zijlstra <[email protected]> CommitterDate: Mon, 05 Jan 2026 16:43:35 +01:00
rhashtable: Enable context analysis
Enable context analysis for rhashtable, which was used as an initial test as it contains a combination of RCU, mutex, and bit_spinlock usage.
Users of rhashtable now also benefit from annotations on the API, which will now warn if the RCU read lock is not held where required.
--- include/linux/rhashtable.h | 16 +++++++++++++--- lib/Makefile | 2 ++ lib/rhashtable.c | 5 +++-- 3 files changed, 18 insertions(+), 5 deletions(-)
include/linux/rhashtable.h +13 -3
@@ -245,16 +245,17 @@ void *rhashtable_insert_slow(struct rhashtable *ht, const void *key,void rhashtable_walk_enter (struct rhashtable *ht,struct rhashtable_iter *iter);void rhashtable_walk_exit (struct rhashtable_iter *iter); -int rhashtable_walk_start_check(struct rhashtable_iter *iter) __acquires(RCU); +int rhashtable_walk_start_check(struct rhashtable_iter *iter) __acquires_shared(RCU);static inline void rhashtable_walk_start (struct rhashtable_iter *iter) +__acquires_shared (RCU ) { (void )rhashtable_walk_start_check (iter); }void *rhashtable_walk_next (struct rhashtable_iter *iter);void *rhashtable_walk_peek (struct rhashtable_iter *iter); -void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases(RCU); +void rhashtable_walk_stop(struct rhashtable_iter *iter) __releases_shared(RCU); void rhashtable_free_and_destroy(struct rhashtable *ht, void (*free_fn)(void *ptr, void *arg),
@@ -325,6 +326,7 @@ static inline struct rhash_lock_head __rcu **rht_bucket_insert(static inline unsigned long rht_lock (struct bucket_table *tbl,struct rhash_lock_head __rcu **bkt) +__acquires (__bitlock (0 , bkt)) {unsigned long flags;
@@ -337,6 +339,7 @@ static inline unsigned long rht_lock(struct bucket_table *tbl,static inline unsigned long rht_lock_nested (struct bucket_table *tbl,struct rhash_lock_head __rcu **bucket,unsigned int subclass) +__acquires (__bitlock (0 , bucket)) {unsigned long flags;
@@ -349,6 +352,7 @@ static inline unsigned long rht_lock_nested(struct bucket_table *tbl,static inline void rht_unlock (struct bucket_table *tbl,struct rhash_lock_head __rcu **bkt,unsigned long flags) +__releases (__bitlock (0 , bkt)) {lock_map_release (&tbl->dep_map);bit_spin_unlock (0 , (unsigned long *)bkt);
@@ -424,13 +428,14 @@ static inline void rht_assign_unlock(struct bucket_table *tbl,struct rhash_lock_head __rcu **bkt, struct rhash_head *obj, unsigned long flags) + __releases(__bitlock(0, bkt)) { if (rht_is_a_nulls(obj)) obj =NULL ;lock_map_release (&tbl->dep_map);rcu_assign_pointer (*bkt, (void *)obj);preempt_enable (); -__release (bitlock); +__release (__bitlock (0 , bkt));local_irq_restore (flags); }
@@ -612,6 +617,7 @@ static __always_inline struct rhash_head *__rhashtable_lookup( struct rhashtable *ht, const void *key, const struct rhashtable_params params, const enum rht_lookup_freq freq) + __must_hold_shared(RCU) { struct rhashtable_compare_arg arg = { .ht = ht,
@@ -666,6 +672,7 @@ restart: static __always_inline void *rhashtable_lookup(struct rhashtable *ht,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (ht, key, params,RHT_LOOKUP_NORMAL );
@@ -676,6 +683,7 @@ static __always_inline void *rhashtable_lookup( static __always_inline void *rhashtable_lookup_likely(struct rhashtable *ht,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (ht, key, params,RHT_LOOKUP_LIKELY );
@@ -727,6 +735,7 @@ static __always_inline void *rhashtable_lookup_fast( static __always_inline struct rhlist_head *rhltable_lookup(struct rhltable *hlt,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (&hlt->ht, key, params,RHT_LOOKUP_NORMAL );
@@ -737,6 +746,7 @@ static __always_inline struct rhlist_head *rhltable_lookup( static __always_inline struct rhlist_head *rhltable_lookup_likely(struct rhltable *hlt,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhash_head *he =__rhashtable_lookup (&hlt->ht, key, params,RHT_LOOKUP_LIKELY );
lib/Makefile +2 -0
@@ -50,6 +50,8 @@ lib-$(CONFIG_MIN_HEAP) += min_heap.o lib-y += kobject.o klist.o obj-y += lockref.o +CONTEXT_ANALYSIS_rhashtable.o := y + obj-y += bcd.o sort.o parser.o debug_locks.o random32.o \ bust_spinlocks.o kasprintf.o bitmap.o scatterlist.o \ list_sort.o uuid.o iov_iter.o clz_ctz.o \
lib/rhashtable.c +3 -2
@@ -358,6 +358,7 @@ static int rhashtable_rehash_table(struct rhashtable *ht)static int rhashtable_rehash_alloc (struct rhashtable *ht,struct bucket_table *old_tbl,unsigned int size) + __must_hold(&ht->mutex) {struct bucket_table *new_tbl;int err;
@@ -392,6 +393,7 @@ static int rhashtable_rehash_alloc(struct rhashtable *ht,* bucket locks or concurrent RCU protected lookups and traversals. */ static int rhashtable_shrink (struct rhashtable *ht) + __must_hold(&ht->mutex) {struct bucket_table *old_tbl =rht_dereference (ht->tbl, ht);unsigned int nelems =atomic_read (&ht->nelems);
@@ -724,7 +726,7 @@ EXPORT_SYMBOL_GPL(rhashtable_walk_exit);* resize events and always continue. */ int rhashtable_walk_start_check (struct rhashtable_iter *iter) -__acquires (RCU ) +__acquires_shared (RCU ) {struct rhashtable *ht = iter->ht;bool rhlist = ht->rhlist;
@@ -940,7 +942,6 @@ EXPORT_SYMBOL_GPL(rhashtable_walk_peek);* hash table. */ void rhashtable_walk_stop (struct rhashtable_iter *iter) -__releases (RCU ) {struct rhashtable *ht;struct bucket_table *tbl = iter->walker.tbl;
Marco Elver
maintainerPATCH v5 33/36 printk: Move locking annotation to printk.c
In reply to Marco ElverWith Sparse support gone, Clang is a bit more strict and warns:
./include/linux/console.h:492:50: error: use of undeclared identifier 'console_mutex'
492 | extern void console_list_unlock(void) __releases(console_mutex);
Since it does not make sense to make console_mutex itself global, move the annotation to printk.c. Context analysis remains disabled for printk.c.
This is needed to enable context analysis for modules that include <linux/console.h>.
---
v2:
* New patch.
--- include/linux/console.h | 4 ++-- kernel/printk/printk.c | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-)
include/linux/console.h +2 -2
@@ -492,8 +492,8 @@ static inline bool console_srcu_read_lock_is_held(void)extern int console_srcu_read_lock (void );extern void console_srcu_read_unlock (int cookie); -extern void console_list_lock(void) __acquires(console_mutex); -extern void console_list_unlock(void) __releases(console_mutex); +extern void console_list_lock (void ); +extern void console_list_unlock (void );extern struct hlist_head console_list;
kernel/printk/printk.c +2 -0
@@ -245,6 +245,7 @@ int devkmsg_sysctl_set_loglvl(const struct ctl_table *table, int write,* For console list or console->flags updates */ void console_list_lock (void ) + __acquires(&console_mutex) {/* * In unregister_console() and console_force_preferred_locked(),
@@ -269,6 +270,7 @@ EXPORT_SYMBOL(console_list_lock);* Counterpart to console_list_lock() */ void console_list_unlock (void ) + __releases(&console_mutex) {mutex_unlock (&console_mutex); }
Signature · 1 line
2.52.0.322.g1dd061c0dc-goog