0001 .. SPDX-License-Identifier: GPL-2.0
0002 .. Copyright (C) 2019, Google LLC.
0003
0004 The Kernel Concurrency Sanitizer (KCSAN)
0005 ========================================
0006
0007 The Kernel Concurrency Sanitizer (KCSAN) is a dynamic race detector, which
0008 relies on compile-time instrumentation, and uses a watchpoint-based sampling
0009 approach to detect races. KCSAN's primary purpose is to detect `data races`_.
0010
0011 Usage
0012 -----
0013
0014 KCSAN is supported by both GCC and Clang. With GCC we require version 11 or
0015 later, and with Clang also require version 11 or later.
0016
0017 To enable KCSAN configure the kernel with::
0018
0019 CONFIG_KCSAN = y
0020
0021 KCSAN provides several other configuration options to customize behaviour (see
0022 the respective help text in ``lib/Kconfig.kcsan`` for more info).
0023
0024 Error reports
0025 ~~~~~~~~~~~~~
0026
0027 A typical data race report looks like this::
0028
0029 ==================================================================
0030 BUG: KCSAN: data-race in test_kernel_read / test_kernel_write
0031
0032 write to 0xffffffffc009a628 of 8 bytes by task 487 on cpu 0:
0033 test_kernel_write+0x1d/0x30
0034 access_thread+0x89/0xd0
0035 kthread+0x23e/0x260
0036 ret_from_fork+0x22/0x30
0037
0038 read to 0xffffffffc009a628 of 8 bytes by task 488 on cpu 6:
0039 test_kernel_read+0x10/0x20
0040 access_thread+0x89/0xd0
0041 kthread+0x23e/0x260
0042 ret_from_fork+0x22/0x30
0043
0044 value changed: 0x00000000000009a6 -> 0x00000000000009b2
0045
0046 Reported by Kernel Concurrency Sanitizer on:
0047 CPU: 6 PID: 488 Comm: access_thread Not tainted 5.12.0-rc2+ #1
0048 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
0049 ==================================================================
0050
0051 The header of the report provides a short summary of the functions involved in
0052 the race. It is followed by the access types and stack traces of the 2 threads
0053 involved in the data race. If KCSAN also observed a value change, the observed
0054 old value and new value are shown on the "value changed" line respectively.
0055
0056 The other less common type of data race report looks like this::
0057
0058 ==================================================================
0059 BUG: KCSAN: data-race in test_kernel_rmw_array+0x71/0xd0
0060
0061 race at unknown origin, with read to 0xffffffffc009bdb0 of 8 bytes by task 515 on cpu 2:
0062 test_kernel_rmw_array+0x71/0xd0
0063 access_thread+0x89/0xd0
0064 kthread+0x23e/0x260
0065 ret_from_fork+0x22/0x30
0066
0067 value changed: 0x0000000000002328 -> 0x0000000000002329
0068
0069 Reported by Kernel Concurrency Sanitizer on:
0070 CPU: 2 PID: 515 Comm: access_thread Not tainted 5.12.0-rc2+ #1
0071 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
0072 ==================================================================
0073
0074 This report is generated where it was not possible to determine the other
0075 racing thread, but a race was inferred due to the data value of the watched
0076 memory location having changed. These reports always show a "value changed"
0077 line. A common reason for reports of this type are missing instrumentation in
0078 the racing thread, but could also occur due to e.g. DMA accesses. Such reports
0079 are shown only if ``CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN=y``, which is
0080 enabled by default.
0081
0082 Selective analysis
0083 ~~~~~~~~~~~~~~~~~~
0084
0085 It may be desirable to disable data race detection for specific accesses,
0086 functions, compilation units, or entire subsystems. For static blacklisting,
0087 the below options are available:
0088
0089 * KCSAN understands the ``data_race(expr)`` annotation, which tells KCSAN that
0090 any data races due to accesses in ``expr`` should be ignored and resulting
0091 behaviour when encountering a data race is deemed safe. Please see
0092 `"Marking Shared-Memory Accesses" in the LKMM`_ for more information.
0093
0094 * Disabling data race detection for entire functions can be accomplished by
0095 using the function attribute ``__no_kcsan``::
0096
0097 __no_kcsan
0098 void foo(void) {
0099 ...
0100
0101 To dynamically limit for which functions to generate reports, see the
0102 `DebugFS interface`_ blacklist/whitelist feature.
0103
0104 * To disable data race detection for a particular compilation unit, add to the
0105 ``Makefile``::
0106
0107 KCSAN_SANITIZE_file.o := n
0108
0109 * To disable data race detection for all compilation units listed in a
0110 ``Makefile``, add to the respective ``Makefile``::
0111
0112 KCSAN_SANITIZE := n
0113
0114 .. _"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
0115
0116 Furthermore, it is possible to tell KCSAN to show or hide entire classes of
0117 data races, depending on preferences. These can be changed via the following
0118 Kconfig options:
0119
0120 * ``CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY``: If enabled and a conflicting write
0121 is observed via a watchpoint, but the data value of the memory location was
0122 observed to remain unchanged, do not report the data race.
0123
0124 * ``CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC``: Assume that plain aligned writes
0125 up to word size are atomic by default. Assumes that such writes are not
0126 subject to unsafe compiler optimizations resulting in data races. The option
0127 causes KCSAN to not report data races due to conflicts where the only plain
0128 accesses are aligned writes up to word size.
0129
0130 * ``CONFIG_KCSAN_PERMISSIVE``: Enable additional permissive rules to ignore
0131 certain classes of common data races. Unlike the above, the rules are more
0132 complex involving value-change patterns, access type, and address. This
0133 option depends on ``CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=y``. For details
0134 please see the ``kernel/kcsan/permissive.h``. Testers and maintainers that
0135 only focus on reports from specific subsystems and not the whole kernel are
0136 recommended to disable this option.
0137
0138 To use the strictest possible rules, select ``CONFIG_KCSAN_STRICT=y``, which
0139 configures KCSAN to follow the Linux-kernel memory consistency model (LKMM) as
0140 closely as possible.
0141
0142 DebugFS interface
0143 ~~~~~~~~~~~~~~~~~
0144
0145 The file ``/sys/kernel/debug/kcsan`` provides the following interface:
0146
0147 * Reading ``/sys/kernel/debug/kcsan`` returns various runtime statistics.
0148
0149 * Writing ``on`` or ``off`` to ``/sys/kernel/debug/kcsan`` allows turning KCSAN
0150 on or off, respectively.
0151
0152 * Writing ``!some_func_name`` to ``/sys/kernel/debug/kcsan`` adds
0153 ``some_func_name`` to the report filter list, which (by default) blacklists
0154 reporting data races where either one of the top stackframes are a function
0155 in the list.
0156
0157 * Writing either ``blacklist`` or ``whitelist`` to ``/sys/kernel/debug/kcsan``
0158 changes the report filtering behaviour. For example, the blacklist feature
0159 can be used to silence frequently occurring data races; the whitelist feature
0160 can help with reproduction and testing of fixes.
0161
0162 Tuning performance
0163 ~~~~~~~~~~~~~~~~~~
0164
0165 Core parameters that affect KCSAN's overall performance and bug detection
0166 ability are exposed as kernel command-line arguments whose defaults can also be
0167 changed via the corresponding Kconfig options.
0168
0169 * ``kcsan.skip_watch`` (``CONFIG_KCSAN_SKIP_WATCH``): Number of per-CPU memory
0170 operations to skip, before another watchpoint is set up. Setting up
0171 watchpoints more frequently will result in the likelihood of races to be
0172 observed to increase. This parameter has the most significant impact on
0173 overall system performance and race detection ability.
0174
0175 * ``kcsan.udelay_task`` (``CONFIG_KCSAN_UDELAY_TASK``): For tasks, the
0176 microsecond delay to stall execution after a watchpoint has been set up.
0177 Larger values result in the window in which we may observe a race to
0178 increase.
0179
0180 * ``kcsan.udelay_interrupt`` (``CONFIG_KCSAN_UDELAY_INTERRUPT``): For
0181 interrupts, the microsecond delay to stall execution after a watchpoint has
0182 been set up. Interrupts have tighter latency requirements, and their delay
0183 should generally be smaller than the one chosen for tasks.
0184
0185 They may be tweaked at runtime via ``/sys/module/kcsan/parameters/``.
0186
0187 Data Races
0188 ----------
0189
0190 In an execution, two memory accesses form a *data race* if they *conflict*,
0191 they happen concurrently in different threads, and at least one of them is a
0192 *plain access*; they *conflict* if both access the same memory location, and at
0193 least one is a write. For a more thorough discussion and definition, see `"Plain
0194 Accesses and Data Races" in the LKMM`_.
0195
0196 .. _"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#n1922
0197
0198 Relationship with the Linux-Kernel Memory Consistency Model (LKMM)
0199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0200
0201 The LKMM defines the propagation and ordering rules of various memory
0202 operations, which gives developers the ability to reason about concurrent code.
0203 Ultimately this allows to determine the possible executions of concurrent code,
0204 and if that code is free from data races.
0205
0206 KCSAN is aware of *marked atomic operations* (``READ_ONCE``, ``WRITE_ONCE``,
0207 ``atomic_*``, etc.), and a subset of ordering guarantees implied by memory
0208 barriers. With ``CONFIG_KCSAN_WEAK_MEMORY=y``, KCSAN models load or store
0209 buffering, and can detect missing ``smp_mb()``, ``smp_wmb()``, ``smp_rmb()``,
0210 ``smp_store_release()``, and all ``atomic_*`` operations with equivalent
0211 implied barriers.
0212
0213 Note, KCSAN will not report all data races due to missing memory ordering,
0214 specifically where a memory barrier would be required to prohibit subsequent
0215 memory operation from reordering before the barrier. Developers should
0216 therefore carefully consider the required memory ordering requirements that
0217 remain unchecked.
0218
0219 Race Detection Beyond Data Races
0220 --------------------------------
0221
0222 For code with complex concurrency design, race-condition bugs may not always
0223 manifest as data races. Race conditions occur if concurrently executing
0224 operations result in unexpected system behaviour. On the other hand, data races
0225 are defined at the C-language level. The following macros can be used to check
0226 properties of concurrent code where bugs would not manifest as data races.
0227
0228 .. kernel-doc:: include/linux/kcsan-checks.h
0229 :functions: ASSERT_EXCLUSIVE_WRITER ASSERT_EXCLUSIVE_WRITER_SCOPED
0230 ASSERT_EXCLUSIVE_ACCESS ASSERT_EXCLUSIVE_ACCESS_SCOPED
0231 ASSERT_EXCLUSIVE_BITS
0232
0233 Implementation Details
0234 ----------------------
0235
0236 KCSAN relies on observing that two accesses happen concurrently. Crucially, we
0237 want to (a) increase the chances of observing races (especially for races that
0238 manifest rarely), and (b) be able to actually observe them. We can accomplish
0239 (a) by injecting various delays, and (b) by using address watchpoints (or
0240 breakpoints).
0241
0242 If we deliberately stall a memory access, while we have a watchpoint for its
0243 address set up, and then observe the watchpoint to fire, two accesses to the
0244 same address just raced. Using hardware watchpoints, this is the approach taken
0245 in `DataCollider
0246 <http://usenix.org/legacy/events/osdi10/tech/full_papers/Erickson.pdf>`_.
0247 Unlike DataCollider, KCSAN does not use hardware watchpoints, but instead
0248 relies on compiler instrumentation and "soft watchpoints".
0249
0250 In KCSAN, watchpoints are implemented using an efficient encoding that stores
0251 access type, size, and address in a long; the benefits of using "soft
0252 watchpoints" are portability and greater flexibility. KCSAN then relies on the
0253 compiler instrumenting plain accesses. For each instrumented plain access:
0254
0255 1. Check if a matching watchpoint exists; if yes, and at least one access is a
0256 write, then we encountered a racing access.
0257
0258 2. Periodically, if no matching watchpoint exists, set up a watchpoint and
0259 stall for a small randomized delay.
0260
0261 3. Also check the data value before the delay, and re-check the data value
0262 after delay; if the values mismatch, we infer a race of unknown origin.
0263
0264 To detect data races between plain and marked accesses, KCSAN also annotates
0265 marked accesses, but only to check if a watchpoint exists; i.e. KCSAN never
0266 sets up a watchpoint on marked accesses. By never setting up watchpoints for
0267 marked operations, if all accesses to a variable that is accessed concurrently
0268 are properly marked, KCSAN will never trigger a watchpoint and therefore never
0269 report the accesses.
0270
0271 Modeling Weak Memory
0272 ~~~~~~~~~~~~~~~~~~~~
0273
0274 KCSAN's approach to detecting data races due to missing memory barriers is
0275 based on modeling access reordering (with ``CONFIG_KCSAN_WEAK_MEMORY=y``).
0276 Each plain memory access for which a watchpoint is set up, is also selected for
0277 simulated reordering within the scope of its function (at most 1 in-flight
0278 access).
0279
0280 Once an access has been selected for reordering, it is checked along every
0281 other access until the end of the function scope. If an appropriate memory
0282 barrier is encountered, the access will no longer be considered for simulated
0283 reordering.
0284
0285 When the result of a memory operation should be ordered by a barrier, KCSAN can
0286 then detect data races where the conflict only occurs as a result of a missing
0287 barrier. Consider the example::
0288
0289 int x, flag;
0290 void T1(void)
0291 {
0292 x = 1; // data race!
0293 WRITE_ONCE(flag, 1); // correct: smp_store_release(&flag, 1)
0294 }
0295 void T2(void)
0296 {
0297 while (!READ_ONCE(flag)); // correct: smp_load_acquire(&flag)
0298 ... = x; // data race!
0299 }
0300
0301 When weak memory modeling is enabled, KCSAN can consider ``x`` in ``T1`` for
0302 simulated reordering. After the write of ``flag``, ``x`` is again checked for
0303 concurrent accesses: because ``T2`` is able to proceed after the write of
0304 ``flag``, a data race is detected. With the correct barriers in place, ``x``
0305 would not be considered for reordering after the proper release of ``flag``,
0306 and no data race would be detected.
0307
0308 Deliberate trade-offs in complexity but also practical limitations mean only a
0309 subset of data races due to missing memory barriers can be detected. With
0310 currently available compiler support, the implementation is limited to modeling
0311 the effects of "buffering" (delaying accesses), since the runtime cannot
0312 "prefetch" accesses. Also recall that watchpoints are only set up for plain
0313 accesses, and the only access type for which KCSAN simulates reordering. This
0314 means reordering of marked accesses is not modeled.
0315
0316 A consequence of the above is that acquire operations do not require barrier
0317 instrumentation (no prefetching). Furthermore, marked accesses introducing
0318 address or control dependencies do not require special handling (the marked
0319 access cannot be reordered, later dependent accesses cannot be prefetched).
0320
0321 Key Properties
0322 ~~~~~~~~~~~~~~
0323
0324 1. **Memory Overhead:** The overall memory overhead is only a few MiB
0325 depending on configuration. The current implementation uses a small array of
0326 longs to encode watchpoint information, which is negligible.
0327
0328 2. **Performance Overhead:** KCSAN's runtime aims to be minimal, using an
0329 efficient watchpoint encoding that does not require acquiring any shared
0330 locks in the fast-path. For kernel boot on a system with 8 CPUs:
0331
0332 - 5.0x slow-down with the default KCSAN config;
0333 - 2.8x slow-down from runtime fast-path overhead only (set very large
0334 ``KCSAN_SKIP_WATCH`` and unset ``KCSAN_SKIP_WATCH_RANDOMIZE``).
0335
0336 3. **Annotation Overheads:** Minimal annotations are required outside the KCSAN
0337 runtime. As a result, maintenance overheads are minimal as the kernel
0338 evolves.
0339
0340 4. **Detects Racy Writes from Devices:** Due to checking data values upon
0341 setting up watchpoints, racy writes from devices can also be detected.
0342
0343 5. **Memory Ordering:** KCSAN is aware of only a subset of LKMM ordering rules;
0344 this may result in missed data races (false negatives).
0345
0346 6. **Analysis Accuracy:** For observed executions, due to using a sampling
0347 strategy, the analysis is *unsound* (false negatives possible), but aims to
0348 be complete (no false positives).
0349
0350 Alternatives Considered
0351 -----------------------
0352
0353 An alternative data race detection approach for the kernel can be found in the
0354 `Kernel Thread Sanitizer (KTSAN) <https://github.com/google/ktsan/wiki>`_.
0355 KTSAN is a happens-before data race detector, which explicitly establishes the
0356 happens-before order between memory operations, which can then be used to
0357 determine data races as defined in `Data Races`_.
0358
0359 To build a correct happens-before relation, KTSAN must be aware of all ordering
0360 rules of the LKMM and synchronization primitives. Unfortunately, any omission
0361 leads to large numbers of false positives, which is especially detrimental in
0362 the context of the kernel which includes numerous custom synchronization
0363 mechanisms. To track the happens-before relation, KTSAN's implementation
0364 requires metadata for each memory location (shadow memory), which for each page
0365 corresponds to 4 pages of shadow memory, and can translate into overhead of
0366 tens of GiB on a large system.