kcsan.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. .. SPDX-License-Identifier: GPL-2.0
  2. .. Copyright (C) 2019, Google LLC.
  3. Kernel Concurrency Sanitizer (KCSAN)
  4. ====================================
  5. The Kernel Concurrency Sanitizer (KCSAN) is a dynamic race detector, which
  6. relies on compile-time instrumentation, and uses a watchpoint-based sampling
  7. approach to detect races. KCSAN's primary purpose is to detect `data races`_.
  8. Usage
  9. -----
  10. KCSAN is supported by both GCC and Clang. With GCC we require version 11 or
  11. later, and with Clang also require version 11 or later.
  12. To enable KCSAN configure the kernel with::
  13. CONFIG_KCSAN = y
  14. KCSAN provides several other configuration options to customize behaviour (see
  15. the respective help text in ``lib/Kconfig.kcsan`` for more info).
  16. Error reports
  17. ~~~~~~~~~~~~~
  18. A typical data race report looks like this::
  19. ==================================================================
  20. BUG: KCSAN: data-race in test_kernel_read / test_kernel_write
  21. write to 0xffffffffc009a628 of 8 bytes by task 487 on cpu 0:
  22. test_kernel_write+0x1d/0x30
  23. access_thread+0x89/0xd0
  24. kthread+0x23e/0x260
  25. ret_from_fork+0x22/0x30
  26. read to 0xffffffffc009a628 of 8 bytes by task 488 on cpu 6:
  27. test_kernel_read+0x10/0x20
  28. access_thread+0x89/0xd0
  29. kthread+0x23e/0x260
  30. ret_from_fork+0x22/0x30
  31. value changed: 0x00000000000009a6 -> 0x00000000000009b2
  32. Reported by Kernel Concurrency Sanitizer on:
  33. CPU: 6 PID: 488 Comm: access_thread Not tainted 5.12.0-rc2+ #1
  34. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
  35. ==================================================================
  36. The header of the report provides a short summary of the functions involved in
  37. the race. It is followed by the access types and stack traces of the 2 threads
  38. involved in the data race. If KCSAN also observed a value change, the observed
  39. old value and new value are shown on the "value changed" line respectively.
  40. The other less common type of data race report looks like this::
  41. ==================================================================
  42. BUG: KCSAN: data-race in test_kernel_rmw_array+0x71/0xd0
  43. race at unknown origin, with read to 0xffffffffc009bdb0 of 8 bytes by task 515 on cpu 2:
  44. test_kernel_rmw_array+0x71/0xd0
  45. access_thread+0x89/0xd0
  46. kthread+0x23e/0x260
  47. ret_from_fork+0x22/0x30
  48. value changed: 0x0000000000002328 -> 0x0000000000002329
  49. Reported by Kernel Concurrency Sanitizer on:
  50. CPU: 2 PID: 515 Comm: access_thread Not tainted 5.12.0-rc2+ #1
  51. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
  52. ==================================================================
  53. This report is generated where it was not possible to determine the other
  54. racing thread, but a race was inferred due to the data value of the watched
  55. memory location having changed. These reports always show a "value changed"
  56. line. A common reason for reports of this type are missing instrumentation in
  57. the racing thread, but could also occur due to e.g. DMA accesses. Such reports
  58. are shown only if ``CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN=y``, which is
  59. enabled by default.
  60. Selective analysis
  61. ~~~~~~~~~~~~~~~~~~
  62. It may be desirable to disable data race detection for specific accesses,
  63. functions, compilation units, or entire subsystems. For static blacklisting,
  64. the below options are available:
  65. * KCSAN understands the ``data_race(expr)`` annotation, which tells KCSAN that
  66. any data races due to accesses in ``expr`` should be ignored and resulting
  67. behaviour when encountering a data race is deemed safe. Please see
  68. `"Marking Shared-Memory Accesses" in the LKMM`_ for more information.
  69. * Similar to ``data_race(...)``, the type qualifier ``__data_racy`` can be used
  70. to document that all data races due to accesses to a variable are intended
  71. and should be ignored by KCSAN::
  72. struct foo {
  73. ...
  74. int __data_racy stats_counter;
  75. ...
  76. };
  77. * Disabling data race detection for entire functions can be accomplished by
  78. using the function attribute ``__no_kcsan``::
  79. __no_kcsan
  80. void foo(void) {
  81. ...
  82. To dynamically limit for which functions to generate reports, see the
  83. `DebugFS interface`_ blacklist/whitelist feature.
  84. * To disable data race detection for a particular compilation unit, add to the
  85. ``Makefile``::
  86. KCSAN_SANITIZE_file.o := n
  87. * To disable data race detection for all compilation units listed in a
  88. ``Makefile``, add to the respective ``Makefile``::
  89. KCSAN_SANITIZE := n
  90. .. _"Marking Shared-Memory Accesses" in the LKMM: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/memory-model/Documentation/access-marking.txt
  91. Furthermore, it is possible to tell KCSAN to show or hide entire classes of
  92. data races, depending on preferences. These can be changed via the following
  93. Kconfig options:
  94. * ``CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY``: If enabled and a conflicting write
  95. is observed via a watchpoint, but the data value of the memory location was
  96. observed to remain unchanged, do not report the data race.
  97. * ``CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC``: Assume that plain aligned writes
  98. up to word size are atomic by default. Assumes that such writes are not
  99. subject to unsafe compiler optimizations resulting in data races. The option
  100. causes KCSAN to not report data races due to conflicts where the only plain
  101. accesses are aligned writes up to word size.
  102. * ``CONFIG_KCSAN_PERMISSIVE``: Enable additional permissive rules to ignore
  103. certain classes of common data races. Unlike the above, the rules are more
  104. complex involving value-change patterns, access type, and address. This
  105. option depends on ``CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=y``. For details
  106. please see the ``kernel/kcsan/permissive.h``. Testers and maintainers that
  107. only focus on reports from specific subsystems and not the whole kernel are
  108. recommended to disable this option.
  109. To use the strictest possible rules, select ``CONFIG_KCSAN_STRICT=y``, which
  110. configures KCSAN to follow the Linux-kernel memory consistency model (LKMM) as
  111. closely as possible.
  112. DebugFS interface
  113. ~~~~~~~~~~~~~~~~~
  114. The file ``/sys/kernel/debug/kcsan`` provides the following interface:
  115. * Reading ``/sys/kernel/debug/kcsan`` returns various runtime statistics.
  116. * Writing ``on`` or ``off`` to ``/sys/kernel/debug/kcsan`` allows turning KCSAN
  117. on or off, respectively.
  118. * Writing ``!some_func_name`` to ``/sys/kernel/debug/kcsan`` adds
  119. ``some_func_name`` to the report filter list, which (by default) blacklists
  120. reporting data races where either one of the top stackframes are a function
  121. in the list.
  122. * Writing either ``blacklist`` or ``whitelist`` to ``/sys/kernel/debug/kcsan``
  123. changes the report filtering behaviour. For example, the blacklist feature
  124. can be used to silence frequently occurring data races; the whitelist feature
  125. can help with reproduction and testing of fixes.
  126. Tuning performance
  127. ~~~~~~~~~~~~~~~~~~
  128. Core parameters that affect KCSAN's overall performance and bug detection
  129. ability are exposed as kernel command-line arguments whose defaults can also be
  130. changed via the corresponding Kconfig options.
  131. * ``kcsan.skip_watch`` (``CONFIG_KCSAN_SKIP_WATCH``): Number of per-CPU memory
  132. operations to skip, before another watchpoint is set up. Setting up
  133. watchpoints more frequently will result in the likelihood of races to be
  134. observed to increase. This parameter has the most significant impact on
  135. overall system performance and race detection ability.
  136. * ``kcsan.udelay_task`` (``CONFIG_KCSAN_UDELAY_TASK``): For tasks, the
  137. microsecond delay to stall execution after a watchpoint has been set up.
  138. Larger values result in the window in which we may observe a race to
  139. increase.
  140. * ``kcsan.udelay_interrupt`` (``CONFIG_KCSAN_UDELAY_INTERRUPT``): For
  141. interrupts, the microsecond delay to stall execution after a watchpoint has
  142. been set up. Interrupts have tighter latency requirements, and their delay
  143. should generally be smaller than the one chosen for tasks.
  144. They may be tweaked at runtime via ``/sys/module/kcsan/parameters/``.
  145. Data Races
  146. ----------
  147. In an execution, two memory accesses form a *data race* if they *conflict*,
  148. they happen concurrently in different threads, and at least one of them is a
  149. *plain access*; they *conflict* if both access the same memory location, and at
  150. least one is a write. For a more thorough discussion and definition, see `"Plain
  151. Accesses and Data Races" in the LKMM`_.
  152. .. _"Plain Accesses and Data Races" in the LKMM: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/memory-model/Documentation/explanation.txt?id=8f6629c004b193d23612641c3607e785819e97ab#n2164
  153. Relationship with the Linux-Kernel Memory Consistency Model (LKMM)
  154. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  155. The LKMM defines the propagation and ordering rules of various memory
  156. operations, which gives developers the ability to reason about concurrent code.
  157. Ultimately this allows to determine the possible executions of concurrent code,
  158. and if that code is free from data races.
  159. KCSAN is aware of *marked atomic operations* (``READ_ONCE``, ``WRITE_ONCE``,
  160. ``atomic_*``, etc.), and a subset of ordering guarantees implied by memory
  161. barriers. With ``CONFIG_KCSAN_WEAK_MEMORY=y``, KCSAN models load or store
  162. buffering, and can detect missing ``smp_mb()``, ``smp_wmb()``, ``smp_rmb()``,
  163. ``smp_store_release()``, and all ``atomic_*`` operations with equivalent
  164. implied barriers.
  165. Note, KCSAN will not report all data races due to missing memory ordering,
  166. specifically where a memory barrier would be required to prohibit subsequent
  167. memory operation from reordering before the barrier. Developers should
  168. therefore carefully consider the required memory ordering requirements that
  169. remain unchecked.
  170. Race Detection Beyond Data Races
  171. --------------------------------
  172. For code with complex concurrency design, race-condition bugs may not always
  173. manifest as data races. Race conditions occur if concurrently executing
  174. operations result in unexpected system behaviour. On the other hand, data races
  175. are defined at the C-language level. The following macros can be used to check
  176. properties of concurrent code where bugs would not manifest as data races.
  177. .. kernel-doc:: include/linux/kcsan-checks.h
  178. :functions: ASSERT_EXCLUSIVE_WRITER ASSERT_EXCLUSIVE_WRITER_SCOPED
  179. ASSERT_EXCLUSIVE_ACCESS ASSERT_EXCLUSIVE_ACCESS_SCOPED
  180. ASSERT_EXCLUSIVE_BITS
  181. Implementation Details
  182. ----------------------
  183. KCSAN relies on observing that two accesses happen concurrently. Crucially, we
  184. want to (a) increase the chances of observing races (especially for races that
  185. manifest rarely), and (b) be able to actually observe them. We can accomplish
  186. (a) by injecting various delays, and (b) by using address watchpoints (or
  187. breakpoints).
  188. If we deliberately stall a memory access, while we have a watchpoint for its
  189. address set up, and then observe the watchpoint to fire, two accesses to the
  190. same address just raced. Using hardware watchpoints, this is the approach taken
  191. in `DataCollider
  192. <http://usenix.org/legacy/events/osdi10/tech/full_papers/Erickson.pdf>`_.
  193. Unlike DataCollider, KCSAN does not use hardware watchpoints, but instead
  194. relies on compiler instrumentation and "soft watchpoints".
  195. In KCSAN, watchpoints are implemented using an efficient encoding that stores
  196. access type, size, and address in a long; the benefits of using "soft
  197. watchpoints" are portability and greater flexibility. KCSAN then relies on the
  198. compiler instrumenting plain accesses. For each instrumented plain access:
  199. 1. Check if a matching watchpoint exists; if yes, and at least one access is a
  200. write, then we encountered a racing access.
  201. 2. Periodically, if no matching watchpoint exists, set up a watchpoint and
  202. stall for a small randomized delay.
  203. 3. Also check the data value before the delay, and re-check the data value
  204. after delay; if the values mismatch, we infer a race of unknown origin.
  205. To detect data races between plain and marked accesses, KCSAN also annotates
  206. marked accesses, but only to check if a watchpoint exists; i.e. KCSAN never
  207. sets up a watchpoint on marked accesses. By never setting up watchpoints for
  208. marked operations, if all accesses to a variable that is accessed concurrently
  209. are properly marked, KCSAN will never trigger a watchpoint and therefore never
  210. report the accesses.
  211. Modeling Weak Memory
  212. ~~~~~~~~~~~~~~~~~~~~
  213. KCSAN's approach to detecting data races due to missing memory barriers is
  214. based on modeling access reordering (with ``CONFIG_KCSAN_WEAK_MEMORY=y``).
  215. Each plain memory access for which a watchpoint is set up, is also selected for
  216. simulated reordering within the scope of its function (at most 1 in-flight
  217. access).
  218. Once an access has been selected for reordering, it is checked along every
  219. other access until the end of the function scope. If an appropriate memory
  220. barrier is encountered, the access will no longer be considered for simulated
  221. reordering.
  222. When the result of a memory operation should be ordered by a barrier, KCSAN can
  223. then detect data races where the conflict only occurs as a result of a missing
  224. barrier. Consider the example::
  225. int x, flag;
  226. void T1(void)
  227. {
  228. x = 1; // data race!
  229. WRITE_ONCE(flag, 1); // correct: smp_store_release(&flag, 1)
  230. }
  231. void T2(void)
  232. {
  233. while (!READ_ONCE(flag)); // correct: smp_load_acquire(&flag)
  234. ... = x; // data race!
  235. }
  236. When weak memory modeling is enabled, KCSAN can consider ``x`` in ``T1`` for
  237. simulated reordering. After the write of ``flag``, ``x`` is again checked for
  238. concurrent accesses: because ``T2`` is able to proceed after the write of
  239. ``flag``, a data race is detected. With the correct barriers in place, ``x``
  240. would not be considered for reordering after the proper release of ``flag``,
  241. and no data race would be detected.
  242. Deliberate trade-offs in complexity but also practical limitations mean only a
  243. subset of data races due to missing memory barriers can be detected. With
  244. currently available compiler support, the implementation is limited to modeling
  245. the effects of "buffering" (delaying accesses), since the runtime cannot
  246. "prefetch" accesses. Also recall that watchpoints are only set up for plain
  247. accesses, and the only access type for which KCSAN simulates reordering. This
  248. means reordering of marked accesses is not modeled.
  249. A consequence of the above is that acquire operations do not require barrier
  250. instrumentation (no prefetching). Furthermore, marked accesses introducing
  251. address or control dependencies do not require special handling (the marked
  252. access cannot be reordered, later dependent accesses cannot be prefetched).
  253. Key Properties
  254. ~~~~~~~~~~~~~~
  255. 1. **Memory Overhead:** The overall memory overhead is only a few MiB
  256. depending on configuration. The current implementation uses a small array of
  257. longs to encode watchpoint information, which is negligible.
  258. 2. **Performance Overhead:** KCSAN's runtime aims to be minimal, using an
  259. efficient watchpoint encoding that does not require acquiring any shared
  260. locks in the fast-path. For kernel boot on a system with 8 CPUs:
  261. - 5.0x slow-down with the default KCSAN config;
  262. - 2.8x slow-down from runtime fast-path overhead only (set very large
  263. ``KCSAN_SKIP_WATCH`` and unset ``KCSAN_SKIP_WATCH_RANDOMIZE``).
  264. 3. **Annotation Overheads:** Minimal annotations are required outside the KCSAN
  265. runtime. As a result, maintenance overheads are minimal as the kernel
  266. evolves.
  267. 4. **Detects Racy Writes from Devices:** Due to checking data values upon
  268. setting up watchpoints, racy writes from devices can also be detected.
  269. 5. **Memory Ordering:** KCSAN is aware of only a subset of LKMM ordering rules;
  270. this may result in missed data races (false negatives).
  271. 6. **Analysis Accuracy:** For observed executions, due to using a sampling
  272. strategy, the analysis is *unsound* (false negatives possible), but aims to
  273. be complete (no false positives).
  274. Alternatives Considered
  275. -----------------------
  276. An alternative data race detection approach for the kernel can be found in the
  277. `Kernel Thread Sanitizer (KTSAN)
  278. <https://github.com/google/kernel-sanitizers/blob/master/KTSAN.md>`_.
  279. KTSAN is a happens-before data race detector, which explicitly establishes the
  280. happens-before order between memory operations, which can then be used to
  281. determine data races as defined in `Data Races`_.
  282. To build a correct happens-before relation, KTSAN must be aware of all ordering
  283. rules of the LKMM and synchronization primitives. Unfortunately, any omission
  284. leads to large numbers of false positives, which is especially detrimental in
  285. the context of the kernel which includes numerous custom synchronization
  286. mechanisms. To track the happens-before relation, KTSAN's implementation
  287. requires metadata for each memory location (shadow memory), which for each page
  288. corresponds to 4 pages of shadow memory, and can translate into overhead of
  289. tens of GiB on a large system.