1
1
The Kernel Concurrency Sanitizer (KCSAN)
2
2
========================================
3
3
4
- Overview
5
- --------
6
-
7
- *Kernel Concurrency Sanitizer (KCSAN) * is a dynamic data race detector for
8
- kernel space. KCSAN is a sampling watchpoint-based data race detector. Key
9
- priorities in KCSAN's design are lack of false positives, scalability, and
10
- simplicity. More details can be found in `Implementation Details `_.
11
-
12
- KCSAN uses compile-time instrumentation to instrument memory accesses. KCSAN is
13
- supported in both GCC and Clang. With GCC it requires version 7.3.0 or later.
14
- With Clang it requires version 7.0.0 or later.
4
+ The Kernel Concurrency Sanitizer (KCSAN) is a dynamic race detector, which
5
+ relies on compile-time instrumentation, and uses a watchpoint-based sampling
6
+ approach to detect races. KCSAN's primary purpose is to detect `data races `_.
15
7
16
8
Usage
17
9
-----
18
10
19
- To enable KCSAN configure kernel with::
11
+ KCSAN is supported in both GCC and Clang. With GCC it requires version 7.3.0 or
12
+ later. With Clang it requires version 7.0.0 or later.
13
+
14
+ To enable KCSAN configure the kernel with::
20
15
21
16
CONFIG_KCSAN = y
22
17
23
18
KCSAN provides several other configuration options to customize behaviour (see
24
- their respective help text for more info).
19
+ the respective help text in `` lib/Kconfig.kcsan `` for more info).
25
20
26
21
Error reports
27
22
~~~~~~~~~~~~~
@@ -96,7 +91,8 @@ The other less common type of data race report looks like this::
96
91
This report is generated where it was not possible to determine the other
97
92
racing thread, but a race was inferred due to the data value of the watched
98
93
memory location having changed. These can occur either due to missing
99
- instrumentation or e.g. DMA accesses.
94
+ instrumentation or e.g. DMA accesses. These reports will only be generated if
95
+ ``CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN=y `` (selected by default).
100
96
101
97
Selective analysis
102
98
~~~~~~~~~~~~~~~~~~
@@ -110,9 +106,26 @@ the below options are available:
110
106
behaviour when encountering a data race is deemed safe.
111
107
112
108
* Disabling data race detection for entire functions can be accomplished by
113
- using the function attribute ``__no_kcsan `` (or ``__no_kcsan_or_inline `` for
114
- ``__always_inline `` functions). To dynamically control for which functions
115
- data races are reported, see the `debugfs `_ blacklist/whitelist feature.
109
+ using the function attribute ``__no_kcsan ``::
110
+
111
+ __no_kcsan
112
+ void foo(void) {
113
+ ...
114
+
115
+ To dynamically limit for which functions to generate reports, see the
116
+ `DebugFS interface `_ blacklist/whitelist feature.
117
+
118
+ For ``__always_inline `` functions, replace ``__always_inline `` with
119
+ ``__no_kcsan_or_inline `` (which implies ``__always_inline ``)::
120
+
121
+ static __no_kcsan_or_inline void foo(void) {
122
+ ...
123
+
124
+ Note: Older compiler versions (GCC < 9) also do not always honor the
125
+ ``__no_kcsan `` attribute on regular ``inline `` functions. If false positives
126
+ with these compilers cannot be tolerated, for small functions where
127
+ ``__always_inline `` would be appropriate, ``__no_kcsan_or_inline `` should be
128
+ preferred instead.
116
129
117
130
* To disable data race detection for a particular compilation unit, add to the
118
131
``Makefile ``::
@@ -124,13 +137,29 @@ the below options are available:
124
137
125
138
KCSAN_SANITIZE := n
126
139
127
- debugfs
128
- ~~~~~~~
140
+ Furthermore, it is possible to tell KCSAN to show or hide entire classes of
141
+ data races, depending on preferences. These can be changed via the following
142
+ Kconfig options:
143
+
144
+ * ``CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY ``: If enabled and a conflicting write
145
+ is observed via a watchpoint, but the data value of the memory location was
146
+ observed to remain unchanged, do not report the data race.
147
+
148
+ * ``CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC ``: Assume that plain aligned writes
149
+ up to word size are atomic by default. Assumes that such writes are not
150
+ subject to unsafe compiler optimizations resulting in data races. The option
151
+ causes KCSAN to not report data races due to conflicts where the only plain
152
+ accesses are aligned writes up to word size.
153
+
154
+ DebugFS interface
155
+ ~~~~~~~~~~~~~~~~~
129
156
130
- * The file ``/sys/kernel/debug/kcsan `` can be read to get stats.
157
+ The file ``/sys/kernel/debug/kcsan `` provides the following interface:
131
158
132
- * KCSAN can be turned on or off by writing ``on `` or ``off `` to
133
- ``/sys/kernel/debug/kcsan ``.
159
+ * Reading ``/sys/kernel/debug/kcsan `` returns various runtime statistics.
160
+
161
+ * Writing ``on `` or ``off `` to ``/sys/kernel/debug/kcsan `` allows turning KCSAN
162
+ on or off, respectively.
134
163
135
164
* Writing ``!some_func_name `` to ``/sys/kernel/debug/kcsan `` adds
136
165
``some_func_name `` to the report filter list, which (by default) blacklists
@@ -142,91 +171,121 @@ debugfs
142
171
can be used to silence frequently occurring data races; the whitelist feature
143
172
can help with reproduction and testing of fixes.
144
173
174
+ Tuning performance
175
+ ~~~~~~~~~~~~~~~~~~
176
+
177
+ Core parameters that affect KCSAN's overall performance and bug detection
178
+ ability are exposed as kernel command-line arguments whose defaults can also be
179
+ changed via the corresponding Kconfig options.
180
+
181
+ * ``kcsan.skip_watch `` (``CONFIG_KCSAN_SKIP_WATCH ``): Number of per-CPU memory
182
+ operations to skip, before another watchpoint is set up. Setting up
183
+ watchpoints more frequently will result in the likelihood of races to be
184
+ observed to increase. This parameter has the most significant impact on
185
+ overall system performance and race detection ability.
186
+
187
+ * ``kcsan.udelay_task `` (``CONFIG_KCSAN_UDELAY_TASK ``): For tasks, the
188
+ microsecond delay to stall execution after a watchpoint has been set up.
189
+ Larger values result in the window in which we may observe a race to
190
+ increase.
191
+
192
+ * ``kcsan.udelay_interrupt `` (``CONFIG_KCSAN_UDELAY_INTERRUPT ``): For
193
+ interrupts, the microsecond delay to stall execution after a watchpoint has
194
+ been set up. Interrupts have tighter latency requirements, and their delay
195
+ should generally be smaller than the one chosen for tasks.
196
+
197
+ They may be tweaked at runtime via ``/sys/module/kcsan/parameters/ ``.
198
+
145
199
Data Races
146
200
----------
147
201
148
- Informally, two operations *conflict * if they access the same memory location,
149
- and at least one of them is a write operation. In an execution, two memory
150
- operations from different threads form a **data race ** if they *conflict *, at
151
- least one of them is a *plain access * (non-atomic), and they are *unordered * in
152
- the "happens-before" order according to the `LKMM
153
- <../../tools/memory-model/Documentation/explanation.txt> `_.
202
+ In an execution, two memory accesses form a *data race * if they *conflict *,
203
+ they happen concurrently in different threads, and at least one of them is a
204
+ *plain access *; they *conflict * if both access the same memory location, and at
205
+ least one is a write. For a more thorough discussion and definition, see `"Plain
206
+ Accesses and Data Races" in the LKMM `_.
154
207
155
- Relationship with the Linux Kernel Memory Model (LKMM)
156
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
208
+ .. _"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
209
+
210
+ Relationship with the Linux-Kernel Memory Consistency Model (LKMM)
211
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157
212
158
213
The LKMM defines the propagation and ordering rules of various memory
159
214
operations, which gives developers the ability to reason about concurrent code.
160
215
Ultimately this allows to determine the possible executions of concurrent code,
161
216
and if that code is free from data races.
162
217
163
- KCSAN is aware of *atomic * accesses (``READ_ONCE ``, ``WRITE_ONCE ``,
164
- ``atomic_* ``, etc.), but is oblivious of any ordering guarantees. In other
165
- words, KCSAN assumes that as long as a plain access is not observed to race
166
- with another conflicting access, memory operations are correctly ordered.
218
+ KCSAN is aware of *marked atomic operations * (``READ_ONCE ``, ``WRITE_ONCE ``,
219
+ ``atomic_* ``, etc.), but is oblivious of any ordering guarantees and simply
220
+ assumes that memory barriers are placed correctly. In other words, KCSAN
221
+ assumes that as long as a plain access is not observed to race with another
222
+ conflicting access, memory operations are correctly ordered.
167
223
168
224
This means that KCSAN will not report *potential * data races due to missing
169
- memory ordering. If, however, missing memory ordering (that is observable with
170
- a particular compiler and architecture) leads to an observable data race (e.g.
171
- entering a critical section erroneously), KCSAN would report the resulting
172
- data race.
173
-
174
- Race conditions vs. data races
175
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176
-
177
- Race conditions are logic bugs, where unexpected interleaving of racing
178
- concurrent operations result in an erroneous state.
179
-
180
- Data races on the other hand are defined at the *memory model/language level *.
181
- Many data races are also harmful race conditions, which a tool like KCSAN
182
- reports! However, not all data races are race conditions and vice-versa.
183
- KCSAN's intent is to report data races according to the LKMM. A data race
184
- detector can only work at the memory model/language level.
185
-
186
- Deeper analysis, to find high-level race conditions only, requires conveying
187
- the intended kernel logic to a tool. This requires (1) the developer writing a
188
- specification or model of their code, and then (2) the tool verifying that the
189
- implementation matches. This has been done for small bits of code using model
190
- checkers and other formal methods, but does not scale to the level of what can
191
- be covered with a dynamic analysis based data race detector such as KCSAN.
192
-
193
- For reasons outlined in this `article <https://lwn.net/Articles/793253/ >`_,
194
- data races can be much more subtle, but can cause no less harm than high-level
195
- race conditions.
225
+ memory ordering. Developers should therefore carefully consider the required
226
+ memory ordering requirements that remain unchecked. If, however, missing
227
+ memory ordering (that is observable with a particular compiler and
228
+ architecture) leads to an observable data race (e.g. entering a critical
229
+ section erroneously), KCSAN would report the resulting data race.
230
+
231
+ Race Detection Beyond Data Races
232
+ --------------------------------
233
+
234
+ For code with complex concurrency design, race-condition bugs may not always
235
+ manifest as data races. Race conditions occur if concurrently executing
236
+ operations result in unexpected system behaviour. On the other hand, data races
237
+ are defined at the C-language level. The following macros can be used to check
238
+ properties of concurrent code where bugs would not manifest as data races.
239
+
240
+ .. kernel-doc :: include/linux/kcsan-checks.h
241
+ :functions: ASSERT_EXCLUSIVE_WRITER ASSERT_EXCLUSIVE_WRITER_SCOPED
242
+ ASSERT_EXCLUSIVE_ACCESS ASSERT_EXCLUSIVE_ACCESS_SCOPED
243
+ ASSERT_EXCLUSIVE_BITS
196
244
197
245
Implementation Details
198
246
----------------------
199
247
200
- The general approach is inspired by `DataCollider
248
+ KCSAN relies on observing that two accesses happen concurrently. Crucially, we
249
+ want to (a) increase the chances of observing races (especially for races that
250
+ manifest rarely), and (b) be able to actually observe them. We can accomplish
251
+ (a) by injecting various delays, and (b) by using address watchpoints (or
252
+ breakpoints).
253
+
254
+ If we deliberately stall a memory access, while we have a watchpoint for its
255
+ address set up, and then observe the watchpoint to fire, two accesses to the
256
+ same address just raced. Using hardware watchpoints, this is the approach taken
257
+ in `DataCollider
201
258
<http://usenix.org/legacy/events/osdi10/tech/full_papers/Erickson.pdf> `_.
202
259
Unlike DataCollider, KCSAN does not use hardware watchpoints, but instead
203
- relies on compiler instrumentation. Watchpoints are implemented using an
204
- efficient encoding that stores access type, size, and address in a long; the
205
- benefits of using "soft watchpoints" are portability and greater flexibility in
206
- limiting which accesses trigger a watchpoint.
260
+ relies on compiler instrumentation and "soft watchpoints".
207
261
208
- More specifically, KCSAN requires instrumenting plain (unmarked, non-atomic)
209
- memory operations; for each instrumented plain access:
262
+ In KCSAN, watchpoints are implemented using an efficient encoding that stores
263
+ access type, size, and address in a long; the benefits of using "soft
264
+ watchpoints" are portability and greater flexibility. KCSAN then relies on the
265
+ compiler instrumenting plain accesses. For each instrumented plain access:
210
266
211
267
1. Check if a matching watchpoint exists; if yes, and at least one access is a
212
268
write, then we encountered a racing access.
213
269
214
270
2. Periodically, if no matching watchpoint exists, set up a watchpoint and
215
- stall for a small delay.
271
+ stall for a small randomized delay.
216
272
217
273
3. Also check the data value before the delay, and re-check the data value
218
274
after delay; if the values mismatch, we infer a race of unknown origin.
219
275
220
- To detect data races between plain and atomic memory operations, KCSAN also
221
- annotates atomic accesses, but only to check if a watchpoint exists
222
- (``kcsan_check_atomic_* ``); i.e. KCSAN never sets up a watchpoint on atomic
223
- accesses.
276
+ To detect data races between plain and marked accesses, KCSAN also annotates
277
+ marked accesses, but only to check if a watchpoint exists; i.e. KCSAN never
278
+ sets up a watchpoint on marked accesses. By never setting up watchpoints for
279
+ marked operations, if all accesses to a variable that is accessed concurrently
280
+ are properly marked, KCSAN will never trigger a watchpoint and therefore never
281
+ report the accesses.
224
282
225
283
Key Properties
226
284
~~~~~~~~~~~~~~
227
285
228
- 1. **Memory Overhead: ** The current implementation uses a small array of longs
229
- to encode watchpoint information, which is negligible.
286
+ 1. **Memory Overhead: ** The overall memory overhead is only a few MiB
287
+ depending on configuration. The current implementation uses a small array of
288
+ longs to encode watchpoint information, which is negligible.
230
289
231
290
2. **Performance Overhead: ** KCSAN's runtime aims to be minimal, using an
232
291
efficient watchpoint encoding that does not require acquiring any shared
@@ -253,14 +312,17 @@ Key Properties
253
312
Alternatives Considered
254
313
-----------------------
255
314
256
- An alternative data race detection approach for the kernel can be found in
315
+ An alternative data race detection approach for the kernel can be found in the
257
316
`Kernel Thread Sanitizer (KTSAN) <https://github.com/google/ktsan/wiki >`_.
258
317
KTSAN is a happens-before data race detector, which explicitly establishes the
259
318
happens-before order between memory operations, which can then be used to
260
- determine data races as defined in `Data Races `_. To build a correct
261
- happens-before relation, KTSAN must be aware of all ordering rules of the LKMM
262
- and synchronization primitives. Unfortunately, any omission leads to false
263
- positives, which is especially important in the context of the kernel which
264
- includes numerous custom synchronization mechanisms. Furthermore, KTSAN's
265
- implementation requires metadata for each memory location (shadow memory);
266
- currently, for each page, KTSAN requires 4 pages of shadow memory.
319
+ determine data races as defined in `Data Races `_.
320
+
321
+ To build a correct happens-before relation, KTSAN must be aware of all ordering
322
+ rules of the LKMM and synchronization primitives. Unfortunately, any omission
323
+ leads to large numbers of false positives, which is especially detrimental in
324
+ the context of the kernel which includes numerous custom synchronization
325
+ mechanisms. To track the happens-before relation, KTSAN's implementation
326
+ requires metadata for each memory location (shadow memory), which for each page
327
+ corresponds to 4 pages of shadow memory, and can translate into overhead of
328
+ tens of GiB on a large system.
0 commit comments