169 lines · 7.0 KB · Text
RawDownload
.. SPDX-License-Identifier: GPL-2.0.. Copyright (C) 2025, Google LLC. .. _context-analysis: Compiler-Based Context Analysis=============================== Context Analysis is a language extension, which enables statically checkingthat required contexts are active (or inactive) by acquiring and releasinguser-definable "context locks". An obvious application is lock-safety checkingfor the kernel's various synchronization primitives (each of which represents a"context lock"), and checking that locking rules are not violated. The Clang compiler currently supports the full set of context analysisfeatures. To enable for Clang, configure the kernel with::     CONFIG_WARN_CONTEXT_ANALYSIS=y The feature requires Clang 23 or later. The analysis is *opt-in by default*, and requires declaring which modules andsubsystems should be analyzed in the respective `Makefile`::     CONTEXT_ANALYSIS_mymodule.o := y Or for all translation units in the directory::     CONTEXT_ANALYSIS := y It is possible to enable the analysis tree-wide, however, which will result innumerous false positive warnings currently and is *not* generally recommended::     CONFIG_WARN_CONTEXT_ANALYSIS_ALL=y Programming Model----------------- The below describes the programming model around using context lock types. .. note::   Enabling context analysis can be seen as enabling a dialect of Linux C with   a Context System. Some valid patterns involving complex control-flow are   constrained (such as conditional acquisition and later conditional release   in the same function). Context analysis is a way to specify permissibility of operations to depend oncontext locks being held (or not held). Typically we are interested inprotecting data and code in a critical section by requiring a specific contextto be active, for example by holding a specific lock. The analysis ensures thatcallers cannot perform an operation without the required context being active. Context locks are associated with named structs, along with functions thatoperate on struct instances to acquire and release the associated context lock. Context locks can be held either exclusively or shared. This mechanism allowsassigning more precise privileges when a context is active, typically todistinguish where a thread may only read (shared) or also write (exclusive) todata guarded within a context. The set of contexts that are actually active in a given thread at a given pointin program execution is a run-time concept. The static analysis works bycalculating an approximation of that set, called the context environment. Thecontext environment is calculated for every program point, and describes theset of contexts that are statically known to be active, or inactive, at thatparticular point. This environment is a conservative approximation of the fullset of contexts that will actually be active in a thread at run-time. More details are also documented `here<https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_. .. note::   Clang's analysis explicitly does not infer context locks acquired or   released by inline functions. It requires explicit annotations to (a) assert   that it's not a bug if a context lock is released or acquired, and (b) to   retain consistency between inline and non-inline function declarations. Supported Kernel Primitives~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently the following synchronization primitives are supported:`raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`,`bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`,`ww_mutex`. To initialize variables guarded by a context lock with an initializationfunction (``type_init(&lock)``), prefer using ``guard(type_init)(&lock)`` or``scoped_guard(type_init, &lock) { ... }`` to initialize such guarded membersor globals in the enclosing scope. This initializes the context lock and treatsthe context as active within the initialization scope (initialization impliesexclusive access to the underlying object). For example::     struct my_data {            spinlock_t lock;            int counter __guarded_by(&lock);    };     void init_my_data(struct my_data *d)    {            ...            guard(spinlock_init)(&d->lock);            d->counter = 0;            ...    } Alternatively, initializing guarded variables can be done with context analysisdisabled, preferably in the smallest possible scope (due to lack of any otherchecking): either with a ``context_unsafe(var = init)`` expression, or bymarking small initialization functions with the ``__context_unsafe(init)``attribute. Lockdep assertions, such as `lockdep_assert_held()`, inform the compiler'scontext analysis that the associated synchronization primitive is held afterthe assertion. This avoids false positives in complex control-flow scenariosand encourages the use of Lockdep where static analysis is limited. Forexample, this is useful when a function doesn't *always* require a lock, making`__must_hold()` inappropriate. Keywords~~~~~~~~ .. kernel-doc:: include/linux/compiler-context-analysis.h   :identifiers: context_lock_struct                 token_context_lock token_context_lock_instance                 __guarded_by __pt_guarded_by                 __must_hold                 __must_not_hold                 __acquires                 __cond_acquires                 __releases                 __must_hold_shared                 __acquires_shared                 __cond_acquires_shared                 __releases_shared                 __acquire                 __release                 __acquire_shared                 __release_shared                 __acquire_ret                 __acquire_shared_ret                 context_unsafe                 __context_unsafe                 disable_context_analysis enable_context_analysis .. note::   The function attribute `__no_context_analysis` is reserved for internal   implementation of context lock types, and should be avoided in normal code. Background---------- Clang originally called the feature `Thread Safety Analysis<https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_, with some keywordsand documentation still using the thread-safety-analysis-only terminology. Thiswas later changed and the feature became more flexible, gaining the ability todefine custom "capabilities". Its foundations can be found in `CapabilitySystems <https://www.cs.cornell.edu/talc/papers/capabilities.pdf>`_, used tospecify the permissibility of operations to depend on some "capability" beingheld (or not held). Because the feature is not just able to express capabilities related tosynchronization primitives, and "capability" is already overloaded in thekernel, the naming chosen for the kernel departs from Clang's initial "ThreadSafety" and "capability" nomenclature; we refer to the feature as "ContextAnalysis" to avoid confusion. The internal implementation still makesreferences to Clang's terminology in a few places, such as `-Wthread-safety`being the warning option that also still appears in diagnostic messages.