Compiler-Based Capability- and Locking-Analysis
Subsystems (38)
Marco Elver
maintainerv2 cover Compiler-Based Capability- and Locking-Analysis
Capability analysis is a C language extension, which enables statically checking that user-definable "capabilities" are acquired and released where required. An obvious application is lock-safety checking for the kernel's various synchronization primitives (each of which represents a "capability"), and checking that locking rules are not violated.
Clang originally called the feature "Thread Safety Analysis" [1], with some terminology still using the thread-safety-analysis-only names. 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, the naming chosen for the kernel departs from Clang's initial "Thread Safety" nomenclature and refers to the feature as "Capability Analysis" to avoid confusion. The implementation still makes references to the older terminology in some places, such as -Wthread-safety being the warning enabled option that also still appears in diagnostic messages.
Enabling capability analysis can be seen as enabling a dialect of Linux C with a Capability System.
Additional details can be found in the added kernel-doc documentation.
[1] https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
[2] https://www.cs.cornell.edu/talc/papers/capabilities.pdf
=== Development Approach ===
Prior art exists in the form of Sparse's context tracking. Locking annotations on functions exist, 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 capability 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 -- 2 approaches have been considered:
A. Tree-wide all-or-nothing approach. This approach requires tree-wide
changes, adding annotations or selective opt-outs. Making additional primitives capability-enabled increases churn, esp. where maintainers are unaware of the feature's existence and how to use it.
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 "capability analysis" (via Makefile):
CAPABILITY_ANALYSIS_foo.o := y # foo.o only
CAPABILITY_ANALYSIS := y # all TUs
Most (eventually all) synchronization primitives and more capabilities (including ones that could 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 capability analysis for the following subsystems:
* mm/kfence
* kernel/kcov
* lib/stackdepot
* lib/rhashtable
* drivers/tty
* security/tomoyo
* crypto/
The initial benefits are static detection of violations of locking rules. As more capabilities are added, we would see more static checking beyond what regular C can provide, all while remaining easy (read 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 capability 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 is recommended, but not a strong dependency:
https://github.com/llvm/llvm-project/commit/de10e44b6fe7f3d3cfde3afd8e1222d251172ade
This series is also available at this Git tree:
https://git.kernel.org/pub/scm/linux/kernel/git/melver/linux.git/log/?h=cap-analysis/dev
=== Changelog ===
v2:
- 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 (34):
compiler_types: Move lock checking attributes to
compiler-capability-analysis.h
compiler-capability-analysis: Add infrastructure for Clang's
capability analysis
compiler-capability-analysis: Add test stub
Documentation: Add documentation for Compiler-Based Capability
Analysis
checkpatch: Warn about capability_unsafe() without comment
cleanup: Basic compatibility with capability analysis
lockdep: Annotate lockdep assertions for capability analysis locking/rwlock, spinlock: Support Clang's capability analysis compiler-capability-analysis: Change __cond_acquires to take return
value
locking/mutex: Support Clang's capability analysis locking/seqlock: Support Clang's capability analysis
bit_spinlock: Include missing <asm/processor.h>
bit_spinlock: Support Clang's capability analysis
rcu: Support Clang's capability analysis
srcu: Support Clang's capability analysis
kref: Add capability-analysis annotations
locking/rwsem: Support Clang's capability analysis locking/local_lock: Include missing headers locking/local_lock: Support Clang's capability analysis locking/ww_mutex: Support Clang's capability analysis
debugfs: Make debugfs_cancellation a capability struct compiler-capability-analysis: Remove Sparse support compiler-capability-analysis: Remove __cond_lock() function-like
helper
compiler-capability-analysis: Introduce header suppressions
compiler: Let data_race() imply disabled capability analysis
kfence: Enable capability analysis
kcov: Enable capability analysis
stackdepot: Enable capability analysis
rhashtable: Enable capability analysis
printk: Move locking annotation to printk.c
drivers/tty: Enable capability analysis for core files security/tomoyo: Enable capability analysis
crypto: Enable capability analysis
MAINTAINERS: Add entry for Capability Analysis
.../dev-tools/capability-analysis.rst | 148 +++++ Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/sparse.rst | 19 - Documentation/mm/process_addrs.rst | 6 +- MAINTAINERS | 11 + Makefile | 1 + crypto/Makefile | 2 + 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 | 8 +- .../net/wireless/intel/iwlwifi/iwl-trans.c | 4 +- .../net/wireless/intel/iwlwifi/iwl-trans.h | 6 +- .../wireless/intel/iwlwifi/pcie/internal.h | 5 +- .../net/wireless/intel/iwlwifi/pcie/trans.c | 4 +- drivers/tty/Makefile | 3 + drivers/tty/n_tty.c | 16 + drivers/tty/pty.c | 1 + drivers/tty/sysrq.c | 1 + drivers/tty/tty.h | 8 +- drivers/tty/tty_buffer.c | 8 +- drivers/tty/tty_io.c | 12 +- drivers/tty/tty_ioctl.c | 2 +- drivers/tty/tty_ldisc.c | 35 +- drivers/tty/tty_ldsem.c | 2 + drivers/tty/tty_mutex.c | 4 + drivers/tty/tty_port.c | 2 + fs/dlm/lock.c | 2 +- include/crypto/internal/engine.h | 2 +- include/linux/bit_spinlock.h | 24 +- include/linux/cleanup.h | 18 +- include/linux/compiler-capability-analysis.h | 368 ++++++++++++ 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 | 18 +- include/linux/local_lock_internal.h | 43 +- include/linux/lockdep.h | 12 +- include/linux/mm.h | 33 +- include/linux/mutex.h | 29 +- include/linux/mutex_types.h | 4 +- include/linux/rcupdate.h | 86 +-- include/linux/refcount.h | 6 +- include/linux/rhashtable.h | 14 +- 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 | 56 +- include/linux/sched/signal.h | 14 +- include/linux/seqlock.h | 24 + include/linux/seqlock_types.h | 5 +- include/linux/spinlock.h | 64 +- 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 | 61 +- include/linux/tty.h | 14 +- include/linux/tty_flip.h | 4 +- include/linux/tty_ldisc.h | 19 +- include/linux/ww_mutex.h | 21 +- kernel/Makefile | 2 + kernel/kcov.c | 36 +- kernel/printk/printk.c | 2 + kernel/signal.c | 4 +- kernel/time/posix-timers.c | 10 +- lib/Kconfig.debug | 45 ++ lib/Makefile | 6 + lib/dec_and_lock.c | 8 +- lib/rhashtable.c | 5 +- lib/stackdepot.c | 20 +- lib/test_capability-analysis.c | 548 ++++++++++++++++++ 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.capability-analysis | 11 + scripts/Makefile.lib | 10 + scripts/capability-analysis-suppression.txt | 32 + scripts/checkpatch.pl | 8 + 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 - 101 files changed, 2086 insertions(+), 521 deletions(-) create mode 100644 Documentation/dev-tools/capability-analysis.rst create mode 100644 include/linux/compiler-capability-analysis.h create mode 100644 lib/test_capability-analysis.c create mode 100644 scripts/Makefile.capability-analysis create mode 100644 scripts/capability-analysis-suppression.txt
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 1/34 compiler_types: Move lock checking attributes to compiler-capability-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 "capability analysis".
No functional change intended.
--- include/linux/compiler-capability-analysis.h | 32 ++++++++++++++++++++ include/linux/compiler_types.h | 18 ++--------- 2 files changed, 34 insertions(+), 16 deletions(-) create mode 100644 include/linux/compiler-capability-analysis.h
include/linux/compiler-capability-analysis.h new file +32 -0
@@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Macros and attributes for compiler-based static capability analysis. +*/ + +#ifndef _LINUX_COMPILER_CAPABILITY_ANALYSIS_H +#define _LINUX_COMPILER_CAPABILITY_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_CAPABILITY_ANALYSIS_H */
include/linux/compiler_types.h +2 -16
@@ -24,6 +24,8 @@# define BTF_TYPE_TAG (value)/* nothing */ #endif +#include <linux/compiler-capability-analysis.h> +/* sparse defines __CHECKER__; see Documentation/dev-tools/sparse.rst */ #ifdef __CHECKER__/* address spaces */
@@ -34,14 +36,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))
@@ -62,14 +56,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.48.1.711.g2feabab25a-goog
Re: [PATCH v2 01/34] compiler_types: Move lock checking attributes to compiler-capability-analysis.h
Quoted 5 lines · Marco Elver
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 "capability analysis".
Re: [PATCH v2 01/34] compiler_types: Move lock checking attributes to compiler-capability-analysis.h
In reply to Marco ElverQuoted 4 lines · Marco Elver
include/linux/compiler-capability-analysis.h new file +4
-0+#ifndef _LINUX_COMPILER_CAPABILITY_ANALYSIS_H +#define _LINUX_COMPILER_CAPABILITY_ANALYSIS_H + +#ifdef __CHECKER__
include/linux/compiler-capability-analysis.h line 19
Quoted 10 lines
include/linux/compiler-capability-analysis.h new file +10
-0+ +/* 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) +
The other thing you might want to annotate is ww_mutex_destroy().
I'm happy about the new __guarded_by annotation.
regards,
dan carpenter
Marco Elver
maintainerRe: [PATCH v2 01/34] compiler_types: Move lock checking attributes to compiler-capability-analysis.h
Quoted 17 lines · Dan Carpenter
Quoted 4 lines · Marco Elver
(quoted diff) +4
-0+#ifndef _LINUX_COMPILER_CAPABILITY_ANALYSIS_H +#define _LINUX_COMPILER_CAPABILITY_ANALYSIS_H + +#ifdef __CHECKER__Review
Quoted 10 lines
(quoted diff) +10
-0+ +/* 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) +The other thing you might want to annotate is
ww_mutex_destroy().
We can add an annotation to check the lock is not held:
include/linux/ww_mutex.h +1 -0
@@ -372,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_capability-analysis.c +4 -0
@@ -516,6 +516,8 @@ static void __used test_ww_mutex_lock_noctx(struct test_ww_mutex_data *d)ww_mutex_lock_slow (&d->mtx,NULL ); d->counter++;ww_mutex_unlock (&d->mtx); + +ww_mutex_destroy (&d->mtx); }static void __used test_ww_mutex_lock_ctx (struct test_ww_mutex_data *d)
@@ -545,4 +547,6 @@ static void __used test_ww_mutex_lock_ctx(struct test_ww_mutex_data *d)ww_acquire_done (&ctx);ww_acquire_fini (&ctx); + +ww_mutex_destroy (&d->mtx); }
Probably a fixup for the ww_mutex patch:
https://lore.kernel.org/all/[email protected]/
Or extra patch depending on when/if Peter decides to take the series.
Quoted 1 line
I'm happy about the new
__guarded_byannotation.
Thanks!
-- Marco
Re: [PATCH v2 01/34] compiler_types: Move lock checking attributes to compiler-capability-analysis.h
Quoted 19 lines · Marco Elver
Quoted 17 lines · Dan Carpenter
Quoted 4 lines · Marco Elver
(quoted diff) +4
-0+#ifndef _LINUX_COMPILER_CAPABILITY_ANALYSIS_H +#define _LINUX_COMPILER_CAPABILITY_ANALYSIS_H + +#ifdef __CHECKER__Review
Quoted 10 lines
(quoted diff) +10
-0+ +/* 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) +The other thing you might want to annotate is
ww_mutex_destroy().
Quoted 2 lines
We can add an annotation to check the lock is not held:
Sorry, my email was bad.
I haven't actually tried your patch at all. I have locking check in Smatch so I'm just basing this on the things that I did...
https://github.com/error27/smatch/blob/master/smatch_locking.c
This isn't a mandatory thing. Whatever happens we're going to end up doing dozens of patches all over the kernel later.
I thought you could destroy a mutex regardless or whether it was held or not. I was getting false positives which said that we should drop the lock on error but actually the mutex is destroyed on that path so it doesn't matter.
regards,
dan carpenter
Marco Elver
maintainerPATCH v2 2/34 compiler-capability-analysis: Add infrastructure for Clang's capability analysis
In reply to Marco ElverCapability analysis is a C language extension, which enables statically checking that user-definable "capabilities" are acquired and released where required. An obvious application is lock-safety checking for the kernel's various synchronization primitives (each of which represents a "capability"), and checking that locking rules are not violated.
Clang originally called the feature "Thread Safety Analysis" [1], with some terminology still using the thread-safety-analysis-only names. 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", used to specify the permissibility of operations to depend on some capability being held (or not held).
[1] https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
[2] https://www.cs.cornell.edu/talc/papers/capabilities.pdf
Because the feature is not just able to express capabilities related to synchronization primitives, the naming chosen for the kernel departs from Clang's initial "Thread Safety" nomenclature and refers to the feature as "Capability Analysis" to avoid confusion. The implementation still makes references to the older terminology in some places, such as -Wthread-safety being the warning enabled option that also still appears in diagnostic messages.
See more details in the kernel-doc documentation added in this and the subsequent changes.
A Clang version that supports -Wthread-safety-pointer is recommended, but not required: https://github.com/llvm/llvm-project/commit/de10e44b6fe7
---
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-capability-analysis.h | 394 ++++++++++++++++++- lib/Kconfig.debug | 29 ++ scripts/Makefile.capability-analysis | 7 + scripts/Makefile.lib | 10 + 5 files changed, 434 insertions(+), 7 deletions(-) create mode 100644 scripts/Makefile.capability-analysis
Makefile +1 -0
@@ -1082,6 +1082,7 @@ include-$(CONFIG_KCOV) += scripts/Makefile.kcov include-$(CONFIG_RANDSTRUCT) += scripts/Makefile.randstruct include-$(CONFIG_AUTOFDO_CLANG) += scripts/Makefile.autofdo include-$(CONFIG_PROPELLER_CLANG) += scripts/Makefile.propeller +include-$(CONFIG_WARN_CAPABILITY_ANALYSIS) += scripts/Makefile.capability-analysis include-$(CONFIG_GCC_PLUGINS) += scripts/Makefile.gcc-plugins include $(addprefix $(srctree)/, $(include-y))
include/linux/compiler-capability-analysis.h +387 -7
413 lines not on this page · raw message
lib/Kconfig.debug +29 -0
@@ -603,6 +603,35 @@ 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_CAPABILITY_ANALYSIS + bool "Compiler capability-analysis warnings" + depends on CC_IS_CLANG && $(cc-option,-Wthread-safety -fexperimental-late-parse-attributes) + # 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 + Capability analysis is a C language extension, which enables + statically checking that user-definable "capabilities" are acquired + and released where required. + + Clang's name of the feature ("Thread Safety Analysis") refers to + the original name of the feature; it was later expanded to be a + generic "Capability Analysis" framework. + + Produces warnings by default. Select CONFIG_WERROR if you wish to + turn these warnings into errors. + +config WARN_CAPABILITY_ANALYSIS_ALL + bool "Enable capability analysis for all source files" + depends on WARN_CAPABILITY_ANALYSIS + depends on EXPERT && !COMPILE_TEST + help + Enable tree-wide capability 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.capability-analysis new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 + +capability-analysis-cflags := -DWARN_CAPABILITY_ANALYSIS \ + -fexperimental-late-parse-attributes -Wthread-safety \ + $(call cc-option,-Wthread-safety-pointer) + +export CFLAGS_CAPABILITY_ANALYSIS := $(capability-analysis-cflags)
scripts/Makefile.lib +10 -0
@@ -191,6 +191,16 @@ _c_flags += $(if $(patsubst n%,, \ -D__KCSAN_INSTRUMENT_BARRIERS__) endif +# +# Enable capability analysis flags only where explicitly opted in. +# (depends on variables CAPABILITY_ANALYSIS_obj.o, CAPABILITY_ANALYSIS) +# +ifeq ($(CONFIG_WARN_CAPABILITY_ANALYSIS),y) +_c_flags += $(if $(patsubst n%,, \ + $(CAPABILITY_ANALYSIS_$(target-stem).o)$(CAPABILITY_ANALYSIS)$(if $(is-kernel-object),$(CONFIG_WARN_CAPABILITY_ANALYSIS_ALL))), \ + $(CFLAGS_CAPABILITY_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.48.1.711.g2feabab25a-goog
Peter Zijlstra
maintainerRe: [PATCH v2 02/34] compiler-capability-analysis: Add infrastructure for Clang's capability analysis
include/linux/compiler-capability-analysis.h line 109
Quoted 7 lines · Marco Elver
include/linux/compiler-capability-analysis.h +6
-0+# define __asserts_cap (var) __attribute__((assert_capability(var))) +# define __asserts_shared_cap (var) __attribute__((assert_shared_capability(var))) + static __always_inline void __assert_cap(const struct name *var) \ + __attribute__((overloadable))__asserts_cap (var) { } \ + static __always_inline void __assert_shared_cap(const struct name *var) \ + __attribute__((overloadable))__asserts_shared_cap (var) { } \
Since this does not in fact check -- that's __must_hold(), I would suggest renaming these like s/assert/assume/.
Marco Elver
maintainerRe: [PATCH v2 02/34] compiler-capability-analysis: Add infrastructure for Clang's capability analysis
Quoted 6 lines · Peter Zijlstra
Quoted 2 lines · Marco Elver
include/linux/compiler-capability-analysis.h +2
-0+# define __asserts_cap (var) __attribute__((assert_capability(var))) +# define __asserts_shared_cap (var) __attribute__((assert_shared_capability(var)))
Quoted 7 lines
include/linux/compiler-capability-analysis.h line 109
Quoted 4 lines
include/linux/compiler-capability-analysis.h +4
-0+ static __always_inline void __assert_cap(const struct name *var) \ + __attribute__((overloadable))__asserts_cap (var) { } \ + static __always_inline void __assert_shared_cap(const struct name *var) \ + __attribute__((overloadable))__asserts_shared_cap (var) { } \Since this does not in fact check -- that's
__must_hold(), I would suggest renaming these like s/assert/assume/.
Yeah, that's better.
FTR - the "asserts_capability" attribute was originally meant to be used on runtime functions that check that a lock is held at runtime; what Clang does underneath is simply adding the given capability/lock to the held lockset, so no real checking is enforced. In this series it's used for a lot more than just our lockdep_assert*() helpers, so the "assert" naming is indeed confusing.
Thanks!
Marco Elver
maintainerPATCH v2 3/34 compiler-capability-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 positive of each new supported capability.
--- lib/Kconfig.debug | 14 ++++++++++++++ lib/Makefile | 3 +++ lib/test_capability-analysis.c | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 lib/test_capability-analysis.c
lib/Kconfig.debug +14 -0
@@ -2764,6 +2764,20 @@ config LINEAR_RANGES_TEST If unsure, say N. +config CAPABILITY_ANALYSIS_TEST + bool "Compiler capability-analysis warnings test" + depends on EXPERT + help + This builds the test for compiler-based capability 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 capabilities, 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
@@ -394,6 +394,9 @@ obj-$(CONFIG_CRC_KUNIT_TEST) += crc_kunit.o obj-$(CONFIG_SIPHASH_KUNIT_TEST) += siphash_kunit.o obj-$(CONFIG_USERCOPY_KUNIT_TEST) += usercopy_kunit.o +CAPABILITY_ANALYSIS_test_capability-analysis.o := y +obj-$(CONFIG_CAPABILITY_ANALYSIS_TEST) += test_capability-analysis.o + obj-$(CONFIG_GENERIC_LIB_DEVMEM_IS_ALLOWED) += devmem_is_allowed.o obj-$(CONFIG_FIRMWARE_TABLE) += fw_table.o
lib/test_capability-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 capability analysis. +*/ + +#include <linux/build_bug.h> + +/* +* Test that helper macros work as expected. +*/ +static void __used test_common_helpers (void ) +{ +BUILD_BUG_ON (capability_unsafe (3 ) !=3 );/* plain expression */ + BUILD_BUG_ON(capability_unsafe((void)2; 3;) != 3); /* does not swallow semi-colon */ +BUILD_BUG_ON (capability_unsafe ((void )2 ,3 ) !=3 );/* does not swallow commas */ + capability_unsafe(do { } while (0)); /* works with void statements */ +}
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Re: [PATCH v2 03/34] compiler-capability-analysis: Add test stub
lib/test_capability-analysis.c line 18
Quoted 12 lines · Marco Elver
lib/test_capability-analysis.c new file +12
-0+#include <linux/build_bug.h> + +/* +* Test that helper macros work as expected. +*/ +static void __used test_common_helpers (void ) +{ +BUILD_BUG_ON (capability_unsafe (3 ) !=3 );/* plain expression */ + BUILD_BUG_ON(capability_unsafe((void)2; 3;) != 3); /* does not swallow semi-colon */ +BUILD_BUG_ON (capability_unsafe ((void )2 ,3 ) !=3 );/* does not swallow commas */ + capability_unsafe(do { } while (0)); /* works with void statements */ +}
Is it guaranteed that <linux/build_bug.h> includes the header file that defines capability_unsafe() or should that header file perhaps be included explicitly?
Thanks,
Bart.
Marco Elver
maintainerRe: [PATCH v2 03/34] compiler-capability-analysis: Add test stub
Quoted 18 lines · Bart Van Assche
lib/test_capability-analysis.c line 18
Quoted 12 lines · Marco Elver
lib/test_capability-analysis.c new file +12
-0+#include <linux/build_bug.h> + +/* +* Test that helper macros work as expected. +*/ +static void __used test_common_helpers (void ) +{ +BUILD_BUG_ON (capability_unsafe (3 ) !=3 );/* plain expression */ + BUILD_BUG_ON(capability_unsafe((void)2; 3;) != 3); /* does not swallow semi-colon */ +BUILD_BUG_ON (capability_unsafe ((void )2 ,3 ) !=3 );/* does not swallow commas */ + capability_unsafe(do { } while (0)); /* works with void statements */ +}Is it guaranteed that <
linux/build_bug.h> includes the header file that definescapability_unsafe()or should that header file perhaps be included explicitly?
It doesn't come in via build_bug.h, but via:
scripts/Makefile.lib -> "-include
$(srctree)/include/linux/compiler_types.h" (all TUs) -> compiler-capability-analysis.h.
The things pulled in via compiler_types.h are treated a bit like builtins available everywhere implicitly.
Marco Elver
maintainerPATCH v2 4/34 Documentation: Add documentation for Compiler-Based Capability Analysis
In reply to Marco ElverAdds documentation in Documentation/dev-tools/capability-analysis.rst, and adds it to the index and cross-references from Sparse's document.
---
v2:
* Remove cross-reference to Sparse, since we plan to remove Sparse support anyway.
* Mention __no_capability_analysis should be avoided.
--- .../dev-tools/capability-analysis.rst | 145 ++++++++++++++++++ Documentation/dev-tools/index.rst | 1 + 2 files changed, 146 insertions(+) create mode 100644 Documentation/dev-tools/capability-analysis.rst
Documentation/dev-tools/capability-analysis.rst new file +145 -0
@@ -0,0 +1,145 @@ +.. SPDX-License-Identifier: GPL-2.0 +.. Copyright (C) 2025, Google LLC. + +.. _capability-analysis: + +Compiler-Based Capability Analysis +================================== + +Capability analysis is a C language extension, which enables statically +checking that user-definable "capabilities" are acquired and released where +required. An obvious application is lock-safety checking for the kernel's +various synchronization primitives (each of which represents a "capability"), +and checking that locking rules are not violated. + +The Clang compiler currently supports the full set of capability analysis +features. To enable for Clang, configure the kernel with:: + + CONFIG_WARN_CAPABILITY_ANALYSIS=y + +The analysis is *opt-in by default*, and requires declaring which modules and +subsystems should be analyzed in the respective `Makefile`:: + + CAPABILITY_ANALYSIS_mymodule.o := y + +Or for all translation units in the directory:: + + CAPABILITY_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_CAPABILITY_ANALYSIS_ALL=y + +Programming Model +----------------- + +The below describes the programming model around using capability-enabled +types. + +.. note:: + Enabling capability analysis can be seen as enabling a dialect of Linux C with + a Capability System. Some valid patterns involving complex control-flow are + constrained (such as conditional acquisition and later conditional release + in the same function, or returning pointers to capabilities from functions. + +Capability analysis is a way to specify permissibility of operations to depend +on capabilities being held (or not held). Typically we are interested in +protecting data and code by requiring some capability to be held, for example a +specific lock. The analysis ensures that the caller cannot perform the +operation without holding the appropriate capability. + +Capabilities are associated with named structs, along with functions that +operate on capability-enabled struct instances to acquire and release the +associated capability. + +Capabilities can be held either exclusively or shared. This mechanism allows +assign more precise privileges when holding a capability, typically to +distinguish where a thread may only read (shared) or also write (exclusive) to +guarded data. + +The set of capabilities that are actually held by 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 capability environment. +The capability environment is calculated for every program point, and describes +the set of capabilities that are statically known to be held, or not held, at +that particular point. This environment is a conservative approximation of the +full set of capabilities that will actually held by 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 capabilities acquired or released + by inline functions. It requires explicit annotations to (a) assert that + it's not a bug if a capability 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 capabilities with an initialization function (e.g., `spin_lock_init()`), +calling this function on the capability instance 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 +capability 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-capability-analysis.h + :identifiers: struct_with_capability + token_capability token_capability_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 + capability_unsafe + __capability_unsafe + disable_capability_analysis enable_capability_analysis + +.. note:: + The function attribute `__no_capability_analysis` is reserved for internal + implementation of capability-enabled primitives, 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 +terminology still using the thread-safety-analysis-only names. This was later +changed and the feature became more flexible, gaining the ability to define +custom "capabilities". + +Indeed, 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, the naming chosen for the kernel departs from +Clang's initial "Thread Safety" nomenclature and refers to the feature as +"Capability Analysis" to avoid confusion. The implementation still makes +references to the older terminology in some places, such as `-Wthread-safety` +being the warning option that also still appears in diagnostic messages.
Documentation/dev-tools/index.rst +1 -0
@@ -18,6 +18,7 @@ Documentation/process/debugging/index.rst :maxdepth: 2 testing-overview + capability-analysis checkpatch clang-format coccinelle
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 5/34 checkpatch: Warn about capability_unsafe() without comment
In reply to Marco ElverWarn about applications of capability_unsafe() without a comment, to encourage documenting the reasoning behind why it was deemed safe.
--- scripts/checkpatch.pl | 8 ++++++++ 1 file changed, 8 insertions(+)
scripts/checkpatch.pl +8 -0
@@ -6693,6 +6693,14 @@ sub process { } } +# check for capability_unsafe without a comment. + if ($line =~ /\bcapability_unsafe\b/) { + if (!ctx_has_comment($first_line, $linenr)) { + WARN("CAPABILITY_UNSAFE", + "capability_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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 6/34 cleanup: Basic compatibility with capability analysis
In reply to Marco ElverDue to the scoped cleanup helpers used for lock guards wrapping acquire/release around their own constructors/destructors that store pointers to the passed locks in a separate struct, we currently cannot accurately annotate *destructors* which lock was released. While it's possible to annotate the constructor to say which lock was acquired, that alone would result in false positives claiming the lock was not released on function return.
Instead, to avoid false positives, we can claim that the constructor "asserts" that the taken lock is held. This will ensure we can still benefit from the analysis where scoped guards are used to protect access to guarded variables, while avoiding false positives. The only downside are false negatives where we might accidentally lock the same lock again:
raw_spin_lock(&my_lock); ... guard(raw_spinlock)(&my_lock); // no warning
Arguably, lockdep will immediately catch issues like this.
While Clang's analysis supports scoped guards in C++ [1], there's no way to apply this to C right now. Better support for Linux's scoped guard design could be added in future if deemed critical.
[1] https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#scoped-capability
--- include/linux/cleanup.h | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
include/linux/cleanup.h +10 -4
@@ -223,7 +223,7 @@ const volatile void * __must_check_fn(const volatile void *val)* @exit is an expression using '_T' -- similar to FREE above. * @init is an expression in @init_args resulting in @type * -* EXTEND_CLASS(name, ext, init, init_args...): +* EXTEND_CLASS(name, ext, ctor_attrs, init, init_args...): * extends class @name to @name@ext with the new constructor * * CLASS(name, var)(args...):
@@ -243,15 +243,18 @@ const volatile void * __must_check_fn(const volatile void *val) #define DEFINE_CLASS(_name, _type, _exit, _init, _init_args...) \ typedef _type class_##_name##_t; \ static inline void class_##_name##_destructor(_type *p) \ + __no_capability_analysis \ { _type _T = *p; _exit; } \ static inline _type class_##_name##_constructor(_init_args) \ + __no_capability_analysis \ { _type t = _init; return t; } -#define EXTEND_CLASS(_name, ext, _init, _init_args...) \ +#define EXTEND_CLASS(_name, ext, ctor_attrs, _init, _init_args...) \ typedef class_##_name##_t class_##_name##ext##_t; \ static inline void class_##_name##ext##_destructor(class_##_name##_t *p)\ { class_##_name##_destructor(p); } \ static inline class_##_name##_t class_##_name##ext##_constructor(_init_args) \ + __no_capability_analysis ctor_attrs \ { class_##_name##_t t = _init; return t; }#define CLASS (_name, var) \
@@ -299,7 +302,7 @@ static __maybe_unused const bool class_##_name##_is_conditional = _is_cond#define DEFINE_GUARD_COND (_name, _ext, _condlock) \ __DEFINE_CLASS_IS_CONDITIONAL(_name##_ext, true); \ - EXTEND_CLASS(_name, _ext, \ + EXTEND_CLASS(_name, _ext,, \ ({ void *_t = _T; if (_T && !(_condlock)) _t = NULL; _t; }), \ class_##_name##_t _T) \ static inline void * class_##_name##_ext##_lock_ptr(class_##_name##_t *_T) \
@@ -371,6 +374,7 @@ typedef struct { \ } class_##_name##_t; \ \ static inline void class_##_name##_destructor(class_##_name##_t *_T) \ + __no_capability_analysis \ { \if (_T->lock) { _unlock; } \ } \
@@ -383,6 +387,7 @@ static inline void *class_##_name##_lock_ptr(class_##_name##_t *_T) \#define __DEFINE_LOCK_GUARD_1 (_name, _type, _lock) \ static inline class_##_name##_t class_##_name##_constructor(_type *l) \ + __no_capability_analysis __asserts_cap(l) \ { \ class_##_name##_t _t = { .lock = l }, *_T = &_t; \ _lock; \
@@ -391,6 +396,7 @@ static inline class_##_name##_t class_##_name##_constructor(_type *l) \#define __DEFINE_LOCK_GUARD_0 (_name, _lock) \ static inline class_##_name##_t class_##_name##_constructor(void) \ + __no_capability_analysis \ { \ class_##_name##_t _t = { .lock = (void*)1 }, \ *_T __maybe_unused = &_t; \
@@ -410,7 +416,7 @@ __DEFINE_LOCK_GUARD_0(_name, _lock)#define DEFINE_LOCK_GUARD_1_COND (_name, _ext, _condlock) \ __DEFINE_CLASS_IS_CONDITIONAL(_name##_ext, true); \ - EXTEND_CLASS(_name, _ext, \ + EXTEND_CLASS(_name, _ext, __asserts_cap(l), \ ({ class_##_name##_t _t = { .lock = l }, *_T = &_t;\ if (_T->lock && !(_condlock)) _T->lock = NULL; \ _t; }), \
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Peter Zijlstra
maintainerRe: [PATCH v2 06/34] cleanup: Basic compatibility with capability analysis
Quoted 19 lines · Marco Elver
Due to the scoped cleanup helpers used for lock guards wrapping acquire/release around their own constructors/destructors that store pointers to the passed locks in a separate struct, we currently cannot accurately annotate *destructors* which lock was released. While it's possible to annotate the constructor to say which lock was acquired, that alone would result in false positives claiming the lock was not released on function return.
Instead, to avoid false positives, we can claim that the constructor "asserts" that the taken lock is held. This will ensure we can still benefit from the analysis where scoped guards are used to protect access to guarded variables, while avoiding false positives. The only downside are false negatives where we might accidentally lock the same lock again:
raw_spin_lock(&my_lock); ... guard(raw_spinlock)(&my_lock); // no warning
Quoted 5 lines
Arguably, lockdep will immediately catch issues like this.
While Clang's analysis supports scoped guards in C++ [1], there's no way to apply this to C right now. Better support for Linux's scoped guard design could be added in future if deemed critical.
Would definitely be nice to have.
include/linux/cleanup.h static inline class_##_name##_t class_##_name##_constructor(_type *l) \ · line 399
Quoted 13 lines
include/linux/cleanup.h +2
-0@@ -383,6 +387,7 @@ static inline void *class_##_name##_lock_ptr(class_##_name##_t *_T) \#define __DEFINE_LOCK_GUARD_1 (_name, _type, _lock) \ static inline class_##_name##_t class_##_name##_constructor(_type *l) \ + __no_capability_analysis __asserts_cap(l) \ { \ class_##_name##_t _t = { .lock = l }, *_T = &_t; \ _lock; \@@ -391,6 +396,7 @@ static inline class_##_name##_t class_##_name##_constructor(_type *l) \#define __DEFINE_LOCK_GUARD_0 (_name, _lock) \ static inline class_##_name##_t class_##_name##_constructor(void) \ + __no_capability_analysis \
Does this not need __asserts_cal(_lock) or somesuch?
GUARD_0 is the one used for RCU and preempt, rather sad if it doesn't have annotations at all.
Marco Elver
maintainerRe: [PATCH v2 06/34] cleanup: Basic compatibility with capability analysis
Quoted 21 lines · Peter Zijlstra
Quoted 19 lines · Marco Elver
Due to the scoped cleanup helpers used for lock guards wrapping acquire/release around their own constructors/destructors that store pointers to the passed locks in a separate struct, we currently cannot accurately annotate *destructors* which lock was released. While it's possible to annotate the constructor to say which lock was acquired, that alone would result in false positives claiming the lock was not released on function return.
Instead, to avoid false positives, we can claim that the constructor "asserts" that the taken lock is held. This will ensure we can still benefit from the analysis where scoped guards are used to protect access to guarded variables, while avoiding false positives. The only downside are false negatives where we might accidentally lock the same lock again:
raw_spin_lock(&my_lock); ... guard(raw_spinlock)(&my_lock); // no warning
Quoted 7 lines
Quoted 5 lines
Arguably, lockdep will immediately catch issues like this.
While Clang's analysis supports scoped guards in C++ [1], there's no way to apply this to C right now. Better support for Linux's scoped guard design could be added in future if deemed critical.
Would definitely be nice to have.
Once we have the basic infra here, I think it'll be easier to push for these improvements. It's not entirely up to me, and we have to coordinate with the Clang maintainers. Definitely is on the list.
Quoted 10 lines
Quoted 10 lines
include/linux/cleanup.h +1
-0@@ -383,6 +387,7 @@ static inline void *class_##_name##_lock_ptr(class_##_name##_t *_T) \#define __DEFINE_LOCK_GUARD_1 (_name, _type, _lock) \ static inline class_##_name##_t class_##_name##_constructor(_type *l) \ + __no_capability_analysis __asserts_cap(l) \ { \ class_##_name##_t _t = { .lock = l }, *_T = &_t; \ _lock; \@@ -391,6 +396,7 @@ static inline class_##_name##_t class_##_name##_constructor(_type *l) \
Quoted 8 lines
include/linux/cleanup.h static inline class_##_name##_t class_##_name##_constructor(_type *l) \ · line 399
Quoted 3 lines
include/linux/cleanup.h +1
-0#define __DEFINE_LOCK_GUARD_0 (_name, _lock) \ static inline class_##_name##_t class_##_name##_constructor(void) \ + __no_capability_analysis \Does this not need
__asserts_cal(_lock)or somesuch?
GUARD_0is the one used for RCU and preempt, rather sad if it doesn't have annotations at all.
This is solved later in the series where we need it for RCU:
https://lore.kernel.org/all/[email protected]/
We can't add this to all GUARD_0, because not all will be for capability-enabled structs. Instead I added a helper to add the necessary annotations where needed (see DECLARE_LOCK_GUARD_0_ATTRS).
Re: [PATCH v2 06/34] cleanup: Basic compatibility with capability analysis
In reply to Marco ElverQuoted 7 lines · Marco Elver
Due to the scoped cleanup helpers used for lock guards wrapping acquire/release around their own constructors/destructors that store pointers to the passed locks in a separate struct, we currently cannot accurately annotate *destructors* which lock was released. While it's possible to annotate the constructor to say which lock was acquired, that alone would result in false positives claiming the lock was not released on function return.
It may be worth mentioning that Clang's thread-safety analyzer not supporting alias analysis plays a role here. Anyway:
Marco Elver
maintainerPATCH v2 7/34 lockdep: Annotate lockdep assertions for capability analysis
In reply to Marco ElverClang's capability analysis can be made aware of functions that assert that capabilities/locks are held.
Presence of these annotations causes the analysis to assume the capability 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); __assert_cap(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)); __assert_cap(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)); __assert_shared_cap(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) __assert_cap(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) __assert_cap(l) +#define lockdep_assert_held_read (l) __assert_shared_cap(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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 8/34 locking/rwlock, spinlock: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability 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 capability as acquired when initialized before guarded variables.
The test verifies that common patterns do not generate false positives.
--- .../dev-tools/capability-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 | 45 +++--- 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_capability-analysis.c | 128 ++++++++++++++++++ 12 files changed, 299 insertions(+), 97 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/rwlock.h +13 -12
@@ -22,23 +22,24 @@ do { \static struct lock_class_key __key; \ \ __rwlock_init((lock), #lock, &__key); \ + __assert_cap(lock); \ } while (0)#else # define rwlock_init (lock) \ - do { *(lock) = __RW_LOCK_UNLOCKED(lock); } while (0) + do { *(lock) = __RW_LOCK_UNLOCKED(lock); __assert_cap(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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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); \ +__assert_cap (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 { +struct_with_capability (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 { +struct_with_capability (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 +29 -16
139 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_capability_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_capability_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_capability_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_capability_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); \ +__assert_cap (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 { +struct_with_capability (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 { +struct_with_capability (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 { +struct_with_capability (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_capability-analysis.c +128 -0
137 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Peter Zijlstra
maintainerRe: [PATCH v2 08/34] locking/rwlock, spinlock: Support Clang's capability analysis
Quoted 2 lines · Marco Elver
To avoid warnings in constructors, the initialization functions mark a capability as acquired when initialized before guarded variables.
Right, took me a bit, but OMG that's a horrific hack :-)
Marco Elver
maintainerPATCH v2 9/34 compiler-capability-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 capability 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 ==> capability acquired in branch taken if condition non-zero, and 0 ==> capability 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.
---
v2:
* Use symbolic values for __cond_acquires() and __cond_acquires_shared() (suggested by Bart).
--- fs/dlm/lock.c | 2 +- include/linux/compiler-capability-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-capability-analysis.h +26 -5
@@ -240,7 +240,7 @@# 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)
@@ -283,15 +283,32 @@*/ # define __acquires (x) __acquires_cap(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__##_cap(1, x) +#define __cond_acquires_impl_false (x, ...) __try_acquires##__VA_ARGS__##_cap(0, x) +#define __cond_acquires_impl_nonzero (x, ...) __try_acquires##__VA_ARGS__##_cap(1, x) +#define __cond_acquires_impl_0 (x, ...) __try_acquires##__VA_ARGS__##_cap(0, x) +#define __cond_acquires_impl_nonnull (x, ...) __try_acquires##__VA_ARGS__##_cap(1, x) +#define __cond_acquires_impl_NULL (x, ...) __try_acquires##__VA_ARGS__##_cap(0, x) +/** * __cond_acquires() - function attribute, function conditionally * acquires a capability exclusively +* @ret: abstract value returned by function if capability acquired * @x: capability instance pointer * * Function attribute declaring that the function conditionally acquires the -* given capability instance @x exclusively, but does not release it. +* given capability instance @x exclusively, but does not release it. The +* function return value @ret denotes when the capability is acquired. +* +* @ret may be one of: true, false, nonzero, 0, nonnull, NULL. */ -# define __cond_acquires (x) __try_acquires_cap(1, x) +# define __cond_acquires (ret, x) __cond_acquires_impl_##ret(x)/** * __releases() - function attribute, function releases a capability exclusively
@@ -358,12 +375,16 @@/** * __cond_acquires_shared() - function attribute, function conditionally * acquires a capability shared +* @ret: abstract value returned by function if capability acquired * @x: capability instance pointer * * Function attribute declaring that the function conditionally acquires the -* given capability instance @x with shared access, but does not release it. +* given capability instance @x with shared access, but does not release it. The +* function return value @ret denotes when the capability is acquired. +* +* @ret may be one of: true, false, nonzero, 0, nonnull, NULL. */ -# define __cond_acquires_shared (x) __try_acquires_shared_cap(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
@@ -353,9 +353,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_capability_analysis +__cond_acquires (true, lock) __no_capability_analysis {return raw_spin_trylock (&lock->rlock); }
@@ -420,13 +420,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_capability_analysis +__cond_acquires (true, lock) __no_capability_analysis {return raw_spin_trylock_bh (&lock->rlock); } static __always_inline int spin_trylock_irq(spinlock_t *lock) -__cond_acquires (lock) __no_capability_analysis +__cond_acquires (true, lock) __no_capability_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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 10/34 locking/mutex: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability analysis for mutex.
--- .../dev-tools/capability-analysis.rst | 2 +- include/linux/mutex.h | 29 +++++---- include/linux/mutex_types.h | 4 +- lib/test_capability-analysis.c | 64 +++++++++++++++++++ 4 files changed, 82 insertions(+), 17 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/mutex.h +15 -14
@@ -62,6 +62,7 @@ do { \static struct lock_class_key __key; \ \ __mutex_init((mutex), #mutex, &__key); \ +__assert_cap (mutex); \ }while (0 )/**
@@ -154,14 +155,14 @@ static inline int __devm_mutex_init(struct device *dev, struct mutex *lock)* 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_nested(struct mutex *lock, -unsigned int subclass); -extern void mutex_lock_io_nested (struct mutex *lock,unsigned int subclass); + unsigned int subclass) __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)
@@ -175,10 +176,10 @@ do { \ } while (0)#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)
@@ -193,13 +194,13 @@ extern void mutex_lock_io(struct mutex *lock);* * Returns 1 if the mutex has been acquired successfully, and 0 on contention. */ -extern int mutex_trylock (struct mutex *lock); -extern void mutex_unlock (struct mutex *lock); +extern int mutex_trylock(struct mutex *lock) __cond_acquires(true, 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) == 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) == 0)#endif /* __LINUX_MUTEX_H */
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 { +struct_with_capability (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 { +struct_with_capability (mutex) {struct rt_mutex_base rtmutex;#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;
lib/test_capability-analysis.c +64 -0
73 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 11/34 locking/seqlock: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability analysis for seqlock_t.
--- .../dev-tools/capability-analysis.rst | 2 +- include/linux/seqlock.h | 24 +++++++++++ include/linux/seqlock_types.h | 5 ++- lib/test_capability-analysis.c | 43 +++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/seqlock.h +24 -0
@@ -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); \ +__assert_cap (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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_analysis {spin_unlock_irq (&sl->lock); }static inline unsigned long __read_seqlock_excl_irqsave (seqlock_t *sl) +__acquires_shared (sl) __no_capability_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_capability_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_capability_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_capability_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_capability_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_capability_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_capability_analysis {if (seq &1 )read_sequnlock_excl_irqrestore (lock, flags);
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 { +struct_with_capability (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_capability-analysis.c +43 -0
52 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 12/34 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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 13/34 bit_spinlock: Support Clang's capability 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 capability analysis is more precise, and we need to ensure we can distinguish different bitlocks.
To do so, add a token capability, 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.
--- .../dev-tools/capability-analysis.rst | 3 ++- include/linux/bit_spinlock.h | 22 +++++++++++++--- include/linux/list_bl.h | 2 ++ lib/test_capability-analysis.c | 26 +++++++++++++++++++ 4 files changed, 48 insertions(+), 5 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/bit_spinlock.h +18 -4
@@ -9,6 +9,16 @@#include <asm/processor.h> /* for cpu_relax() */ +/* +* For static capability 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 capability 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. +*/ +struct_with_capability (__capability_bitlock) { }; +#define __bitlock (bitnum, addr) (struct __capability_bitlock *)(bitnum + (addr)) +/* * bit-based spin_lock() *
@@ -16,6 +26,7 @@* are significantly faster. */ static 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 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 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 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 inline int bit_spin_trylock(int bitnum, unsigned long *addr)* bit-based spin_unlock() */ static 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 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 inline void bit_spin_unlock(int bitnum, unsigned long *addr)* protecting the rest of the flags in the word. */ static 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 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_capability-analysis.c +26 -0
@@ -4,6 +4,7 @@* positive errors when compiled with Clang's capability analysis. */ +#include <linux/bit_spinlock.h> #include <linux/build_bug.h> #include <linux/mutex.h> #include <linux/seqlock.h>
@@ -251,3 +252,28 @@ static void __used test_seqlock_writer(struct test_seqlock_data *d) d->counter++;write_sequnlock_irqrestore (&d->sl, flags); } + +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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 14/34 rcu: Support Clang's capability analysis
In reply to Marco ElverImprove the existing annotations to properly support Clang's capability 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 capabilities to denote more generally that "IRQ", "BH", "PREEMPT" are disabled, it would make sense to acquire these capabilities instead of RCU_BH and RCU_SCHED respectively.
The above change also simplified introducing __guarded_by support, where only the "RCU" capability needs to be held: introduce __rcu_guarded, where Clang's capability analysis warns if a pointer is dereferenced without any of the RCU locks held, or updated without the appropriate helpers.
| Note: A limitation of the compiler's analysis is re-entrancy; a pattern | such as the below will result in a warning: | | rcu_read_lock(); // acquires RCU | .. | rcu_read_lock_bh(); // error: acquiring __capability_RCU 'RCU' that is already held | .. | rcu_read_unlock_bh(); // releases RCU | .. | rcu_read_unlock(); // error: releasing __capability_RCU 'RCU' that was not held | | Such patterns should generally be uncommon, and initial usage in enabled | subsystems did not result in any false positives due to re-entrancy. | Until the compiler supports re-entrancy, keeping the analysis disabled | for code relying on re-entrancy is the only option.
The primitives rcu_assign_pointer() and friends are wrapped with capability_unsafe(), which enforces using them to update RCU-protected pointers marked with __rcu_guarded.
---
v2:
* Reword commit message and point out re-entrancy caveat.
--- .../dev-tools/capability-analysis.rst | 2 +- include/linux/cleanup.h | 4 + include/linux/rcupdate.h | 73 +++++++++++++------ lib/test_capability-analysis.c | 68 +++++++++++++++++ 4 files changed, 123 insertions(+), 24 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/cleanup.h +4 -0
@@ -404,6 +404,10 @@ static 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 +#define DEFINE_LOCK_GUARD_1 (_name, _type, _lock, _unlock, ...) \ __DEFINE_CLASS_IS_CONDITIONAL(_name, false); \ __DEFINE_UNLOCK_GUARD(_name, _type, _unlock, __VA_ARGS__) \
include/linux/rcupdate.h +50 -23
216 lines not on this page · raw message
lib/test_capability-analysis.c +68 -0
77 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 15/34 srcu: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability analysis for SRCU.
--- .../dev-tools/capability-analysis.rst | 2 +- include/linux/srcu.h | 61 +++++++++++++------ lib/test_capability-analysis.c | 24 ++++++++ 3 files changed, 66 insertions(+), 21 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/srcu.h +41 -20
161 lines not on this page · raw message
lib/test_capability-analysis.c +24 -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.
@@ -345,3 +346,26 @@ 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); +}
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 16/34 kref: Add capability-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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 17/34 locking/rwsem: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability analysis for rw_semaphore.
--- .../dev-tools/capability-analysis.rst | 2 +- include/linux/rwsem.h | 56 +++++++++------- lib/test_capability-analysis.c | 64 +++++++++++++++++++ 3 files changed, 97 insertions(+), 25 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/rwsem.h +32 -24
158 lines not on this page · raw message
lib/test_capability-analysis.c +64 -0
76 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 18/34 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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 19/34 locking/local_lock: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability analysis for local_lock_t.
--- .../dev-tools/capability-analysis.rst | 2 +- include/linux/local_lock.h | 18 ++++---- include/linux/local_lock_internal.h | 41 ++++++++++++++--- lib/test_capability-analysis.c | 46 +++++++++++++++++++ 4 files changed, 90 insertions(+), 17 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/local_lock.h +9 -9
@@ -51,12 +51,12 @@#define local_unlock_irqrestore (lock, flags) \ __local_unlock_irqrestore(lock, flags) -DEFINE_GUARD(local_lock, local_lock_t __percpu*, -local_lock (_T), - local_unlock(_T)) -DEFINE_GUARD(local_lock_irq, local_lock_t __percpu*, -local_lock_irq (_T), - local_unlock_irq(_T)) +DEFINE_LOCK_GUARD_1 (local_lock, local_lock_t__percpu , +local_lock (_T->lock), + local_unlock(_T->lock)) +DEFINE_LOCK_GUARD_1 (local_lock_irq, local_lock_t__percpu , +local_lock_irq (_T->lock), + local_unlock_irq(_T->lock)) DEFINE_LOCK_GUARD_1(local_lock_irqsave, local_lock_t __percpu, local_lock_irqsave(_T->lock, _T->flags), local_unlock_irqrestore(_T->lock, _T->flags),
@@ -68,8 +68,8 @@ DEFINE_LOCK_GUARD_1(local_lock_irqsave, local_lock_t __percpu,#define local_unlock_nested_bh (_lock) \ __local_unlock_nested_bh(_lock) -DEFINE_GUARD(local_lock_nested_bh, local_lock_t __percpu*, -local_lock_nested_bh (_T), - local_unlock_nested_bh(_T)) +DEFINE_LOCK_GUARD_1 (local_lock_nested_bh, local_lock_t__percpu , +local_lock_nested_bh (_T->lock), + local_unlock_nested_bh(_T->lock))#endif
include/linux/local_lock_internal.h +34 -7
137 lines not on this page · raw message
lib/test_capability-analysis.c +46 -0
56 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 20/34 locking/ww_mutex: Support Clang's capability analysis
In reply to Marco ElverAdd support for Clang's capability 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 capability analysis makes incorrect use of the API harder.
---
v2:
* New patch.
--- .../dev-tools/capability-analysis.rst | 3 +- include/linux/ww_mutex.h | 21 ++++-- lib/test_capability-analysis.c | 65 +++++++++++++++++++ 3 files changed, 82 insertions(+), 7 deletions(-)
Documentation/dev-tools/capability-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 capabilities with an initialization function (e.g., `spin_lock_init()`), calling this function on the capability instance before initializing any
include/linux/ww_mutex.h +15 -6
@@ -44,7 +44,7 @@ struct ww_class {unsigned int is_wait_die; }; -struct ww_mutex { +struct_with_capability (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 { +struct_with_capability (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) +__asserts_cap (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_capability_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_capability_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_capability_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_capability_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
lib/test_capability-analysis.c +65 -0
74 lines not on this page · raw message
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 21/34 debugfs: Make debugfs_cancellation a capability struct
In reply to Marco ElverWhen compiling include/linux/debugfs.h with CAPABILITY_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 capability to benefit from Clang's capability analysis.
--- include/linux/debugfs.h | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-)
include/linux/debugfs.h +5 -7
@@ -240,18 +240,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 { +struct_with_capability (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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 22/34 compiler-capability-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 capability analysis, these places will show up and need adjustment or removal of the workarounds altogether.
---
v2:
* New patch.
--- Documentation/dev-tools/sparse.rst | 19 ------- include/linux/compiler-capability-analysis.h | 56 ++++++-------------- include/linux/rcupdate.h | 15 +----- 3 files changed, 17 insertions(+), 73 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-capability-analysis.h +16 -40
152 lines not on this page · raw message
include/linux/rcupdate.h +1 -14
@@ -1183,20 +1183,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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 23/34 compiler-capability-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.
---
v2:
* New patch.
--- .../dev-tools/capability-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 +- .../wireless/intel/iwlwifi/pcie/internal.h | 5 +- .../net/wireless/intel/iwlwifi/pcie/trans.c | 4 +- include/linux/compiler-capability-analysis.h | 41 ------------- 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 | 10 +-- lib/dec_and_lock.c | 8 +-- mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +++--- tools/include/linux/compiler_types.h | 2 - 22 files changed, 160 insertions(+), 200 deletions(-)
Documentation/dev-tools/capability-analysis.rst +0 -2
@@ -113,10 +113,8 @@ Keywords __releases_shared __acquire __release - __cond_lock __acquire_shared __release_shared - __cond_lock_shared capability_unsafe __capability_unsafe disable_capability_analysis enable_capability_analysis
Documentation/mm/process_addrs.rst +3 -3
@@ -540,7 +540,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 ^^^^^^^^^
@@ -624,7 +624,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,
@@ -643,7 +643,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
@@ -528,11 +528,11 @@ int iwl_trans_read_config32(struct iwl_trans *trans, u32 ofs, }IWL_EXPORT_SYMBOL (iwl_trans_read_config32); -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
@@ -1133,11 +1133,7 @@ int iwl_trans_sw_reset(struct iwl_trans *trans, bool retake_ownership);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/internal.h +1 -4
@@ -558,10 +558,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); -#define _iwl_trans_pcie_grab_nic_access (trans) \ - __cond_lock(nic_access_nobh, \ - likely(__iwl_trans_pcie_grab_nic_access(trans))) +bool _iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans);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/trans.c +2 -2
@@ -2405,7 +2405,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 _iwl_trans_pcie_grab_nic_access (struct iwl_trans *trans) {int ret;struct iwl_trans_pcie *trans_pcie =IWL_TRANS_GET_PCIE_TRANS (trans);
@@ -2488,7 +2488,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); + ret =_iwl_trans_pcie_grab_nic_access (trans);if (ret) {/* keep BHs disabled until iwl_trans_pcie_release_nic_access */ return ret;
include/linux/compiler-capability-analysis.h +0 -41
63 lines not on this page · raw message
include/linux/mm.h +5 -28
@@ -2732,15 +2732,8 @@ static inline int pte_devmap(pte_t pte) }#endif -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,
@@ -3023,31 +3016,15 @@ static inline bool pagetable_pte_ctor(struct ptdesc *ptdesc)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
@@ -732,18 +732,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
@@ -1354,8 +1354,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 +1 -9
@@ -59,14 +59,6 @@ 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,unsigned long *flags); - -#define lock_timer (tid, flags) \ -({ struct k_itimer *__timr; \ - __cond_lock(&__timr->it_lock, __timr = __lock_timer(tid, flags)); \ - __timr; \ -}) -static int hash (struct signal_struct *sig,unsigned int nr) {return hash_32 (hash32_ptr (sig) ^ nr,HASH_BITS (posix_timers_hashtable));
@@ -507,7 +499,7 @@ COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock, }#endif -static struct k_itimer *__lock_timer (timer_t timer_id,unsigned long *flags) +static struct k_itimer *lock_timer (timer_t timer_id,unsigned long *flags) {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)
mm/memory.c +2 -2
@@ -2076,8 +2076,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
@@ -279,7 +279,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;
@@ -331,13 +331,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
@@ -388,8 +387,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.48.1.711.g2feabab25a-goog
Re: [PATCH v2 23/34] compiler-capability-analysis: Remove __cond_lock() function-like helper
Quoted 15 lines · Marco Elver
.../dev-tools/capability-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 +- .../wireless/intel/iwlwifi/pcie/internal.h | 5 +- .../net/wireless/intel/iwlwifi/pcie/trans.c | 4 +- include/linux/compiler-capability-analysis.h | 41 ------------- 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 | 10 +-- lib/dec_and_lock.c | 8 +-- mm/memory.c | 4 +- mm/pgtable-generic.c | 19 +++--- tools/include/linux/compiler_types.h | 2 - 22 files changed, 160 insertions(+), 200 deletions(-)
Should this patch perhaps be split in one patch per subsystem (mm, iwlwifi, rwlock, signal, spinlock, time)? Would that make it more likely that subsystem maintainers review this work? Can this patch be moved to
the start of this series? Anyway, if others are fine with this patch and its position in this patch series I'm also fine with this patch.
Thanks,
Bart.
Marco Elver
maintainerPATCH v2 24/34 compiler-capability-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_capability_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 capability analysis, suppress all -Wthread-safety warnings in headers. Explicitly opt in headers with capability-enabled primitives.
This bumps the required Clang version to version 20+.
With this in place, we can start enabling the analysis on more complex subsystems in subsequent changes.
--- .../dev-tools/capability-analysis.rst | 2 ++ lib/Kconfig.debug | 4 ++- scripts/Makefile.capability-analysis | 4 +++ scripts/capability-analysis-suppression.txt | 32 +++++++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 scripts/capability-analysis-suppression.txt
Documentation/dev-tools/capability-analysis.rst +2 -0
@@ -17,6 +17,8 @@ features. To enable for Clang, configure the kernel with:: CONFIG_WARN_CAPABILITY_ANALYSIS=y +The feature requires Clang 20 or later. + The analysis is *opt-in by default*, and requires declaring which modules and subsystems should be analyzed in the respective `Makefile`::
lib/Kconfig.debug +3 -1
@@ -605,7 +605,7 @@ config DEBUG_FORCE_WEAK_PER_CPU config WARN_CAPABILITY_ANALYSIS bool "Compiler capability-analysis warnings" - depends on CC_IS_CLANG && $(cc-option,-Wthread-safety -fexperimental-late-parse-attributes) + depends on CC_IS_CLANG && $(cc-option,-Wthread-safety -fexperimental-late-parse-attributes --warning-suppression-mappings=/dev/null) # 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
@@ -619,6 +619,8 @@ config WARN_CAPABILITY_ANALYSIS the original name of the feature; it was later expanded to be a generic "Capability Analysis" framework. + Requires Clang 20 or later. + Produces warnings by default. Select CONFIG_WERROR if you wish to turn these warnings into errors.
scripts/Makefile.capability-analysis +4 -0
@@ -4,4 +4,8 @@ capability-analysis-cflags := -DWARN_CAPABILITY_ANALYSIS \ -fexperimental-late-parse-attributes -Wthread-safety \ $(call cc-option,-Wthread-safety-pointer) +ifndef CONFIG_WARN_CAPABILITY_ANALYSIS_ALL +capability-analysis-cflags += --warning-suppression-mappings=$(srctree)/scripts/capability-analysis-suppression.txt +endif + export CFLAGS_CAPABILITY_ANALYSIS := $(capability-analysis-cflags)
scripts/capability-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 CAPABILITY_ANALYSIS := [yn]. +# +# The suppressions are ignored when CONFIG_WARN_CAPABILITY_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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 25/34 compiler: Let data_race() imply disabled capability 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 capability_unsafe(data_race(..)), simply make the data_race(..) macro imply capability-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.
---
v2:
* New patch.
--- include/linux/compiler.h | 2 ++ lib/test_capability-analysis.c | 2 ++ 2 files changed, 4 insertions(+)
include/linux/compiler.h +2 -0
@@ -186,7 +186,9 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val,#define data_race (expr) \ ({ \ __kcsan_disable_current(); \ + disable_capability_analysis(); \ __auto_type __v = (expr); \ + enable_capability_analysis(); \ __kcsan_enable_current(); \ __v; \ })
lib/test_capability-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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 26/34 kfence: Enable capability analysis
In reply to Marco ElverEnable capability 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.
---
v2:
* Remove disable/enable_capability_analysis() around headers.
* Use __capability_unsafe() instead of __no_capability_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 +CAPABILITY_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
@@ -132,8 +132,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
@@ -253,6 +253,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];
@@ -288,6 +289,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;
@@ -485,7 +487,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 ;
@@ -514,6 +516,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;
@@ -546,9 +549,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);
@@ -593,6 +597,7 @@ static void rcu_guarded_free(struct rcu_head *h)* which partial initialization succeeded. */ static unsigned long kfence_init_pool (void ) +__capability_unsafe (/* constructor */ ) {unsigned long addr;struct page *pages;
@@ -1192,6 +1197,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;
@@ -1225,9 +1231,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
@@ -1239,7 +1244,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
@@ -1251,6 +1255,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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 27/34 kcov: Enable capability analysis
In reply to Marco ElverEnable capability analysis for the KCOV subsystem.
---
v2:
* Remove disable/enable_capability_analysis() around headers.
--- kernel/Makefile | 2 ++ kernel/kcov.c | 36 +++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-)
kernel/Makefile +2 -0
@@ -39,6 +39,8 @@ KASAN_SANITIZE_kcov.o := n KCSAN_SANITIZE_kcov.o := n UBSAN_SANITIZE_kcov.o := n KMSAN_SANITIZE_kcov.o := n + +CAPABILITY_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); +/* Capability-safety: no references left, object being destroyed. */ +capability_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; +unsigned long *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 =capability_unsafe (kcov->mode); sequence = kcov->sequence;if (in_task ()) { size = kcov->remote_size;
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 28/34 stackdepot: Enable capability analysis
In reply to Marco ElverEnable capability analysis for stackdepot.
---
v2:
* Remove disable/enable_capability_analysis() around headers.
--- lib/Makefile | 1 + lib/stackdepot.c | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-)
lib/Makefile +1 -0
@@ -270,6 +270,7 @@ obj-$(CONFIG_POLYNOMIAL) += polynomial.o # Prevent the compiler from calling builtins like memcmp() or bcmp() from this # file. CFLAGS_stackdepot.o += -fno-builtin +CAPABILITY_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[DEPOT_MAX_POOLS ]; +static void *stack_pools[DEPOT_MAX_POOLS] __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 {
@@ -242,6 +242,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);
@@ -289,6 +290,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);
@@ -308,6 +310,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;
@@ -342,6 +345,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;
@@ -379,6 +383,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;
@@ -437,6 +442,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 };
@@ -453,7 +459,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 =capability_unsafe (stack_pools[pool_index]);if (WARN_ON (!pool))return NULL ;
@@ -466,6 +473,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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 29/34 rhashtable: Enable capability analysis
In reply to Marco ElverEnable capability 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.
---
v2:
* Remove disable/enable_capability_analysis() around headers.
--- include/linux/rhashtable.h | 14 +++++++++++--- lib/Makefile | 2 ++ lib/rhashtable.c | 5 +++-- 3 files changed, 16 insertions(+), 5 deletions(-)
include/linux/rhashtable.h +11 -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);
@@ -402,13 +406,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); }
@@ -589,6 +594,7 @@ static inline int rhashtable_compare(struct rhashtable_compare_arg *arg,static inline struct rhash_head *__rhashtable_lookup (struct rhashtable *ht,const void *key,const struct rhashtable_params params) +__must_hold_shared (RCU ) {struct rhashtable_compare_arg arg = { .ht = ht,
@@ -642,6 +648,7 @@ static inline struct rhash_head *__rhashtable_lookup(static 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);
@@ -692,6 +699,7 @@ static inline void *rhashtable_lookup_fast(static 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);
lib/Makefile +2 -0
@@ -45,6 +45,8 @@ lib-$(CONFIG_MIN_HEAP) += min_heap.o lib-y += kobject.o klist.o obj-y += lockref.o +CAPABILITY_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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 30/34 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. Capability analysis remains disabled for printk.c.
This is needed to enable capability 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
@@ -488,8 +488,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
@@ -244,6 +244,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(),
@@ -268,6 +269,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.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 31/34 drivers/tty: Enable capability analysis for core files
In reply to Marco ElverEnable capability analysis for drivers/tty/*.
This demonstrates a larger conversion to use Clang's capability analysis. The benefit is additional static checking of locking rules, along with better documentation.
---
v2:
* New patch.
--- drivers/tty/Makefile | 3 +++ drivers/tty/n_tty.c | 16 ++++++++++++++++ drivers/tty/pty.c | 1 + drivers/tty/sysrq.c | 1 + drivers/tty/tty.h | 8 ++++---- drivers/tty/tty_buffer.c | 8 +++----- drivers/tty/tty_io.c | 12 +++++++++--- drivers/tty/tty_ioctl.c | 2 +- drivers/tty/tty_ldisc.c | 35 ++++++++++++++++++++++++++++++++--- drivers/tty/tty_ldsem.c | 2 ++ drivers/tty/tty_mutex.c | 4 ++++ drivers/tty/tty_port.c | 2 ++ include/linux/tty.h | 14 +++++++------- include/linux/tty_flip.h | 4 ++-- include/linux/tty_ldisc.h | 19 ++++++++++--------- 15 files changed, 97 insertions(+), 34 deletions(-)
drivers/tty/Makefile +3 -0
@@ -1,4 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 + +CAPABILITY_ANALYSIS := y + obj-$(CONFIG_TTY) += tty_io.o n_tty.o tty_ioctl.o tty_ldisc.o \ tty_buffer.o tty_port.o tty_mutex.o \ tty_ldsem.o tty_baudrate.o tty_jobctrl.o \
drivers/tty/n_tty.c +16 -0
@@ -1088,6 +1088,7 @@ static void __isig(int sig, struct tty_struct *tty)* Locking: %ctrl.lock */ static void isig (int sig,struct tty_struct *tty) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;
@@ -1135,6 +1136,7 @@ static void isig(int sig, struct tty_struct *tty)* Note: may get exclusive %termios_rwsem if flushing input buffer */ static void n_tty_receive_break (struct tty_struct *tty) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;
@@ -1204,6 +1206,7 @@ static void n_tty_receive_parity_error(const struct tty_struct *tty,static void n_tty_receive_signal_char (struct tty_struct *tty,int signal,u8 c) + __must_hold_shared(&tty->termios_rwsem) {isig (signal, tty);if (I_IXON (tty))
@@ -1353,6 +1356,7 @@ static bool n_tty_receive_char_canon(struct tty_struct *tty, u8 c)static void n_tty_receive_char_special (struct tty_struct *tty,u8 c,bool lookahead_done) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;
@@ -1463,6 +1467,7 @@ static void n_tty_receive_char_closing(struct tty_struct *tty, u8 c,static void n_tty_receive_char_flagged (struct tty_struct *tty,u8 c,u8 flag) + __must_hold_shared(&tty->termios_rwsem) {switch (flag) {case TTY_BREAK :
@@ -1483,6 +1488,7 @@ n_tty_receive_char_flagged(struct tty_struct *tty, u8 c, u8 flag)static void n_tty_receive_char_lnext (struct tty_struct *tty,u8 c,u8 flag) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;
@@ -1540,6 +1546,7 @@ n_tty_receive_buf_real_raw(const struct tty_struct *tty, const u8 *cp,static void n_tty_receive_buf_raw (struct tty_struct *tty,const u8 *cp,const u8 *fp,size_t count) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;u8 flag =TTY_NORMAL ;
@@ -1571,6 +1578,7 @@ n_tty_receive_buf_closing(struct tty_struct *tty, const u8 *cp, const u8 *fp,static void n_tty_receive_buf_standard (struct tty_struct *tty,const u8 *cp,const u8 *fp,size_t count,bool lookahead_done) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;u8 flag =TTY_NORMAL ;
@@ -1609,6 +1617,7 @@ static void n_tty_receive_buf_standard(struct tty_struct *tty, const u8 *cp,static void __receive_buf (struct tty_struct *tty,const u8 *cp,const u8 *fp,size_t count) + __must_hold_shared(&tty->termios_rwsem) {struct n_tty_data *ldata = tty->disc_data;bool preops =I_ISTRIP (tty) || (I_IUCLC (tty) &&L_IEXTEN (tty));
@@ -2188,6 +2197,10 @@ static ssize_t n_tty_read(struct tty_struct *tty, struct file *file, u8 *kbuf,return kb - kbuf; } +/* Adopted locks from prior call. */ +__acquire (&ldata->atomic_read_lock); +__acquire_shared (&tty->termios_rwsem); +/* No more data - release locks and stop retries */ n_tty_kick_worker (tty);n_tty_check_unthrottle (tty);
@@ -2305,6 +2318,9 @@ static ssize_t n_tty_read(struct tty_struct *tty, struct file *file, u8 *kbuf, more_to_be_read:remove_wait_queue (&tty->read_wait, &wait); *cookie = cookie; +/* Hand-off locks to retry with cookie set. */ +__release_shared (&tty->termios_rwsem); +__release (&ldata->atomic_read_lock);return kb - kbuf; } }
drivers/tty/pty.c +1 -0
@@ -824,6 +824,7 @@ static int ptmx_open(struct inode *inode, struct file *filp) tty =tty_init_dev (ptm_driver, index);/* The tty returned here is locked so we can safely drop the mutex */ +lockdep_assert_held (&tty->legacy_mutex);mutex_unlock (&tty_mutex); retval =PTR_ERR (tty);
drivers/tty/sysrq.c +1 -0
@@ -149,6 +149,7 @@ static const struct sysrq_key_op sysrq_unraw_op = {static void sysrq_handle_crash (u8 key) {/* release the RCU read lock before crashing */ +lockdep_assert_in_rcu_read_lock ();rcu_read_unlock ();panic ("sysrq triggered crash\n" );
drivers/tty/tty.h +4 -4
@@ -60,15 +60,15 @@ static inline void tty_set_flow_change(struct tty_struct *tty,smp_mb (); } -int tty_ldisc_lock (struct tty_struct *tty,unsigned long timeout); -void tty_ldisc_unlock (struct tty_struct *tty); +int tty_ldisc_lock(struct tty_struct *tty, unsigned long timeout) __cond_acquires(0, &tty->ldisc_sem); +void tty_ldisc_unlock(struct tty_struct *tty) __releases(&tty->ldisc_sem);int __tty_check_change (struct tty_struct *tty,int sig);int tty_check_change (struct tty_struct *tty);void __stop_tty (struct tty_struct *tty);void __start_tty (struct tty_struct *tty); -void tty_write_unlock (struct tty_struct *tty); -int tty_write_lock (struct tty_struct *tty,bool ndelay); +void tty_write_unlock(struct tty_struct *tty) __releases(&tty->atomic_write_lock); +int tty_write_lock(struct tty_struct *tty, bool ndelay) __cond_acquires(0, &tty->atomic_write_lock);void tty_vhangup_session (struct tty_struct *tty);void tty_open_proc_set_tty (struct file *filp,struct tty_struct *tty);int tty_signal_session_leader (struct tty_struct *tty,int exit_session);
drivers/tty/tty_buffer.c +3 -5
@@ -52,10 +52,8 @@*/ void tty_buffer_lock_exclusive (struct tty_port *port) { -struct tty_bufhead *buf = &port->buf; - -atomic_inc (&buf->priority); -mutex_lock (&buf->lock); +atomic_inc (&port->buf.priority); +mutex_lock (&port->buf.lock); }EXPORT_SYMBOL_GPL (tty_buffer_lock_exclusive);
@@ -73,7 +71,7 @@ void tty_buffer_unlock_exclusive(struct tty_port *port)bool restart = buf->head->commit != buf->head->read;atomic_dec (&buf->priority); -mutex_unlock (&buf->lock); +mutex_unlock (&port->buf.lock);if (restart)queue_work (system_unbound_wq, &buf->work);
drivers/tty/tty_io.c +9 -3
@@ -167,6 +167,7 @@ static void release_tty(struct tty_struct *tty, int idx);* Locking: none. Must be called after tty is definitely unused */ static void free_tty_struct (struct tty_struct *tty) +__capability_unsafe (/* destructor */ ) {tty_ldisc_deinit (tty);put_device (tty->dev);
@@ -965,7 +966,7 @@ static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty,ssize_t ret, written =0 ; ret =tty_write_lock (tty, file->f_flags &O_NDELAY ); -if (ret <0 ) +if (ret)return ret;/*
@@ -1154,7 +1155,7 @@ int tty_send_xchar(struct tty_struct *tty, u8 ch)return 0 ; } -if (tty_write_lock (tty, false) <0 ) +if (tty_write_lock (tty, false))return -ERESTARTSYS ;down_read (&tty->termios_rwsem);
@@ -1391,6 +1392,7 @@ static int tty_reopen(struct tty_struct *tty)* Return: new tty structure */ struct tty_struct *tty_init_dev (struct tty_driver *driver,int idx) +__capability_unsafe (/* returns with locked tty */ ) {struct tty_struct *tty;int retval;
@@ -1874,6 +1876,7 @@ int tty_release(struct inode *inode, struct file *filp)* will not work then. It expects inodes to be from devpts FS. */ static struct tty_struct *tty_open_current_tty (dev_t device,struct file *filp) +__capability_unsafe (/* returns with locked tty */ ) {struct tty_struct *tty;int retval;
@@ -2037,6 +2040,7 @@ EXPORT_SYMBOL_GPL(tty_kopen_shared);*/ static struct tty_struct *tty_open_by_driver (dev_t device,struct file *filp) +__capability_unsafe (/* returns with locked tty */ ) {struct tty_struct *tty;struct tty_driver *driver =NULL ;
@@ -2137,6 +2141,8 @@ static int tty_open(struct inode *inode, struct file *filp) goto retry_open; } +lockdep_assert_held (&tty->legacy_mutex); +tty_add_file (tty, filp);check_tty_count (tty, __func__);
@@ -2486,7 +2492,7 @@ static int send_break(struct tty_struct *tty, unsigned int duration)return tty->ops->break_ctl (tty, duration);/* Do the work ourselves */ -if (tty_write_lock (tty, false) <0 ) +if (tty_write_lock (tty, false))return -EINTR ; retval = tty->ops->break_ctl (tty,-1 );
drivers/tty/tty_ioctl.c +1 -1
@@ -489,7 +489,7 @@ static int set_termios(struct tty_struct *tty, void __user *arg, int opt)if (retval <0 )return retval; -if (tty_write_lock (tty, false) <0 ) +if (tty_write_lock (tty, false)) goto retry_write_wait;/* Racing writer? */
drivers/tty/tty_ldisc.c +32 -3
@@ -237,6 +237,7 @@ const struct seq_operations tty_ldiscs_seq_ops = {* to wait for any ldisc lifetime events to finish. */ struct tty_ldisc *tty_ldisc_ref_wait (struct tty_struct *tty) + __cond_acquires_shared(nonnull, &tty->ldisc_sem) {struct tty_ldisc *ld;
@@ -257,6 +258,7 @@ EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait);* and timer functions. */ struct tty_ldisc *tty_ldisc_ref (struct tty_struct *tty) + __cond_acquires_shared(nonnull, &tty->ldisc_sem) {struct tty_ldisc *ld =NULL ;
@@ -277,26 +279,43 @@ EXPORT_SYMBOL_GPL(tty_ldisc_ref);* in IRQ context. */ void tty_ldisc_deref (struct tty_ldisc *ld) + __releases_shared(&ld->tty->ldisc_sem) {ldsem_up_read (&ld->tty->ldisc_sem); }EXPORT_SYMBOL_GPL (tty_ldisc_deref); +/* +* Note: Capability analysis does not like asymmetric interfaces (above types +* for ref and deref are tty_struct and tty_ldisc respectively -- which are +* dependent, but the compiler cannot figure that out); in this case, work +* around that with this helper which takes an unused @tty argument but tells +* the analysis which lock is released. +*/ +static inline void __tty_ldisc_deref (struct tty_struct *tty,struct tty_ldisc *ld) + __releases_shared(&tty->ldisc_sem) +__capability_unsafe (/* matches released with tty_ldisc_ref() */ ) +{ +tty_ldisc_deref (ld); +}static inline int __tty_ldisc_lock (struct tty_struct *tty,unsigned long timeout) + __cond_acquires(true, &tty->ldisc_sem) {return ldsem_down_write (&tty->ldisc_sem, timeout); }static inline int __tty_ldisc_lock_nested (struct tty_struct *tty,unsigned long timeout) + __cond_acquires(true, &tty->ldisc_sem) {return ldsem_down_write_nested (&tty->ldisc_sem,LDISC_SEM_OTHER , timeout); }static inline void __tty_ldisc_unlock (struct tty_struct *tty) + __releases(&tty->ldisc_sem) {ldsem_up_write (&tty->ldisc_sem); }
@@ -328,6 +347,8 @@ void tty_ldisc_unlock(struct tty_struct *tty)static int tty_ldisc_lock_pair_timeout (struct tty_struct *tty,struct tty_struct *tty2,unsigned long timeout) + __cond_acquires(0, &tty->ldisc_sem) + __cond_acquires(0, &tty2->ldisc_sem) {int ret;
@@ -362,16 +383,23 @@ tty_ldisc_lock_pair_timeout(struct tty_struct *tty, struct tty_struct *tty2, }static void tty_ldisc_lock_pair (struct tty_struct *tty,struct tty_struct *tty2) + __acquires(&tty->ldisc_sem) + __acquires(&tty2->ldisc_sem) +__capability_unsafe (/* MAX_SCHEDULE_TIMEOUT ensures acquisition */ ) {tty_ldisc_lock_pair_timeout (tty, tty2,MAX_SCHEDULE_TIMEOUT ); }static void tty_ldisc_unlock_pair (struct tty_struct *tty,struct tty_struct *tty2) + __releases(&tty->ldisc_sem) + __releases(&tty2->ldisc_sem) {__tty_ldisc_unlock (tty);if (tty2)__tty_ldisc_unlock (tty2); +else +__release (&tty2->ldisc_sem); }/**
@@ -387,7 +415,7 @@ void tty_ldisc_flush(struct tty_struct *tty)tty_buffer_flush (tty, ld);if (ld) -tty_ldisc_deref (ld); +__tty_ldisc_deref (tty, ld); }EXPORT_SYMBOL_GPL (tty_ldisc_flush);
@@ -694,7 +722,7 @@ void tty_ldisc_hangup(struct tty_struct *tty, bool reinit)tty_ldisc_debug (tty,"%p: hangup\n" , tty->ldisc); ld =tty_ldisc_ref (tty); -if (ld !=NULL ) { +if (ld) {if (ld->ops->flush_buffer) ld->ops->flush_buffer (tty);tty_driver_flush_buffer (tty);
@@ -703,7 +731,7 @@ void tty_ldisc_hangup(struct tty_struct *tty, bool reinit) ld->ops->write_wakeup (tty);if (ld->ops->hangup) ld->ops->hangup (tty); -tty_ldisc_deref (ld); +__tty_ldisc_deref (tty, ld); }wake_up_interruptible_poll (&tty->write_wait,EPOLLOUT );
@@ -716,6 +744,7 @@ void tty_ldisc_hangup(struct tty_struct *tty, bool reinit)* Avoid racing set_ldisc or tty_ldisc_release */ tty_ldisc_lock (tty,MAX_SCHEDULE_TIMEOUT ); +lockdep_assert_held_write (&tty->ldisc_sem);if (tty->driver->flags &TTY_DRIVER_RESET_TERMIOS )tty_reset_termios (tty);
drivers/tty/tty_ldsem.c +2 -0
@@ -390,6 +390,7 @@ void ldsem_up_read(struct ld_semaphore *sem) {long count; +__release_shared (sem);rwsem_release (&sem->dep_map, _RET_IP_); count =atomic_long_add_return (-LDSEM_READ_BIAS , &sem->count);
@@ -404,6 +405,7 @@ void ldsem_up_write(struct ld_semaphore *sem) {long count; +__release (sem);rwsem_release (&sem->dep_map, _RET_IP_); count =atomic_long_add_return (-LDSEM_WRITE_BIAS , &sem->count);
drivers/tty/tty_mutex.c +4 -0
@@ -41,12 +41,16 @@ void tty_lock_slave(struct tty_struct *tty) {if (tty && tty != tty->link)tty_lock (tty); +else +__acquire (&tty->legacy_mutex); }void tty_unlock_slave (struct tty_struct *tty) {if (tty && tty != tty->link)tty_unlock (tty); +else +__release (&tty->legacy_mutex); }void tty_set_lock_subclass (struct tty_struct *tty)
drivers/tty/tty_port.c +2 -0
@@ -509,6 +509,7 @@ EXPORT_SYMBOL(tty_port_lower_dtr_rts);*/ int tty_port_block_til_ready (struct tty_port *port,struct tty_struct *tty,struct file *filp) + __must_hold(&tty->legacy_mutex) {int do_clocal =0 , retval;unsigned long flags;
@@ -764,6 +765,7 @@ EXPORT_SYMBOL_GPL(tty_port_install);*/ int tty_port_open (struct tty_port *port,struct tty_struct *tty,struct file *filp) + __must_hold(&tty->legacy_mutex) {spin_lock_irq (&port->lock); ++port->count;
include/linux/tty.h +7 -7
@@ -234,8 +234,8 @@ struct tty_struct {void *disc_data;void *driver_data;spinlock_t files_lock; -int write_cnt; -u8 *write_buf; + int write_cnt __guarded_by(&atomic_write_lock); + u8 *write_buf __guarded_by(&atomic_write_lock);struct list_head tty_files;
@@ -500,11 +500,11 @@ long vt_compat_ioctl(struct tty_struct *tty, unsigned int cmd,/* tty_mutex.c */ /* functions for preparation of BKL removal */ -void tty_lock (struct tty_struct *tty); -int tty_lock_interruptible (struct tty_struct *tty); -void tty_unlock (struct tty_struct *tty); -void tty_lock_slave (struct tty_struct *tty); -void tty_unlock_slave (struct tty_struct *tty); +void tty_lock(struct tty_struct *tty) __acquires(&tty->legacy_mutex); +int tty_lock_interruptible(struct tty_struct *tty) __cond_acquires(0, &tty->legacy_mutex); +void tty_unlock(struct tty_struct *tty) __releases(&tty->legacy_mutex); +void tty_lock_slave(struct tty_struct *tty) __acquires(&tty->legacy_mutex); +void tty_unlock_slave(struct tty_struct *tty) __releases(&tty->legacy_mutex);void tty_set_lock_subclass (struct tty_struct *tty);#endif
include/linux/tty_flip.h +2 -2
@@ -86,7 +86,7 @@ static inline size_t tty_insert_flip_string(struct tty_port *port,size_t tty_ldisc_receive_buf (struct tty_ldisc *ld,const u8 *p,const u8 *f,size_t count); -void tty_buffer_lock_exclusive (struct tty_port *port); -void tty_buffer_unlock_exclusive (struct tty_port *port); +void tty_buffer_lock_exclusive(struct tty_port *port) __acquires(&port->buf.lock); +void tty_buffer_unlock_exclusive(struct tty_port *port) __releases(&port->buf.lock);#endif /* _LINUX_TTY_FLIP_H */
include/linux/tty_ldisc.h +10 -9
@@ -14,7 +14,7 @@ struct tty_struct;/* * the semaphore definition */ -struct ld_semaphore { +struct_with_capability (ld_semaphore) {atomic_long_t count;raw_spinlock_t wait_lock;unsigned int wait_readers;
@@ -33,21 +33,22 @@ do { \static struct lock_class_key __key; \ \ __init_ldsem((sem), #sem, &__key); \ +__assert_cap (sem); \ }while (0 ) -int ldsem_down_read (struct ld_semaphore *sem,long timeout); -int ldsem_down_read_trylock (struct ld_semaphore *sem); -int ldsem_down_write (struct ld_semaphore *sem,long timeout); -int ldsem_down_write_trylock (struct ld_semaphore *sem); -void ldsem_up_read (struct ld_semaphore *sem); -void ldsem_up_write (struct ld_semaphore *sem); +int ldsem_down_read(struct ld_semaphore *sem, long timeout) __cond_acquires_shared(true, sem); +int ldsem_down_read_trylock(struct ld_semaphore *sem) __cond_acquires_shared(true, sem); +int ldsem_down_write(struct ld_semaphore *sem, long timeout) __cond_acquires(true, sem); +int ldsem_down_write_trylock(struct ld_semaphore *sem) __cond_acquires(true, sem); +void ldsem_up_read(struct ld_semaphore *sem) __releases_shared(sem); +void ldsem_up_write(struct ld_semaphore *sem) __releases(sem);#ifdef CONFIG_DEBUG_LOCK_ALLOC int ldsem_down_read_nested(struct ld_semaphore *sem, int subclass, -long timeout); + long timeout) __cond_acquires_shared(true, sem); int ldsem_down_write_nested(struct ld_semaphore *sem, int subclass, -long timeout); + long timeout) __cond_acquires(true, sem);#else # define ldsem_down_read_nested (sem, subclass, timeout) \ ldsem_down_read(sem, timeout)
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Jiri Slaby
maintainerRe: [PATCH v2 31/34] drivers/tty: Enable capability analysis for core files
Quoted 9 lines · Marco Elver
Enable capability analysis for
drivers/tty/*.This demonstrates a larger conversion to use Clang's capability analysis. The benefit is additional static checking of locking rules, along with better documentation.
Signed-off-by Marco Elver <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Jiri Slaby <[email protected]>
...
drivers/tty/tty_buffer.c line 56
Quoted 12 lines
drivers/tty/tty_buffer.c +2
-4@@ -52,10 +52,8 @@*/ void tty_buffer_lock_exclusive (struct tty_port *port) { -struct tty_bufhead *buf = &port->buf; - -atomic_inc (&buf->priority); -mutex_lock (&buf->lock); +atomic_inc (&port->buf.priority); +mutex_lock (&port->buf.lock);
Here and:
drivers/tty/tty_buffer.c void tty_buffer_unlock_exclusive(struct tty_port *port) · line 74
Quoted 6 lines
drivers/tty/tty_buffer.c +1
-1@@ -73,7 +71,7 @@ void tty_buffer_unlock_exclusive(struct tty_port *port)bool restart = buf->head->commit != buf->head->read;atomic_dec (&buf->priority); -mutex_unlock (&buf->lock); +mutex_unlock (&port->buf.lock);
here, this appears excessive. You are changing code to adapt to one kind of static analysis. Adding function annotations is mostly fine, but changing code is too much. We don't do that. Fix the analyzer instead.
Quoted 11 lines
drivers/tty/tty_io.c +1
-0@@ -167,6 +167,7 @@ static void release_tty(struct tty_struct *tty, int idx);* Locking: none. Must be called after tty is definitely unused */ static void free_tty_struct (struct tty_struct *tty) +__capability_unsafe (/* destructor */ ) {tty_ldisc_deinit (tty);put_device (tty->dev);
drivers/tty/tty_io.c static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty, · line 969
Quoted 5 lines
drivers/tty/tty_io.c +1
-1@@ -965,7 +966,7 @@ static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty,ssize_t ret, written =0 ; ret =tty_write_lock (tty, file->f_flags &O_NDELAY ); -if (ret <0 ) +if (ret)
This change is not documented.
drivers/tty/tty_io.c int tty_send_xchar(struct tty_struct *tty, u8 ch) · line 1158
Quoted 6 lines
drivers/tty/tty_io.c +1
-1@@ -1154,7 +1155,7 @@ int tty_send_xchar(struct tty_struct *tty, u8 ch)return 0 ; } -if (tty_write_lock (tty, false) <0 ) +if (tty_write_lock (tty, false))
And this one. And more times later.
Quoted 2 lines
drivers/tty/tty_ldisc.c +0
-0
...
drivers/tty/tty_ldisc.c EXPORT_SYMBOL_GPL(tty_ldisc_ref); · line 300
Quoted 13 lines
drivers/tty/tty_ldisc.c +13
-0+/* +* Note: Capability analysis does not like asymmetric interfaces (above types +* for ref and deref are tty_struct and tty_ldisc respectively -- which are +* dependent, but the compiler cannot figure that out); in this case, work +* around that with this helper which takes an unused @tty argument but tells +* the analysis which lock is released. +*/ +static inline void __tty_ldisc_deref (struct tty_struct *tty,struct tty_ldisc *ld) + __releases_shared(&tty->ldisc_sem) +__capability_unsafe (/* matches released with tty_ldisc_ref() */ ) +{ +tty_ldisc_deref (ld); +}
You want to invert the __ prefix for these two. tty_ldisc_deref() should be kept as the one to be called by everybody.
thanks,
Signature · 2 lines
js suse labs
Marco Elver
maintainerRe: [PATCH v2 31/34] drivers/tty: Enable capability analysis for core files
Quoted 30 lines · Jiri Slaby
Quoted 9 lines · Marco Elver
Enable capability analysis for
drivers/tty/*.This demonstrates a larger conversion to use Clang's capability analysis. The benefit is additional static checking of locking rules, along with better documentation.
Signed-off-by Marco Elver <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Jiri Slaby <[email protected]>...
drivers/tty/tty_buffer.c line 56
Quoted 12 lines
drivers/tty/tty_buffer.c +2
-4@@ -52,10 +52,8 @@*/ void tty_buffer_lock_exclusive (struct tty_port *port) { -struct tty_bufhead *buf = &port->buf; - -atomic_inc (&buf->priority); -mutex_lock (&buf->lock); +atomic_inc (&port->buf.priority); +mutex_lock (&port->buf.lock);Here and:
Quoted 3 lines
drivers/tty/tty_buffer.c +0
-0@@ -73,7 +71,7 @@ void tty_buffer_unlock_exclusive(struct tty_port *port)bool restart = buf->head->commit != buf->head->read;
Quoted 7 lines
drivers/tty/tty_buffer.c void tty_buffer_unlock_exclusive(struct tty_port *port) · line 74
Quoted 3 lines
drivers/tty/tty_buffer.c +1
-1atomic_dec (&buf->priority); -mutex_unlock (&buf->lock); +mutex_unlock (&port->buf.lock);here, this appears excessive. You are changing code to adapt to one kind of static analysis. Adding function annotations is mostly fine, but changing code is too much. We don't do that. Fix the analyzer instead.
Right. So the analysis doesn't do alias analysis.
Quoted 13 lines
Quoted 13 lines
drivers/tty/tty_io.c +1
-0@@ -167,6 +167,7 @@ static void release_tty(struct tty_struct *tty, int idx);* Locking: none. Must be called after tty is definitely unused */ static void free_tty_struct (struct tty_struct *tty) +__capability_unsafe (/* destructor */ ) {tty_ldisc_deinit (tty);put_device (tty->dev);@@ -965,7 +966,7 @@ static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty,ssize_t ret, written =0 ;
Quoted 5 lines
drivers/tty/tty_io.c static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty, · line 969
Quoted 3 lines
drivers/tty/tty_io.c +1
-1ret =tty_write_lock (tty, file->f_flags &O_NDELAY ); -if (ret <0 ) +if (ret)This change is not documented.
Fair point. This is because the analysis can only deal with conditional locking when fed into zero/non-zero condition checks.
Quoted 12 lines
drivers/tty/tty_io.c int tty_send_xchar(struct tty_struct *tty, u8 ch) · line 1158
Quoted 6 lines
drivers/tty/tty_io.c +1
-1@@ -1154,7 +1155,7 @@ int tty_send_xchar(struct tty_struct *tty, u8 ch)return 0 ; } -if (tty_write_lock (tty, false) <0 ) +if (tty_write_lock (tty, false))And this one. And more times later.
Quoted 2 lines
drivers/tty/tty_ldisc.c +0
-0...
Quoted 16 lines
drivers/tty/tty_ldisc.c EXPORT_SYMBOL_GPL(tty_ldisc_ref); · line 300
Quoted 13 lines
drivers/tty/tty_ldisc.c +13
-0+/* +* Note: Capability analysis does not like asymmetric interfaces (above types +* for ref and deref are tty_struct and tty_ldisc respectively -- which are +* dependent, but the compiler cannot figure that out); in this case, work +* around that with this helper which takes an unused @tty argument but tells +* the analysis which lock is released. +*/ +static inline void __tty_ldisc_deref (struct tty_struct *tty,struct tty_ldisc *ld) + __releases_shared(&tty->ldisc_sem) +__capability_unsafe (/* matches released with tty_ldisc_ref() */ ) +{ +tty_ldisc_deref (ld); +}You want to invert the __ prefix for these two.
tty_ldisc_deref()should be kept as the one to be called by everybody.
Ack.
I think in the near term the alias analysis issues + conditional check of < 0 aren't solvable. Alias analysis being the bigger issue. Two options:
1. Adding __capability_unsafe to the few functions that you weren't happy with above.
2. Dropping the whole patch.
I'm inclined to drop the whole patch.
Thanks,
-- Marco
Marco Elver
maintainerPATCH v2 32/34 security/tomoyo: Enable capability analysis
In reply to Marco ElverEnable capability analysis for security/tomoyo.
This demonstrates a larger conversion to use Clang's capability analysis. The benefit is additional static checking of locking rules, along with better documentation.
Tomoyo makes use of several synchronization primitives, yet its clear design made it relatively straightforward to enable capability analysis.
One notable finding was:
security/tomoyo/gc.c:664:20: error: reading variable 'write_buf' requires holding mutex '&tomoyo_io_buffer::io_sem'
664 | is_write = head->write_buf != NULL;
For which Tetsuo writes:
"Good catch. This should be data_race(), for tomoyo_write_control()
might concurrently update head->write_buf from non-NULL to non-NULL with head->io_sem held."
---
v2:
* New patch.
--- 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 ++ 9 files changed, 122 insertions(+), 49 deletions(-)
security/tomoyo/Makefile +2 -0
@@ -1,4 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 +CAPABILITY_ANALYSIS := y + obj-y = audit.o common.o condition.o domain.o environ.o file.o gc.o group.o load_policy.o memory.o mount.o network.o realpath.o securityfs_if.o tomoyo.o util.o targets += builtin-policy.h
security/tomoyo/common.c +48 -4
250 lines not on this page · raw message
security/tomoyo/common.h +40 -37
129 lines not on this page · raw message
security/tomoyo/domain.c +1 -0
@@ -611,6 +611,7 @@ struct tomoyo_domain_info *tomoyo_assign_domain(const char *domainname,* Returns 0 on success, negative value otherwise. */ static int tomoyo_environ (struct tomoyo_execve *ee) + __must_hold_shared(&tomoyo_ss) {struct tomoyo_request_info *r = &ee->r;struct linux_binprm *bprm = ee->bprm;
security/tomoyo/environ.c +1 -0
@@ -32,6 +32,7 @@ static bool tomoyo_check_env_acl(struct tomoyo_request_info *r,* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_env_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) {return tomoyo_supervisor (r,"misc env %s\n" , r->param.environ.name->name);
security/tomoyo/file.c +5 -0
@@ -164,6 +164,7 @@ static bool tomoyo_get_realpath(struct tomoyo_path_info *buf, const struct path* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_path_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) { return tomoyo_supervisor(r, "file %s %s\n", tomoyo_path_keyword [r->param.path.operation],
@@ -178,6 +179,7 @@ static int tomoyo_audit_path_log(struct tomoyo_request_info *r)* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_path2_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) { return tomoyo_supervisor(r, "file %s %s %s\n", tomoyo_mac_keywords [tomoyo_pp2mac[r->param.path2.operation]],
@@ -193,6 +195,7 @@ static int tomoyo_audit_path2_log(struct tomoyo_request_info *r)* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_mkdev_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) {return tomoyo_supervisor (r,"file %s %s 0%o %u %u\n" , tomoyo_mac_keywords
@@ -210,6 +213,7 @@ static int tomoyo_audit_mkdev_log(struct tomoyo_request_info *r)* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_path_number_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) {const u8 type = r->param.path_number.operation;u8 radix;
@@ -572,6 +576,7 @@ static int tomoyo_update_path2_acl(const u8 perm,*/ static int tomoyo_path_permission (struct tomoyo_request_info *r,u8 operation,const struct tomoyo_path_info *filename) + __must_hold_shared(&tomoyo_ss) {int error;
security/tomoyo/gc.c +20 -8
@@ -23,11 +23,10 @@ static inline void tomoyo_memory_free(void *ptr) tomoyo_memory_used[TOMOYO_MEMORY_POLICY ] -=ksize (ptr);kfree (ptr); } - -/* The list for "struct tomoyo_io_buffer". */ -static LIST_HEAD (tomoyo_io_buffer_list);/* Lock for protecting tomoyo_io_buffer_list. */ static DEFINE_SPINLOCK (tomoyo_io_buffer_list_lock); +/* The list for "struct tomoyo_io_buffer". */ +static __guarded_by(&tomoyo_io_buffer_list_lock) LIST_HEAD(tomoyo_io_buffer_list);/** * tomoyo_struct_used_by_io_buffer - Check whether the list element is used by /sys/kernel/security/tomoyo/ users or not.
@@ -385,6 +384,7 @@ static inline void tomoyo_del_number_group(struct list_head *element)*/ static void tomoyo_try_to_gc (const enum tomoyo_policy_id type,struct list_head *element) + __must_hold(&tomoyo_policy_lock) {/* * __list_del_entry() guarantees that the list element became no longer
@@ -484,6 +484,7 @@ static void tomoyo_try_to_gc(const enum tomoyo_policy_id type,*/ static void tomoyo_collect_member (const enum tomoyo_policy_id id,struct list_head *member_list) + __must_hold(&tomoyo_policy_lock) {struct tomoyo_acl_head *member;struct tomoyo_acl_head *tmp;
@@ -504,6 +505,7 @@ static void tomoyo_collect_member(const enum tomoyo_policy_id id,* Returns nothing. */ static void tomoyo_collect_acl (struct list_head *list) + __must_hold(&tomoyo_policy_lock) {struct tomoyo_acl_info *acl;struct tomoyo_acl_info *tmp;
@@ -627,8 +629,11 @@ static int tomoyo_gc_thread(void *unused)if (head->users)continue ;list_del (&head->list); -kfree (head->read_buf); -kfree (head->write_buf); +/* Safe destruction because no users are left. */ +capability_unsafe ( + kfree(head->read_buf); +kfree (head->write_buf); + );kfree (head); }spin_unlock (&tomoyo_io_buffer_list_lock);
@@ -656,11 +661,18 @@ void tomoyo_notify_gc(struct tomoyo_io_buffer *head, const bool is_register) head->users =1 ;list_add (&head->list, &tomoyo_io_buffer_list); }else { - is_write = head->write_buf !=NULL ; +/* +* tomoyo_write_control() can concurrently update write_buf from +* a non-NULL to new non-NULL pointer with io_sem held. +*/ + is_write =data_race (head->write_buf !=NULL );if (!--head->users) {list_del (&head->list); -kfree (head->read_buf); -kfree (head->write_buf); +/* Safe destruction because no users are left. */ +capability_unsafe ( + kfree(head->read_buf); +kfree (head->write_buf); + );kfree (head); } }
security/tomoyo/mount.c +2 -0
@@ -28,6 +28,7 @@ static const char * const tomoyo_mounts[TOMOYO_MAX_SPECIAL_MOUNT] = {* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_mount_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) { return tomoyo_supervisor(r, "file mount %s %s %s 0x%lX\n", r->param.mount.dev->name,
@@ -78,6 +79,7 @@ static int tomoyo_mount_acl(struct tomoyo_request_info *r,const char *dev_name, const struct path *dir, const char *type, unsigned long flags) + __must_hold_shared(&tomoyo_ss) { struct tomoyo_obj_info obj = { };struct path path;
security/tomoyo/network.c +3 -0
@@ -363,6 +363,7 @@ int tomoyo_write_unix_network(struct tomoyo_acl_param *param)static int tomoyo_audit_net_log (struct tomoyo_request_info *r,const char *family,const u8 protocol,const u8 operation,const char *address) + __must_hold_shared(&tomoyo_ss) { return tomoyo_supervisor(r, "network %s %s %s %s\n", family, tomoyo_proto_keyword[protocol],
@@ -377,6 +378,7 @@ static int tomoyo_audit_net_log(struct tomoyo_request_info *r,* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_inet_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) {char buf[128 ];int len;
@@ -402,6 +404,7 @@ static int tomoyo_audit_inet_log(struct tomoyo_request_info *r)* Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_unix_log (struct tomoyo_request_info *r) + __must_hold_shared(&tomoyo_ss) { return tomoyo_audit_net_log(r, "unix", r->param.unix_network.protocol, r->param.unix_network.operation,
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 33/34 crypto: Enable capability analysis
In reply to Marco ElverEnable capability analysis for crypto subsystem.
This demonstrates a larger conversion to use Clang's capability analysis. The benefit is additional static checking of locking rules, along with better documentation.
---
v2:
* New patch.
--- crypto/Makefile | 2 ++ 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 | 8 +++++--- include/crypto/internal/engine.h | 2 +- 9 files changed, 21 insertions(+), 6 deletions(-)
crypto/Makefile +2 -0
@@ -3,6 +3,8 @@ # Cryptographic API # +CAPABILITY_ANALYSIS := y + obj-$(CONFIG_CRYPTO) += crypto.o crypto-y := api.o cipher.o compress.o
crypto/algapi.c +2 -0
@@ -230,6 +230,7 @@ EXPORT_SYMBOL_GPL(crypto_remove_spawns);static void crypto_alg_finish_registration (struct crypto_alg *alg,struct list_head *algs_to_put) + __must_hold(&crypto_alg_sem) {struct crypto_alg *q;
@@ -286,6 +287,7 @@ static struct crypto_larval *crypto_alloc_test_larval(struct crypto_alg *alg)static struct crypto_larval *__crypto_register_alg (struct crypto_alg *alg,struct list_head *algs_to_put) + __must_hold(&crypto_alg_sem) {struct crypto_alg *q;struct crypto_larval *larval;
crypto/api.c +1 -0
@@ -57,6 +57,7 @@ EXPORT_SYMBOL_GPL(crypto_mod_put);static struct crypto_alg *__crypto_alg_lookup (const char *name,u32 type,u32 mask) + __must_hold_shared(&crypto_alg_sem) {struct crypto_alg *q, *alg =NULL ;int best =-2 ;
crypto/crypto_engine.c +1 -1
@@ -514,8 +514,8 @@ struct crypto_engine *crypto_engine_alloc_init_and_set(struct device *dev,snprintf (engine->name,sizeof (engine->name),"%s-engine" ,dev_name (dev)); -crypto_init_queue (&engine->queue, qlen);spin_lock_init (&engine->queue_lock); +crypto_init_queue (&engine->queue, qlen); engine->kworker =kthread_run_worker (0 ,"%s" , engine->name);if (IS_ERR (engine->kworker)) {
crypto/drbg.c +5 -0
@@ -231,6 +231,7 @@ static inline unsigned short drbg_sec_strength(drbg_flag_t flags)*/ static int drbg_fips_continuous_test (struct drbg_state *drbg,const unsigned char *entropy) + __must_hold(&drbg->drbg_mutex) {unsigned short entropylen =drbg_sec_strength (drbg->core->flags);int ret =0 ;
@@ -1061,6 +1062,7 @@ static inline int __drbg_seed(struct drbg_state *drbg, struct list_head *seed,static inline int drbg_get_random_bytes (struct drbg_state *drbg,unsigned char *entropy,unsigned int entropylen) + __must_hold(&drbg->drbg_mutex) {int ret;
@@ -1075,6 +1077,7 @@ static inline int drbg_get_random_bytes(struct drbg_state *drbg, }static int drbg_seed_from_random (struct drbg_state *drbg) + __must_hold(&drbg->drbg_mutex) {struct drbg_string data;LIST_HEAD (seedlist);
@@ -1132,6 +1135,7 @@ static bool drbg_nopr_reseed_interval_elapsed(struct drbg_state *drbg)*/ static int drbg_seed (struct drbg_state *drbg,struct drbg_string *pers,bool reseed) + __must_hold(&drbg->drbg_mutex) {int ret;unsigned char entropy[((32 +16 ) *2 )];
@@ -1368,6 +1372,7 @@ static inline int drbg_alloc_state(struct drbg_state *drbg)static int drbg_generate (struct drbg_state *drbg,unsigned char *buf,unsigned int buflen,struct drbg_string *addtl) + __must_hold(&drbg->drbg_mutex) {int len =0 ;LIST_HEAD (addtllist);
crypto/internal.h +1 -1
@@ -45,8 +45,8 @@ enum {/* Maximum number of (rtattr) parameters for each template. */ #define CRYPTO_MAX_ATTRS 32 -extern struct list_head crypto_alg_list;extern struct rw_semaphore crypto_alg_sem; +extern struct list_head crypto_alg_list __guarded_by(&crypto_alg_sem);extern struct blocking_notifier_head crypto_chain;int alg_test (const char *driver,const char *alg,u32 type,u32 mask);
crypto/proc.c +3 -0
@@ -19,17 +19,20 @@#include "internal.h" static void *c_start (struct seq_file *m,loff_t *pos) + __acquires_shared(&crypto_alg_sem) {down_read (&crypto_alg_sem);return seq_list_start (&crypto_alg_list, *pos); }static void *c_next (struct seq_file *m,void *p,loff_t *pos) + __must_hold_shared(&crypto_alg_sem) {return seq_list_next (p, &crypto_alg_list, pos); }static void c_stop (struct seq_file *m,void *p) + __releases_shared(&crypto_alg_sem) {up_read (&crypto_alg_sem); }
crypto/scompress.c +5 -3
@@ -25,8 +25,8 @@struct scomp_scratch {spinlock_t lock; -void *src; -void *dst; + void *src __guarded_by(&lock); + void *dst __guarded_by(&lock); }; static DEFINE_PER_CPU(struct scomp_scratch, scomp_scratch) = {
@@ -34,8 +34,8 @@ static DEFINE_PER_CPU(struct scomp_scratch, scomp_scratch) = { };static const struct crypto_type crypto_scomp_type; -static int scomp_scratch_users;static DEFINE_MUTEX (scomp_lock); +static int scomp_scratch_users __guarded_by(&scomp_lock);static int __maybe_unused crypto_scomp_report (struct sk_buff *skb,struct crypto_alg *alg)
@@ -59,6 +59,7 @@ static void crypto_scomp_show(struct seq_file *m, struct crypto_alg *alg) }static void crypto_scomp_free_scratches (void ) +__capability_unsafe (/* frees @scratch */ ) {struct scomp_scratch *scratch;int i;
@@ -74,6 +75,7 @@ static void crypto_scomp_free_scratches(void) }static int crypto_scomp_alloc_scratches (void ) +__capability_unsafe (/* allocates @scratch */ ) {struct scomp_scratch *scratch;int i;
include/crypto/internal/engine.h +1 -1
@@ -54,7 +54,7 @@ struct crypto_engine {struct list_head list;spinlock_t queue_lock; -struct crypto_queue queue; + struct crypto_queue queue __guarded_by(&queue_lock);struct device *dev;bool rt;
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Marco Elver
maintainerPATCH v2 34/34 MAINTAINERS: Add entry for Capability Analysis
In reply to Marco ElverAdd entry for all new files added for Clang's capability analysis.
--- MAINTAINERS | 11 +++++++++++ 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
@@ -5638,6 +5638,17 @@ M: Nelson Escobar <[email protected]> S: Supported F: drivers/infiniband/hw/usnic/ +CLANG CAPABILITY ANALYSIS +M: Marco Elver <[email protected]> +R: Bart Van Assche <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/dev-tools/capability-analysis.rst +F: include/linux/compiler-capability-analysis.h +F: lib/test_capability-analysis.c +F: scripts/Makefile.capability-analysis +F: scripts/capability-analysis-suppression.txt + CLANG CONTROL FLOW INTEGRITY SUPPORT M: Sami Tolvanen <[email protected]> M: Kees Cook <[email protected]>
Signature · 1 line
2.48.1.711.g2feabab25a-goog
Re: [PATCH v2 34/34] MAINTAINERS: Add entry for Capability Analysis
Quoted 1 line · Marco Elver
Add entry for all new files added for Clang's capability analysis.
Peter Zijlstra
maintainerQuoted 6 lines · Marco Elver
=== 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.
Wasn't there a limitation wrt recursion -- specifically RCU is very much a recursive lock and TS didn't really fancy that?
Quoted 6 lines
- Rename
__var_guarded_byto 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_byto__pt_guarded_by.
Shorter is better :-)
Anyway; I think I would like to start talking about extensions for these asap.
Notably I feel like we should have a means to annotate the rules for access/read vs modify/write to a variable.
The obvious case is RCU; where holding RCU is sufficient to read, but modification requires a 'real' lock. This is not something that can be currently expressed.
The other is the lock pattern I touched upon the other day, where reading is permitted when holding one of two locks, while writing requires holding both locks.
Being able to explicitly write that in the __guarded_by() annotations is the cleanest way I think.
Anyway, let me go stare at the actual patches :-)
Marco Elver
maintainerQuoted 5 lines · Peter Zijlstra
Quoted 2 lines · Marco Elver
=== Initial Uses ===
Quoted 7 lines
Quoted 4 lines
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.Wasn't there a limitation wrt recursion -- specifically RCU is very much a recursive lock and TS didn't really fancy that?
Yup, I mentioned that in the rcu patch. Make it more prominent in documentation?
Quoted 12 lines
Quoted 6 lines
- Rename
__var_guarded_byto 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_byto__pt_guarded_by.Shorter is better :-)
Anyway; I think I would like to start talking about extensions for these asap.
Quoted 6 lines
Notably I feel like we should have a means to annotate the rules for access/read vs modify/write to a variable.
The obvious case is RCU; where holding RCU is sufficient to read, but modification requires a 'real' lock. This is not something that can be currently expressed.
It can. It distinguishes between holding shared/read locks and exclusive/read-write locks.
RCU is is a bit special because we also have rcu_dereference() and rcu_assign_pointer() and such, but in general if you only hold a "shared capability" e.g. the RCU read lock only, it won't let you write to __guarded_by variables. Again, the RCU case is special because updating RCU-guarded can be done any number of ways, so I had to make rcu_assign_pointer() a bit more relaxed.
But besides RCU, the distinction between holding a lock exclusively or shared does what one would expect: holding the lock exclusively lets you write, and holding it shared only lets you only read a __guarded_by() member.
Quoted 6 lines
The other is the lock pattern I touched upon the other day, where reading is permitted when holding one of two locks, while writing requires holding both locks.
Being able to explicitly write that in the
__guarded_by()annotations is the cleanest way I think.
Simpler forms of this are possible if you stack __guarded_by(): you must hold both locks exclusively to write, otherwise you can only read (but must still hold both locks "shared", or "shared"+"exclusive").
The special case regarding "hold lock A -OR- B to read" is problematic of course - that can be solved by designing lock-wrappers that "fake acquire" some lock, or we do design some extension. We can go off and propose something to the Clang maintainers, but I fear that there are only few cases where we need __guarded_by(A OR B). If you say we need an extension, then we need a list of requirements that we can go and design a clear and implementable extension.
In general, yes, the analysis imposes additional constraints, and not all kernel locking patterns will be expressible (if ever). But a lot of the "regular" code (drivers!) can be opted in today.
Thanks,
-- Marco
Peter Zijlstra
maintainerRight, so since this is all awesome, I figured I should try and have it compile kernel/sched/, see how far I get.
I know I can't use the __guarded_by() things, they're just too primitive for that I need, but I figured I should try and have it track the lock/unlock thingies at least.
I've had to rework how the GUARD bits work, since some guards are defined on objects that contain locks, rather than the locks themselves.
We've also had discussions on IRQ on all the things I've ran across, like needing to be able to reference the return object for things like:
struct sighand_struct * lock_task_sighand(struct task_struct *task, unsigned long *flags) __cond_acquires(nonnull, return->siglock);
The patch below tried working around that by doing:
__cond_acquires(nonnull, task->sighand->siglock)
But I'm not quite sure it does the right thing, and definitely doesn't always work for other such cases. Notably, I've managed to ICE clang (send you the details).
This is on top of queue.git/locking/core, but I imagine that tree won't live very long at those point.
It is basically tip/locking/core with your patches ran through:
sed -e 's/__acquire/__assume/g'
before applying them.
---
include/linux/blkdev.h +2 -0
@@ -945,6 +945,7 @@ static inline unsigned int blk_boundary_sectors_left(sector_t offset,*/ static inline struct queue_limits queue_limits_start_update (struct request_queue *q) + __acquires(q->limits_lock) {mutex_lock (&q->limits_lock);return q->limits;
@@ -965,6 +966,7 @@ int blk_validate_limits(struct queue_limits *lim);* starting update. */ static inline void queue_limits_cancel_update (struct request_queue *q) + __releases(q->limits_lock) {mutex_unlock (&q->limits_lock); }
include/linux/bpf.h +1 -0
@@ -2196,6 +2196,7 @@ bpf_prog_run_array(const struct bpf_prog_array *array, static __always_inline u32bpf_prog_run_array_uprobe (const struct bpf_prog_array *array,const void *ctx,bpf_prog_run_fn run_prog) + __no_capability_analysis/* too stupid for cond rcu lock */ {const struct bpf_prog_array_item *item;const struct bpf_prog *prog;
include/linux/cgroup.h +2 -0
@@ -364,11 +364,13 @@ static inline void cgroup_put(struct cgroup *cgrp)extern struct mutex cgroup_mutex;static inline void cgroup_lock (void ) +__acquires (cgroup_mutex) {mutex_lock (&cgroup_mutex); }static inline void cgroup_unlock (void ) +__releases (cgroup_mutex) {mutex_unlock (&cgroup_mutex); }
include/linux/cleanup.h +11 -6
@@ -249,12 +249,13 @@ static inline _type class_##_name##_constructor(_init_args) \ __no_capability_analysis \ {_type t = _init;return t; } -#define EXTEND_CLASS(_name, ext, ctor_attrs, _init, _init_args...) \ +#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 inline void class_##_name##ext##_destructor(class_##_name##_t *p)\ { class_##_name##_destructor(p); } \ static inline class_##_name##_t class_##_name##ext##_constructor(_init_args) \ - __no_capability_analysis ctor_attrs \ + __no_capability_analysis \ { class_##_name##_t t = _init; return t; }#define CLASS (_name, var) \
@@ -302,7 +303,7 @@ static __maybe_unused const bool class_##_name##_is_conditional = _is_cond#define DEFINE_GUARD_COND (_name, _ext, _condlock) \ __DEFINE_CLASS_IS_CONDITIONAL(_name##_ext, true); \ - EXTEND_CLASS(_name, _ext,, \ + EXTEND_CLASS(_name, _ext, \ ({ void *_t = _T; if (_T && !(_condlock)) _t = NULL; _t; }), \ class_##_name##_t _T) \ static inline void * class_##_name##_ext##_lock_ptr(class_##_name##_t *_T) \
@@ -368,6 +369,7 @@ _label: \*/ #define __DEFINE_UNLOCK_GUARD (_name, _type, _unlock, ...) \ +typedef _type lock_##_name##_t; \ typedef struct { \ _type *lock; \ __VA_ARGS__; \
@@ -387,7 +389,7 @@ static inline void *class_##_name##_lock_ptr(class_##_name##_t *_T) \#define __DEFINE_LOCK_GUARD_1 (_name, _type, _lock) \ static inline class_##_name##_t class_##_name##_constructor(_type *l) \ - __no_capability_analysis __assumes_cap(l) \ + __no_capability_analysis \ { \ class_##_name##_t _t = { .lock = l }, *_T = &_t; \ _lock; \
@@ -408,6 +410,10 @@ static inline class_##_name##_t class_##_name##_constructor(void) \ static inline class_##_name##_t class_##_name##_constructor(void) _lock;\ static inline void class_##_name##_destructor(class_##_name##_t *_T) _unlock +#define DECLARE_LOCK_GUARD_1_ATTRS(_name, _lock, _unlock) \ +static inline class_##_name##_t class_##_name##_constructor(lock_##_name##_t *_T) _lock;\ +static inline void class_##_name##_destructor(class_##_name##_t *_T) _unlock + #define DEFINE_LOCK_GUARD_1(_name, _type, _lock, _unlock, ...) \ __DEFINE_CLASS_IS_CONDITIONAL(_name, false); \ __DEFINE_UNLOCK_GUARD(_name, _type, _unlock, __VA_ARGS__) \
@@ -420,7 +426,7 @@ __DEFINE_LOCK_GUARD_0(_name, _lock)#define DEFINE_LOCK_GUARD_1_COND (_name, _ext, _condlock) \ __DEFINE_CLASS_IS_CONDITIONAL(_name##_ext, true); \ - EXTEND_CLASS(_name, _ext, __assumes_cap(l), \ + EXTEND_CLASS(_name, _ext, \ ({ class_##_name##_t _t = { .lock = l }, *_T = &_t;\ if (_T->lock && !(_condlock)) _T->lock = NULL; \ _t; }), \
@@ -428,5 +434,4 @@ __DEFINE_LOCK_GUARD_0(_name, _lock) static inline void * class_##_name##_ext##_lock_ptr(class_##_name##_t *_T) \ { return class_##_name##_lock_ptr(_T); } -#endif /* _LINUX_CLEANUP_H */
include/linux/device.h +4 -0
@@ -1026,21 +1026,25 @@ static inline bool dev_pm_test_driver_flags(struct device *dev, u32 flags) }static inline void device_lock (struct device *dev) + __acquires(dev->mutex) {mutex_lock (&dev->mutex); }static inline int device_lock_interruptible (struct device *dev) + __cond_acquires(0, dev->mutex) {return mutex_lock_interruptible (&dev->mutex); }static inline int device_trylock (struct device *dev) + __cond_acquires(true, dev->mutex) {return mutex_trylock (&dev->mutex); }static inline void device_unlock (struct device *dev) + __releases(dev->mutex) {mutex_unlock (&dev->mutex); }
include/linux/fs.h +21 -0
@@ -540,31 +540,37 @@ static inline bool mapping_tagged(struct address_space *mapping, xa_mark_t tag) }static inline void i_mmap_lock_write (struct address_space *mapping) + __acquires(mapping->i_mmap_rwsem) {down_write (&mapping->i_mmap_rwsem); }static inline int i_mmap_trylock_write (struct address_space *mapping) + __cond_acquires(true, mapping->i_mmap_rwsem) {return down_write_trylock (&mapping->i_mmap_rwsem); }static inline void i_mmap_unlock_write (struct address_space *mapping) + __releases(mapping->i_mmap_rwsem) {up_write (&mapping->i_mmap_rwsem); }static inline int i_mmap_trylock_read (struct address_space *mapping) + __cond_acquires_shared(true, mapping->i_mmap_rwsem) {return down_read_trylock (&mapping->i_mmap_rwsem); }static inline void i_mmap_lock_read (struct address_space *mapping) + __acquires_shared(mapping->i_mmap_rwsem) {down_read (&mapping->i_mmap_rwsem); }static inline void i_mmap_unlock_read (struct address_space *mapping) + __releases_shared(mapping->i_mmap_rwsem) {up_read (&mapping->i_mmap_rwsem); }
@@ -873,31 +879,37 @@ enum inode_i_mutex_lock_class };static inline void inode_lock (struct inode *inode) + __acquires(inode->i_rwsem) {down_write (&inode->i_rwsem); }static inline void inode_unlock (struct inode *inode) + __releases(inode->i_rwsem) {up_write (&inode->i_rwsem); }static inline void inode_lock_shared (struct inode *inode) + __acquires_shared(inode->i_rwsem) {down_read (&inode->i_rwsem); }static inline void inode_unlock_shared (struct inode *inode) + __releases_shared(inode->i_rwsem) {up_read (&inode->i_rwsem); }static inline int inode_trylock (struct inode *inode) + __cond_acquires(true, inode->i_rwsem) {return down_write_trylock (&inode->i_rwsem); }static inline int inode_trylock_shared (struct inode *inode) + __cond_acquires_shared(true, inode->i_rwsem) {return down_read_trylock (&inode->i_rwsem); }
@@ -908,38 +920,45 @@ static inline int inode_is_locked(struct inode *inode) }static inline void inode_lock_nested (struct inode *inode,unsigned subclass) + __acquires(inode->i_rwsem) {down_write_nested (&inode->i_rwsem, subclass); }static inline void inode_lock_shared_nested (struct inode *inode,unsigned subclass) + __acquires_shared(inode->i_rwsem) {down_read_nested (&inode->i_rwsem, subclass); }static inline void filemap_invalidate_lock (struct address_space *mapping) + __acquires(mapping->invalidate_lock) {down_write (&mapping->invalidate_lock); }static inline void filemap_invalidate_unlock (struct address_space *mapping) + __releases(mapping->invalidate_lock) {up_write (&mapping->invalidate_lock); }static inline void filemap_invalidate_lock_shared (struct address_space *mapping) + __acquires_shared(mapping->invalidate_lock) {down_read (&mapping->invalidate_lock); }static inline int filemap_invalidate_trylock_shared (struct address_space *mapping) + __cond_acquires_shared(true, mapping->invalidate_lock) {return down_read_trylock (&mapping->invalidate_lock); }static inline void filemap_invalidate_unlock_shared (struct address_space *mapping) + __releases_shared(mapping->invalidate_lock) {up_read (&mapping->invalidate_lock); }
@@ -3873,6 +3892,7 @@ static inline bool dir_emit_dots(struct file *file, struct dir_context *ctx)return true; }static inline bool dir_relax (struct inode *inode) + __releases(inode->i_rwsem) __acquires(inode->i_rwsem) {inode_unlock (inode);inode_lock (inode);
@@ -3880,6 +3900,7 @@ static inline bool dir_relax(struct inode *inode) }static inline bool dir_relax_shared (struct inode *inode) + __releases_shared(inode->i_rwsem) __acquires_shared(inode->i_rwsem) {inode_unlock_shared (inode);inode_lock_shared (inode);
include/linux/idr.h +1 -0
@@ -170,6 +170,7 @@ static inline bool idr_is_empty(const struct idr *idr)* function. See idr_preload() for details. */ static inline void idr_preload_end (void ) + __releases(radix_tree_preloads.lock) {local_unlock (&radix_tree_preloads.lock); }
include/linux/interrupt.h +2 -2
@@ -236,8 +236,8 @@ extern void enable_percpu_irq(unsigned int irq, unsigned int type);extern bool irq_percpu_is_enabled (unsigned int irq);extern void irq_wake_thread (unsigned int irq,void *dev_id); -DEFINE_LOCK_GUARD_1 (disable_irq, int, - disable_irq(*_T->lock), enable_irq(*_T->lock)) +DEFINE_GUARD (disable_irq, int, +disable_irq (_T),enable_irq (_T));extern void disable_nmi_nosync (unsigned int irq);extern void disable_percpu_nmi (unsigned int irq);
include/linux/memcontrol.h +9 -3
@@ -1512,17 +1512,20 @@ static inline struct lruvec *parent_lruvec(struct lruvec *lruvec) }static inline void unlock_page_lruvec (struct lruvec *lruvec) + __releases(lruvec->lru_lock) {spin_unlock (&lruvec->lru_lock); }static inline void unlock_page_lruvec_irq (struct lruvec *lruvec) + __releases(lruvec->lru_lock) {spin_unlock_irq (&lruvec->lru_lock); }static inline void unlock_page_lruvec_irqrestore (struct lruvec *lruvec, -unsigned long flags) +unsigned long flags) + __releases(lruvec->lru_lock) {spin_unlock_irqrestore (&lruvec->lru_lock, flags); }
@@ -1537,7 +1540,8 @@ static inline bool folio_matches_lruvec(struct folio *folio,/* Don't lock again iff page's lruvec locked */ static inline struct lruvec *folio_lruvec_relock_irq (struct folio *folio, -struct lruvec *locked_lruvec) +struct lruvec *locked_lruvec) + __no_capability_analysis/* no __cond_releases */ {if (locked_lruvec) {if (folio_matches_lruvec (folio, locked_lruvec))
@@ -1551,7 +1555,9 @@ static inline struct lruvec *folio_lruvec_relock_irq(struct folio *folio,/* Don't lock again iff folio's lruvec locked */ static inline void folio_lruvec_relock_irqsave (struct folio *folio, -struct lruvec **lruvecp,unsigned long *flags) +struct lruvec **lruvecp, +unsigned long *flags) + __no_capability_analysis {if (*lruvecp) {if (folio_matches_lruvec (folio, *lruvecp))
include/linux/memory_hotplug.h +8 -0
@@ -99,18 +99,22 @@ bool mhp_supports_memmap_on_memory(void);* can't be changed while pgdat_resize_lock() held. */ static inline unsigned zone_span_seqbegin (struct zone *zone) + __acquires_shared(zone->span_seqlock) {return read_seqbegin (&zone->span_seqlock); }static inline int zone_span_seqretry (struct zone *zone,unsigned iv) + __releases_shared(zone->span_seqlock) {return read_seqretry (&zone->span_seqlock, iv); }static inline void zone_span_writelock (struct zone *zone) + __acquires(zone->span_seqlock) {write_seqlock (&zone->span_seqlock); }static inline void zone_span_writeunlock (struct zone *zone) + __releases(zone->span_seqlock) {write_sequnlock (&zone->span_seqlock); }
@@ -178,11 +182,13 @@ void mem_hotplug_done(void);/* See kswapd_is_running() */ static inline void pgdat_kswapd_lock (pg_data_t *pgdat) + __acquires(pgdat->kswapd_lock) {mutex_lock (&pgdat->kswapd_lock); }static inline void pgdat_kswapd_unlock (pg_data_t *pgdat) + __releases(pgdat->kswapd_lock) {mutex_unlock (&pgdat->kswapd_lock); }
@@ -252,11 +258,13 @@ struct range arch_get_mappable_range(void);*/ static inline void pgdat_resize_lock (struct pglist_data *pgdat,unsigned long *flags) + __acquires(pgdat->node_size_lock) {spin_lock_irqsave (&pgdat->node_size_lock, *flags); }static inline void pgdat_resize_unlock (struct pglist_data *pgdat,unsigned long *flags) + __releases(pgdat->node_size_lock) {spin_unlock_irqrestore (&pgdat->node_size_lock, *flags); }
include/linux/mm.h +7 -1
@@ -703,6 +703,7 @@ static inline void vma_numab_state_free(struct vm_area_struct *vma) {}* using mmap_lock. The function should never yield false unlocked result. */ static inline bool vma_start_read (struct vm_area_struct *vma) + __cond_acquires_shared(true, vma->vm_lock->lock) {/* * Check before locking. A race might cause false locked result.
@@ -736,6 +737,7 @@ static inline bool vma_start_read(struct vm_area_struct *vma) }static inline void vma_end_read (struct vm_area_struct *vma) + __releases_shared(vma->vm_lock->lock) {rcu_read_lock ();/* keeps vma alive till the end of up_read */ up_read (&vma->vm_lock->lock);
@@ -800,6 +802,7 @@ static inline void vma_mark_detached(struct vm_area_struct *vma, bool detached) }static inline void release_fault_lock (struct vm_fault *vmf) + __no_capability_analysis {if (vmf->flags &FAULT_FLAG_VMA_LOCK )vma_end_read (vmf->vma);
@@ -3016,7 +3019,8 @@ static inline bool pagetable_pte_ctor(struct ptdesc *ptdesc)return true; } -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) +__cond_acquires_shared (nonnull,RCU );static inline pte_t *pte_offset_map (pmd_t *pmd,unsigned long addr) {
@@ -3092,6 +3096,7 @@ static inline bool pmd_ptlock_init(struct ptdesc *ptdesc) { return true; }#endif static inline spinlock_t *pmd_lock (struct mm_struct *mm,pmd_t *pmd) + __no_capability_analysis {spinlock_t *ptl =pmd_lockptr (mm, pmd);spin_lock (ptl);
@@ -3119,6 +3124,7 @@ static inline spinlock_t *pud_lockptr(struct mm_struct *mm, pud_t *pud) }static inline spinlock_t *pud_lock (struct mm_struct *mm,pud_t *pud) + __no_capability_analysis {spinlock_t *ptl =pud_lockptr (mm, pud);
include/linux/mmap_lock.h +10 -0
@@ -129,6 +129,7 @@ static inline void mmap_init_lock(struct mm_struct *mm) }static inline void mmap_write_lock (struct mm_struct *mm) + __acquires(mm->mmap_lock) {__mmap_lock_trace_start_locking (mm, true);down_write (&mm->mmap_lock);
@@ -137,6 +138,7 @@ static inline void mmap_write_lock(struct mm_struct *mm) }static inline void mmap_write_lock_nested (struct mm_struct *mm,int subclass) + __acquires(mm->mmap_lock) {__mmap_lock_trace_start_locking (mm, true);down_write_nested (&mm->mmap_lock, subclass);
@@ -145,6 +147,7 @@ static inline void mmap_write_lock_nested(struct mm_struct *mm, int subclass) }static inline int mmap_write_lock_killable (struct mm_struct *mm) + __cond_acquires(0, mm->mmap_lock) {int ret;
@@ -171,6 +174,7 @@ static inline void vma_end_write_all(struct mm_struct *mm) }static inline void mmap_write_unlock (struct mm_struct *mm) + __releases(mm->mmap_lock) {__mmap_lock_trace_released (mm, true);vma_end_write_all (mm);
@@ -178,6 +182,7 @@ static inline void mmap_write_unlock(struct mm_struct *mm) }static inline void mmap_write_downgrade (struct mm_struct *mm) + __releases(mm->mmap_lock) __acquires_shared(mm->mmap_lock) {__mmap_lock_trace_acquire_returned (mm, false, true);vma_end_write_all (mm);
@@ -185,6 +190,7 @@ static inline void mmap_write_downgrade(struct mm_struct *mm) }static inline void mmap_read_lock (struct mm_struct *mm) + __acquires_shared(mm->mmap_lock) {__mmap_lock_trace_start_locking (mm, false);down_read (&mm->mmap_lock);
@@ -192,6 +198,7 @@ static inline void mmap_read_lock(struct mm_struct *mm) }static inline int mmap_read_lock_killable (struct mm_struct *mm) + __cond_acquires_shared(0, mm->mmap_lock) {int ret;
@@ -202,6 +209,7 @@ static inline int mmap_read_lock_killable(struct mm_struct *mm) }static inline bool mmap_read_trylock (struct mm_struct *mm) + __cond_acquires_shared(true, mm->mmap_lock) {bool ret;
@@ -212,12 +220,14 @@ static inline bool mmap_read_trylock(struct mm_struct *mm) }static inline void mmap_read_unlock (struct mm_struct *mm) + __releases_shared(mm->mmap_lock) {__mmap_lock_trace_released (mm, false);up_read (&mm->mmap_lock); }static inline void mmap_read_unlock_non_owner (struct mm_struct *mm) + __releases_shared(mm->mmap_lock) {__mmap_lock_trace_released (mm, false);up_read_non_owner (&mm->mmap_lock);
include/linux/mutex.h +4 -0
@@ -203,4 +203,8 @@ DEFINE_LOCK_GUARD_1(mutex, struct mutex, mutex_lock(_T->lock), mutex_unlock(_T-> DEFINE_LOCK_GUARD_1_COND(mutex, _try, mutex_trylock(_T->lock)) DEFINE_LOCK_GUARD_1_COND(mutex, _intr, mutex_lock_interruptible(_T->lock) == 0) +DECLARE_LOCK_GUARD_1_ATTRS(mutex, __assumes_cap(_T), /* */); +DECLARE_LOCK_GUARD_1_ATTRS(mutex_try, __assumes_cap(_T), /* */); +DECLARE_LOCK_GUARD_1_ATTRS(mutex_intr, __assumes_cap(_T), /* */); +#endif /* __LINUX_MUTEX_H */
include/linux/pgtable.h +1 -0
@@ -132,6 +132,7 @@ static inline pte_t *__pte_map(pmd_t *pmd, unsigned long address)return pte_offset_kernel (pmd, address); }static inline void pte_unmap (pte_t *pte) +__releases_shared (RCU ) {rcu_read_unlock (); }
include/linux/radix-tree.h +2 -1
@@ -236,7 +236,7 @@ void *radix_tree_delete(struct radix_tree_root *, unsigned long);unsigned int radix_tree_gang_lookup (const struct radix_tree_root *,void **results,unsigned long first_index,unsigned int max_items); -int radix_tree_preload (gfp_t gfp_mask); +int radix_tree_preload(gfp_t gfp_mask) __acquires(radix_tree_preloads.lock);int radix_tree_maybe_preload (gfp_t gfp_mask);void radix_tree_init (void ); void *radix_tree_tag_set(struct radix_tree_root *,
@@ -256,6 +256,7 @@ unsigned int radix_tree_gang_lookup_tag_slot(const struct radix_tree_root *,int radix_tree_tagged (const struct radix_tree_root *,unsigned int tag);static inline void radix_tree_preload_end (void ) + __releases(radix_tree_preloads.lock) {local_unlock (&radix_tree_preloads.lock); }
include/linux/sched/signal.h +3 -1
@@ -733,10 +733,12 @@ static inline int thread_group_empty(struct task_struct *p) (thread_group_leader(p) && !thread_group_empty(p))extern struct sighand_struct *lock_task_sighand (struct task_struct *task, -unsigned long *flags); +unsigned long *flags) + __cond_acquires(nonnull, task->sighand->siglock);static inline void unlock_task_sighand (struct task_struct *task,unsigned long *flags) + __releases(task->sighand->siglock) {spin_unlock_irqrestore (&task->sighand->siglock, *flags); }
include/linux/sched/task.h +2 -0
@@ -226,11 +226,13 @@ static inline struct vm_struct *task_stack_vm_area(const struct task_struct *t)* neither inside nor outside. */ static inline void task_lock (struct task_struct *p) + __acquires(p->alloc_lock) {spin_lock (&p->alloc_lock); }static inline void task_unlock (struct task_struct *p) + __releases(p->alloc_lock) {spin_unlock (&p->alloc_lock); }
include/linux/sched/wake_q.h +3 -0
@@ -66,6 +66,7 @@ extern void wake_up_q(struct wake_q_head *head);/* Spin unlock helpers to unlock and call wake_up_q with preempt disabled */ static inline void raw_spin_unlock_wake (raw_spinlock_t *lock,struct wake_q_head *wake_q) +__releases (lock) {guard (preempt)();raw_spin_unlock (lock);
@@ -77,6 +78,7 @@ void raw_spin_unlock_wake(raw_spinlock_t *lock, struct wake_q_head *wake_q)static inline void raw_spin_unlock_irq_wake (raw_spinlock_t *lock,struct wake_q_head *wake_q) +__releases (lock) {guard (preempt)();raw_spin_unlock_irq (lock);
@@ -89,6 +91,7 @@ void raw_spin_unlock_irq_wake(raw_spinlock_t *lock, struct wake_q_head *wake_q)static inline void raw_spin_unlock_irqrestore_wake (raw_spinlock_t *lock,unsigned long flags,struct wake_q_head *wake_q) +__releases (lock) {guard (preempt)();raw_spin_unlock_irqrestore (lock, flags);
include/linux/spinlock.h +21 -0
@@ -359,11 +359,13 @@ static __always_inline int spin_trylock(spinlock_t *lock)#define spin_lock_nested (lock, subclass) \ do { \ raw_spin_lock_nested(spinlock_check(lock), subclass); \ + __release(spinlock_check(lock)); __acquire(lock); \ } while (0)#define spin_lock_nest_lock (lock, nest_lock) \ do { \ raw_spin_lock_nest_lock(spinlock_check(lock), nest_lock); \ + __release(spinlock_check(lock)); __acquire(lock); \ } while (0) static __always_inline void spin_lock_irq(spinlock_t *lock)
@@ -535,73 +537,92 @@ void free_bucket_spinlocks(spinlock_t *locks);DEFINE_LOCK_GUARD_1 (raw_spinlock, raw_spinlock_t,raw_spin_lock (_T->lock), raw_spin_unlock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock, __assumes_cap(_T), /* */); DEFINE_LOCK_GUARD_1_COND(raw_spinlock, _try, raw_spin_trylock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_try, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (raw_spinlock_nested, raw_spinlock_t,raw_spin_lock_nested (_T->lock,SINGLE_DEPTH_NESTING ), raw_spin_unlock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_nested, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (raw_spinlock_irq, raw_spinlock_t,raw_spin_lock_irq (_T->lock), raw_spin_unlock_irq(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irq, __assumes_cap(_T), /* */); DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irq, _try, raw_spin_trylock_irq(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irq_try, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (raw_spinlock_irqsave, raw_spinlock_t,raw_spin_lock_irqsave (_T->lock, _T->flags),raw_spin_unlock_irqrestore (_T->lock, _T->flags), unsigned long flags) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1_COND (raw_spinlock_irqsave, _try, raw_spin_trylock_irqsave(_T->lock, _T->flags)) +DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave_try, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (spinlock, spinlock_t,spin_lock (_T->lock), spin_unlock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(spinlock, __assumes_cap(_T), /* */); DEFINE_LOCK_GUARD_1_COND(spinlock, _try, spin_trylock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(spinlock_try, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (spinlock_irq, spinlock_t,spin_lock_irq (_T->lock), spin_unlock_irq(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irq, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1_COND (spinlock_irq, _try, spin_trylock_irq(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irq_try, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (spinlock_irqsave, spinlock_t,spin_lock_irqsave (_T->lock, _T->flags),spin_unlock_irqrestore (_T->lock, _T->flags), unsigned long flags) +DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irqsave, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1_COND (spinlock_irqsave, _try, spin_trylock_irqsave(_T->lock, _T->flags)) +DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irqsave_try, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (read_lock, rwlock_t,read_lock (_T->lock), read_unlock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(read_lock, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (read_lock_irq, rwlock_t,read_lock_irq (_T->lock), read_unlock_irq(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(read_lock_irq, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (read_lock_irqsave, rwlock_t,read_lock_irqsave (_T->lock, _T->flags),read_unlock_irqrestore (_T->lock, _T->flags), unsigned long flags) +DECLARE_LOCK_GUARD_1_ATTRS(read_lock_irqsave, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (write_lock, rwlock_t,write_lock (_T->lock), write_unlock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(write_lock, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (write_lock_irq, rwlock_t,write_lock_irq (_T->lock), write_unlock_irq(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(write_lock_irq, __assumes_cap(_T), /* */);DEFINE_LOCK_GUARD_1 (write_lock_irqsave, rwlock_t,write_lock_irqsave (_T->lock, _T->flags),write_unlock_irqrestore (_T->lock, _T->flags), unsigned long flags) +DECLARE_LOCK_GUARD_1_ATTRS(write_lock_irqsave, __assumes_cap(_T), /* */);#undef __LINUX_INSIDE_SPINLOCK_H#endif /* __LINUX_SPINLOCK_H */
kernel/sched/sched.h +68 -30
291 lines not on this page · raw message
Quoted 13 lines · Peter Zijlstra
include/linux/blkdev.h +1
-0@@ -945,6 +945,7 @@ static inline unsigned int blk_boundary_sectors_left(sector_t offset,*/ static inline struct queue_limits queue_limits_start_update (struct request_queue *q) + __acquires(q->limits_lock) {mutex_lock (&q->limits_lock);return q->limits;
include/linux/blkdev.h int blk_validate_limits(struct queue_limits *lim); · line 972
Quoted 7 lines
include/linux/blkdev.h +1
-0@@ -965,6 +966,7 @@ int blk_validate_limits(struct queue_limits *lim);* starting update. */ static inline void queue_limits_cancel_update (struct request_queue *q) + __releases(q->limits_lock) {mutex_unlock (&q->limits_lock); }
The above is incomplete. Here is what I came up with myself:
include/linux/blkdev.h +8 -3
@@ -945,15 +945,19 @@ static inline unsigned int blk_boundary_sectors_left(sector_t offset,*/ static inline struct queue_limits queue_limits_start_update (struct request_queue *q) + ACQUIRE(q->limits_lock) {mutex_lock (&q->limits_lock);return q->limits; } int queue_limits_commit_update_frozen(struct request_queue *q, -struct queue_limits *lim); + struct queue_limits *lim) + RELEASE(q->limits_lock); int queue_limits_commit_update(struct request_queue *q, -struct queue_limits *lim); -int queue_limits_set (struct request_queue *q,struct queue_limits *lim); + struct queue_limits *lim) + RELEASE(q->limits_lock); +int queue_limits_set(struct request_queue *q, struct queue_limits *lim) + EXCLUDES(q->limits_lock);int blk_validate_limits (struct queue_limits *lim);/**
@@ -965,6 +969,7 @@ int blk_validate_limits(struct queue_limits *lim);* starting update. */ static inline void queue_limits_cancel_update (struct request_queue *q) + RELEASE(q->limits_lock) {mutex_unlock (&q->limits_lock); }
Quoted 20 lines
include/linux/device.h +2
-0@@ -1026,21 +1026,25 @@ static inline bool dev_pm_test_driver_flags(struct device *dev, u32 flags) }static inline void device_lock (struct device *dev) + __acquires(dev->mutex) {mutex_lock (&dev->mutex); }static inline int device_lock_interruptible (struct device *dev) + __cond_acquires(0, dev->mutex) {return mutex_lock_interruptible (&dev->mutex); }static inline int device_trylock (struct device *dev)
include/linux/device.h static inline bool dev_pm_test_driver_flags(struct device *dev, u32 flags) · line 1050
Quoted 10 lines
include/linux/device.h +2
-0+ __cond_acquires(true, dev->mutex) {return mutex_trylock (&dev->mutex); }static inline void device_unlock (struct device *dev) + __releases(dev->mutex) {mutex_unlock (&dev->mutex); }
I propose to annotate these functions with __no_capability_analysis as a first step. Review of all callers of these functions in the entire kernel tree learned me that annotating these functions results in a significant number of false positives and not to the discovery of any bugs. The false positives are triggered by conditional locking. An example of code that triggers false positive thread-safety warnings:
static void ath9k_hif_usb_firmware_fail(struct hif_device_usb *hif_dev)
{
struct device *dev = &hif_dev->udev->dev;
struct device *parent = dev->parent;
complete_all(&hif_dev->fw_done);
if (parent)
device_lock(parent);
device_release_driver(dev);
if (parent)
device_unlock(parent);
}Thanks,
Bart.
Peter Zijlstra
maintainerQuoted 15 lines · Bart Van Assche
Quoted 14 lines · Peter Zijlstra
include/linux/blkdev.h +1
-0@@ -945,6 +945,7 @@ static inline unsigned int blk_boundary_sectors_left(sector_t offset,*/ static inline struct queue_limits queue_limits_start_update (struct request_queue *q) + __acquires(q->limits_lock) {mutex_lock (&q->limits_lock);return q->limits;@@ -965,6 +966,7 @@ int blk_validate_limits(struct queue_limits *lim);* starting update.
Quoted 8 lines
include/linux/blkdev.h int blk_validate_limits(struct queue_limits *lim); · line 975
Quoted 6 lines
include/linux/blkdev.h +1
-0*/ static inline void queue_limits_cancel_update (struct request_queue *q) + __releases(q->limits_lock) {mutex_unlock (&q->limits_lock); }The above is incomplete. Here is what I came up with myself:
Oh, I'm sure. I simply fixed whatever was topmost in the compile output when trying to build kernel/sched/. After fixing these two, it stopped complaining about blkdev.
I think it complains about these because they're inline, even though they're otherwise unused.
Quoted 25 lines
Quoted 25 lines
include/linux/device.h +4
-0@@ -1026,21 +1026,25 @@ static inline bool dev_pm_test_driver_flags(struct device *dev, u32 flags) }static inline void device_lock (struct device *dev) + __acquires(dev->mutex) {mutex_lock (&dev->mutex); }static inline int device_lock_interruptible (struct device *dev) + __cond_acquires(0, dev->mutex) {return mutex_lock_interruptible (&dev->mutex); }static inline int device_trylock (struct device *dev) + __cond_acquires(true, dev->mutex) {return mutex_trylock (&dev->mutex); }static inline void device_unlock (struct device *dev) + __releases(dev->mutex) {mutex_unlock (&dev->mutex);
Quoted 8 lines
include/linux/device.h static inline bool dev_pm_test_driver_flags(struct device *dev, u32 flags) · line 1046
Quoted 1 line
include/linux/device.h +0
-0}I propose to annotate these functions with
__no_capability_analysisas a first step. Review of all callers of these functions in the entire kernel tree learned me that annotating these functions results in a significant number of false positives and not to the discovery of any bugs. The false positives are triggered by conditional locking. An example of code that triggers false positive thread-safety warnings:
Yeah, I've ran into this as well. The thing is entirely stupid when it sees a branch. This is really unfortunate. But I disagree, I would annotate those functions that have conditional locking with __no_capability_analysis, or possibly:
#define __confused_by_conditionals __no_capability_analysis
I'm also not quite sure how to annotate things like pte_lockptr().
Anyway, this thing has some promise, however it is *really*, as in *really* *REALLY* simple. Anything remotely interesting, where you actually want the help, it falls over.
But you gotta start somewhere I suppose. I think the thing that is important here is how receptive the clang folks are to working on this -- because it definitely needs work.
Marco Elver
maintainerQuoted 4 lines · Peter Zijlstra
Right, so since this is all awesome, I figured I should try and have it compile
kernel/sched/, see how far I get.
[...]
It's been a while, but teaching Clang new tricks for this analysis has been taking its time (and I've only been looking into this on and off).
Anyway, Clang has already gained __attribute__((reentrant_capability). Of course, that alone doesn't quite help that much.
But what we really wanted, I think, per this Clang discussion thread [1], was some "simple" form of intra-procedural alias analysis.
[1] https://lore.kernel.org/all/CANpmjNPquO=W1JAh1FNQb8pMQjgeZAKCPQUAd7qUg=5pjJ6x=Q@mail.gmail.com/
Anyway, this evolving Clang PR probably gets us pretty close:
https://github.com/llvm/llvm-project/pull/142955
With Clang from that PR, I can compile kernel/sched/{core.c, fair.c} with modest changes (see below - work in progress) without warnings. Notably, this can also deal with "capability acquired in returned object" with some macro magic.
The full v3 series preview is here:
https://git.kernel.org/pub/scm/linux/kernel/git/melver/linux.git/log/?h=cap-analysis/dev
The whole tree compiles cleanly, although I might have missed testing some kernel configs.
If/when that Clang PR lands (~ETA another month probably), I would think about sending the next version of this series.
Thanks,
-- Marco
------ >8 ------
From: Marco Elver <[email protected]>
Date: Sun, 3 Aug 2025 20:21:39 +0200
Subject: [PATCH] sched: Enable capability analysis for core.c and fair.c
This demonstrates a larger conversion to use Clang's capability analysis. The benefit is additional static checking of locking rules, along with better documentation.
Arguably, kernel/sched is the "final boss" of Clang's capability analysis, and application to core.c & fair.c demonstrates that the latest Clang version has become powerful enough to start applying this to more complex subsystems (with some modest annotations and changes).
---
v3:
* New patch.
--- include/linux/sched.h | 6 +- include/linux/sched/signal.h | 4 +- include/linux/sched/task.h | 5 +- include/linux/sched/wake_q.h | 3 + kernel/sched/Makefile | 3 + kernel/sched/core.c | 82 ++++++++++----- kernel/sched/fair.c | 6 +- kernel/sched/sched.h | 108 +++++++++++++------- scripts/capability-analysis-suppression.txt | 1 + 9 files changed, 148 insertions(+), 70 deletions(-)
include/linux/sched.h +3 -3
@@ -2125,9 +2125,9 @@ static inline int _cond_resched(void)_cond_resched (); \ }) -extern int __cond_resched_lock (spinlock_t *lock); -extern int __cond_resched_rwlock_read (rwlock_t *lock); -extern int __cond_resched_rwlock_write (rwlock_t *lock); +extern int __cond_resched_lock(spinlock_t *lock) __must_hold(lock); +extern int __cond_resched_rwlock_read(rwlock_t *lock) __must_hold_shared(lock); +extern int __cond_resched_rwlock_write(rwlock_t *lock) __must_hold(lock);#define MIGHT_RESCHED_RCU_SHIFT 8#define MIGHT_RESCHED_PREEMPT_MASK ((1U << MIGHT_RESCHED_RCU_SHIFT) - 1)
include/linux/sched/signal.h +3 -1
@@ -734,10 +734,12 @@ static inline int thread_group_empty(struct task_struct *p) (thread_group_leader(p) && !thread_group_empty(p))extern struct sighand_struct *lock_task_sighand (struct task_struct *task, -unsigned long *flags); +unsigned long *flags) + __acquires(&task->sighand->siglock);static inline void unlock_task_sighand (struct task_struct *task,unsigned long *flags) + __releases(&task->sighand->siglock) {spin_unlock_irqrestore (&task->sighand->siglock, *flags); }
include/linux/sched/task.h +4 -1
@@ -226,15 +226,18 @@ static inline struct vm_struct *task_stack_vm_area(const struct task_struct *t)* neither inside nor outside. */ static inline void task_lock (struct task_struct *p) + __acquires(&p->alloc_lock) {spin_lock (&p->alloc_lock); }static inline void task_unlock (struct task_struct *p) + __releases(&p->alloc_lock) {spin_unlock (&p->alloc_lock); } -DEFINE_GUARD(task_lock, struct task_struct *, task_lock(_T), task_unlock(_T)) +DEFINE_LOCK_GUARD_1(task_lock, struct task_struct, task_lock(_T->lock), task_unlock(_T->lock)) +DECLARE_LOCK_GUARD_1_ATTRS(task_lock, __assumes_cap(_T->alloc_lock), /* */)#endif /* _LINUX_SCHED_TASK_H */
include/linux/sched/wake_q.h +3 -0
@@ -66,6 +66,7 @@ extern void wake_up_q(struct wake_q_head *head);/* Spin unlock helpers to unlock and call wake_up_q with preempt disabled */ static inline void raw_spin_unlock_wake (raw_spinlock_t *lock,struct wake_q_head *wake_q) +__releases (lock) {guard (preempt)();raw_spin_unlock (lock);
@@ -77,6 +78,7 @@ void raw_spin_unlock_wake(raw_spinlock_t *lock, struct wake_q_head *wake_q)static inline void raw_spin_unlock_irq_wake (raw_spinlock_t *lock,struct wake_q_head *wake_q) +__releases (lock) {guard (preempt)();raw_spin_unlock_irq (lock);
@@ -89,6 +91,7 @@ void raw_spin_unlock_irq_wake(raw_spinlock_t *lock, struct wake_q_head *wake_q)static inline void raw_spin_unlock_irqrestore_wake (raw_spinlock_t *lock,unsigned long flags,struct wake_q_head *wake_q) +__releases (lock) {guard (preempt)();raw_spin_unlock_irqrestore (lock, flags);
kernel/sched/Makefile +3 -0
@@ -1,5 +1,8 @@ # SPDX-License-Identifier: GPL-2.0 +CAPABILITY_ANALYSIS_core.o := y +CAPABILITY_ANALYSIS_fair.o := y + # The compilers are complaining about unused variables inside an if(0) scope # block. This is daft, shut them up. ccflags-y += $(call cc-disable-warning, unused-but-set-variable)
kernel/sched/core.c +55 -27
220 lines not on this page · raw message
kernel/sched/fair.c +5 -1
@@ -4842,7 +4842,8 @@ static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)return cfs_rq->avg.load_avg; } -static int sched_balance_newidle (struct rq *this_rq,struct rq_flags *rf); +static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) + __must_hold(__rq_lockp(this_rq));static inline unsigned long task_util (struct task_struct *p) {
@@ -8737,6 +8738,7 @@ static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_contextstatic int balance_fair (struct rq *rq,struct task_struct *prev,struct rq_flags *rf) +__must_hold (__rq_lockp (rq)) {if (sched_fair_runnable (rq))return 1 ;
@@ -8884,6 +8886,7 @@ static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)struct task_struct *pick_next_task_fair (struct rq *rq,struct task_struct *prev,struct rq_flags *rf) +__must_hold (__rq_lockp (rq)) {struct sched_entity *se;struct task_struct *p;
@@ -8970,6 +8973,7 @@ pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf }static struct task_struct *__pick_next_task_fair (struct rq *rq,struct task_struct *prev) +__must_hold (__rq_lockp (rq)) {return pick_next_task_fair (rq, prev,NULL ); }
kernel/sched/sched.h +71 -37
322 lines not on this page · raw message
scripts/capability-analysis-suppression.txt +1 -0
@@ -26,6 +26,7 @@ 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/sched*=emit src:*include/linux/seqlock*.h=emit src:*include/linux/spinlock*.h=emit src:*include/linux/srcu*.h=emit
Signature · 1 line
2.50.1.565.gc32cd1483b-goog