context-analysis.rst 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. .. SPDX-License-Identifier: GPL-2.0
  2. .. Copyright (C) 2025, Google LLC.
  3. .. _context-analysis:
  4. Compiler-Based Context Analysis
  5. ===============================
  6. Context Analysis is a language extension, which enables statically checking
  7. that required contexts are active (or inactive) by acquiring and releasing
  8. user-definable "context locks". An obvious application is lock-safety checking
  9. for the kernel's various synchronization primitives (each of which represents a
  10. "context lock"), and checking that locking rules are not violated.
  11. The Clang compiler currently supports the full set of context analysis
  12. features. To enable for Clang, configure the kernel with::
  13. CONFIG_WARN_CONTEXT_ANALYSIS=y
  14. The feature requires Clang 22 or later.
  15. The analysis is *opt-in by default*, and requires declaring which modules and
  16. subsystems should be analyzed in the respective `Makefile`::
  17. CONTEXT_ANALYSIS_mymodule.o := y
  18. Or for all translation units in the directory::
  19. CONTEXT_ANALYSIS := y
  20. It is possible to enable the analysis tree-wide, however, which will result in
  21. numerous false positive warnings currently and is *not* generally recommended::
  22. CONFIG_WARN_CONTEXT_ANALYSIS_ALL=y
  23. Programming Model
  24. -----------------
  25. The below describes the programming model around using context lock types.
  26. .. note::
  27. Enabling context analysis can be seen as enabling a dialect of Linux C with
  28. a Context System. Some valid patterns involving complex control-flow are
  29. constrained (such as conditional acquisition and later conditional release
  30. in the same function).
  31. Context analysis is a way to specify permissibility of operations to depend on
  32. context locks being held (or not held). Typically we are interested in
  33. protecting data and code in a critical section by requiring a specific context
  34. to be active, for example by holding a specific lock. The analysis ensures that
  35. callers cannot perform an operation without the required context being active.
  36. Context locks are associated with named structs, along with functions that
  37. operate on struct instances to acquire and release the associated context lock.
  38. Context locks can be held either exclusively or shared. This mechanism allows
  39. assigning more precise privileges when a context is active, typically to
  40. distinguish where a thread may only read (shared) or also write (exclusive) to
  41. data guarded within a context.
  42. The set of contexts that are actually active in a given thread at a given point
  43. in program execution is a run-time concept. The static analysis works by
  44. calculating an approximation of that set, called the context environment. The
  45. context environment is calculated for every program point, and describes the
  46. set of contexts that are statically known to be active, or inactive, at that
  47. particular point. This environment is a conservative approximation of the full
  48. set of contexts that will actually be active in a thread at run-time.
  49. More details are also documented `here
  50. <https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_.
  51. .. note::
  52. Clang's analysis explicitly does not infer context locks acquired or
  53. released by inline functions. It requires explicit annotations to (a) assert
  54. that it's not a bug if a context lock is released or acquired, and (b) to
  55. retain consistency between inline and non-inline function declarations.
  56. Supported Kernel Primitives
  57. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  58. Currently the following synchronization primitives are supported:
  59. `raw_spinlock_t`, `spinlock_t`, `rwlock_t`, `mutex`, `seqlock_t`,
  60. `bit_spinlock`, RCU, SRCU (`srcu_struct`), `rw_semaphore`, `local_lock_t`,
  61. `ww_mutex`.
  62. To initialize variables guarded by a context lock with an initialization
  63. function (``type_init(&lock)``), prefer using ``guard(type_init)(&lock)`` or
  64. ``scoped_guard(type_init, &lock) { ... }`` to initialize such guarded members
  65. or globals in the enclosing scope. This initializes the context lock and treats
  66. the context as active within the initialization scope (initialization implies
  67. exclusive access to the underlying object).
  68. For example::
  69. struct my_data {
  70. spinlock_t lock;
  71. int counter __guarded_by(&lock);
  72. };
  73. void init_my_data(struct my_data *d)
  74. {
  75. ...
  76. guard(spinlock_init)(&d->lock);
  77. d->counter = 0;
  78. ...
  79. }
  80. Alternatively, initializing guarded variables can be done with context analysis
  81. disabled, preferably in the smallest possible scope (due to lack of any other
  82. checking): either with a ``context_unsafe(var = init)`` expression, or by
  83. marking small initialization functions with the ``__context_unsafe(init)``
  84. attribute.
  85. Lockdep assertions, such as `lockdep_assert_held()`, inform the compiler's
  86. context analysis that the associated synchronization primitive is held after
  87. the assertion. This avoids false positives in complex control-flow scenarios
  88. and encourages the use of Lockdep where static analysis is limited. For
  89. example, this is useful when a function doesn't *always* require a lock, making
  90. `__must_hold()` inappropriate.
  91. Keywords
  92. ~~~~~~~~
  93. .. kernel-doc:: include/linux/compiler-context-analysis.h
  94. :identifiers: context_lock_struct
  95. token_context_lock token_context_lock_instance
  96. __guarded_by __pt_guarded_by
  97. __must_hold
  98. __must_not_hold
  99. __acquires
  100. __cond_acquires
  101. __releases
  102. __must_hold_shared
  103. __acquires_shared
  104. __cond_acquires_shared
  105. __releases_shared
  106. __acquire
  107. __release
  108. __acquire_shared
  109. __release_shared
  110. __acquire_ret
  111. __acquire_shared_ret
  112. context_unsafe
  113. __context_unsafe
  114. disable_context_analysis enable_context_analysis
  115. .. note::
  116. The function attribute `__no_context_analysis` is reserved for internal
  117. implementation of context lock types, and should be avoided in normal code.
  118. Background
  119. ----------
  120. Clang originally called the feature `Thread Safety Analysis
  121. <https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>`_, with some keywords
  122. and documentation still using the thread-safety-analysis-only terminology. This
  123. was later changed and the feature became more flexible, gaining the ability to
  124. define custom "capabilities". Its foundations can be found in `Capability
  125. Systems <https://www.cs.cornell.edu/talc/papers/capabilities.pdf>`_, used to
  126. specify the permissibility of operations to depend on some "capability" being
  127. held (or not held).
  128. Because the feature is not just able to express capabilities related to
  129. synchronization primitives, and "capability" is already overloaded in the
  130. kernel, the naming chosen for the kernel departs from Clang's initial "Thread
  131. Safety" and "capability" nomenclature; we refer to the feature as "Context
  132. Analysis" to avoid confusion. The internal implementation still makes
  133. references to Clang's terminology in a few places, such as `-Wthread-safety`
  134. being the warning option that also still appears in diagnostic messages.