1 MARKING SHARED-MEMORY ACCESSES 1 MARKING SHARED-MEMORY ACCESSES 2 ============================== 2 ============================== 3 3 4 This document provides guidelines for marking 4 This document provides guidelines for marking intentionally concurrent 5 normal accesses to shared memory, that is "nor 5 normal accesses to shared memory, that is "normal" as in accesses that do 6 not use read-modify-write atomic operations. 6 not use read-modify-write atomic operations. It also describes how to 7 document these accesses, both with comments an 7 document these accesses, both with comments and with special assertions 8 processed by the Kernel Concurrency Sanitizer 8 processed by the Kernel Concurrency Sanitizer (KCSAN). This discussion 9 builds on an earlier LWN article [1] and Linux !! 9 builds on an earlier LWN article [1]. 10 session [2]. << 11 10 12 11 13 ACCESS-MARKING OPTIONS 12 ACCESS-MARKING OPTIONS 14 ====================== 13 ====================== 15 14 16 The Linux kernel provides the following access 15 The Linux kernel provides the following access-marking options: 17 16 18 1. Plain C-language accesses (unmarked), 17 1. Plain C-language accesses (unmarked), for example, "a = b;" 19 18 20 2. Data-race marking, for example, "data_ 19 2. Data-race marking, for example, "data_race(a = b);" 21 20 22 3. READ_ONCE(), for example, "a = READ_ON 21 3. READ_ONCE(), for example, "a = READ_ONCE(b);" 23 The various forms of atomic_read() als 22 The various forms of atomic_read() also fit in here. 24 23 25 4. WRITE_ONCE(), for example, "WRITE_ONCE 24 4. WRITE_ONCE(), for example, "WRITE_ONCE(a, b);" 26 The various forms of atomic_set() also 25 The various forms of atomic_set() also fit in here. 27 26 28 5. __data_racy, for example "int __data_r << 29 << 30 6. KCSAN's negative-marking assertions, A << 31 and ASSERT_EXCLUSIVE_WRITER(), are des << 32 "ACCESS-DOCUMENTATION OPTIONS" section << 33 27 34 These may be used in combination, as shown in 28 These may be used in combination, as shown in this admittedly improbable 35 example: 29 example: 36 30 37 WRITE_ONCE(a, b + data_race(c + d) + R 31 WRITE_ONCE(a, b + data_race(c + d) + READ_ONCE(e)); 38 32 39 Neither plain C-language accesses nor data_rac 33 Neither plain C-language accesses nor data_race() (#1 and #2 above) place 40 any sort of constraint on the compiler's choic !! 34 any sort of constraint on the compiler's choice of optimizations [2]. 41 In contrast, READ_ONCE() and WRITE_ONCE() (#3 35 In contrast, READ_ONCE() and WRITE_ONCE() (#3 and #4 above) restrict the 42 compiler's use of code-motion and common-subex 36 compiler's use of code-motion and common-subexpression optimizations. 43 Therefore, if a given access is involved in an 37 Therefore, if a given access is involved in an intentional data race, 44 using READ_ONCE() for loads and WRITE_ONCE() f 38 using READ_ONCE() for loads and WRITE_ONCE() for stores is usually 45 preferable to data_race(), which in turn is us 39 preferable to data_race(), which in turn is usually preferable to plain 46 C-language accesses. It is permissible to com !! 40 C-language accesses. 47 data_race(READ_ONCE(a)), which will both restr << 48 and disable KCSAN diagnostics. << 49 41 50 KCSAN will complain about many types of data r 42 KCSAN will complain about many types of data races involving plain 51 C-language accesses, but marking all accesses 43 C-language accesses, but marking all accesses involved in a given data 52 race with one of data_race(), READ_ONCE(), or 44 race with one of data_race(), READ_ONCE(), or WRITE_ONCE(), will prevent 53 KCSAN from complaining. Of course, lack of KC 45 KCSAN from complaining. Of course, lack of KCSAN complaints does not 54 imply correct code. Therefore, please take a 46 imply correct code. Therefore, please take a thoughtful approach 55 when responding to KCSAN complaints. Churning 47 when responding to KCSAN complaints. Churning the code base with 56 ill-considered additions of data_race(), READ_ 48 ill-considered additions of data_race(), READ_ONCE(), and WRITE_ONCE() 57 is unhelpful. 49 is unhelpful. 58 50 59 In fact, the following sections describe situa 51 In fact, the following sections describe situations where use of 60 data_race() and even plain C-language accesses 52 data_race() and even plain C-language accesses is preferable to 61 READ_ONCE() and WRITE_ONCE(). 53 READ_ONCE() and WRITE_ONCE(). 62 54 63 55 64 Use of the data_race() Macro 56 Use of the data_race() Macro 65 ---------------------------- 57 ---------------------------- 66 58 67 Here are some situations where data_race() sho 59 Here are some situations where data_race() should be used instead of 68 READ_ONCE() and WRITE_ONCE(): 60 READ_ONCE() and WRITE_ONCE(): 69 61 70 1. Data-racy loads from shared variables 62 1. Data-racy loads from shared variables whose values are used only 71 for diagnostic purposes. 63 for diagnostic purposes. 72 64 73 2. Data-racy reads whose values are check 65 2. Data-racy reads whose values are checked against marked reload. 74 66 75 3. Reads whose values feed into error-tol 67 3. Reads whose values feed into error-tolerant heuristics. 76 68 77 4. Writes setting values that feed into e 69 4. Writes setting values that feed into error-tolerant heuristics. 78 70 79 71 80 Data-Racy Reads for Approximate Diagnostics 72 Data-Racy Reads for Approximate Diagnostics 81 73 82 Approximate diagnostics include lockdep report 74 Approximate diagnostics include lockdep reports, monitoring/statistics 83 (including /proc and /sys output), WARN*()/BUG 75 (including /proc and /sys output), WARN*()/BUG*() checks whose return 84 values are ignored, and other situations where 76 values are ignored, and other situations where reads from shared variables 85 are not an integral part of the core concurren 77 are not an integral part of the core concurrency design. 86 78 87 In fact, use of data_race() instead READ_ONCE( 79 In fact, use of data_race() instead READ_ONCE() for these diagnostic 88 reads can enable better checking of the remain 80 reads can enable better checking of the remaining accesses implementing 89 the core concurrency design. For example, sup 81 the core concurrency design. For example, suppose that the core design 90 prevents any non-diagnostic reads from shared 82 prevents any non-diagnostic reads from shared variable x from running 91 concurrently with updates to x. Then using pl 83 concurrently with updates to x. Then using plain C-language writes 92 to x allows KCSAN to detect reads from x from 84 to x allows KCSAN to detect reads from x from within regions of code 93 that fail to exclude the updates. In this cas 85 that fail to exclude the updates. In this case, it is important to use 94 data_race() for the diagnostic reads because o 86 data_race() for the diagnostic reads because otherwise KCSAN would give 95 false-positive warnings about these diagnostic 87 false-positive warnings about these diagnostic reads. 96 88 97 If it is necessary to both restrict compiler o << 98 KCSAN diagnostics, use both data_race() and RE << 99 data_race(READ_ONCE(a)). << 100 << 101 In theory, plain C-language loads can also be 89 In theory, plain C-language loads can also be used for this use case. 102 However, in practice this will have the disadv 90 However, in practice this will have the disadvantage of causing KCSAN 103 to generate false positives because KCSAN will 91 to generate false positives because KCSAN will have no way of knowing 104 that the resulting data race was intentional. 92 that the resulting data race was intentional. 105 93 106 94 107 Data-Racy Reads That Are Checked Against Marke 95 Data-Racy Reads That Are Checked Against Marked Reload 108 96 109 The values from some reads are not implicitly 97 The values from some reads are not implicitly trusted. They are instead 110 fed into some operation that checks the full v 98 fed into some operation that checks the full value against a later marked 111 load from memory, which means that the occasio 99 load from memory, which means that the occasional arbitrarily bogus value 112 is not a problem. For example, if a bogus val 100 is not a problem. For example, if a bogus value is fed into cmpxchg(), 113 all that happens is that this cmpxchg() fails, 101 all that happens is that this cmpxchg() fails, which normally results 114 in a retry. Unless the race condition that re 102 in a retry. Unless the race condition that resulted in the bogus value 115 recurs, this retry will with high probability 103 recurs, this retry will with high probability succeed, so no harm done. 116 104 117 However, please keep in mind that a data_race( 105 However, please keep in mind that a data_race() load feeding into 118 a cmpxchg_relaxed() might still be subject to 106 a cmpxchg_relaxed() might still be subject to load fusing on some 119 architectures. Therefore, it is best to captu 107 architectures. Therefore, it is best to capture the return value from 120 the failing cmpxchg() for the next iteration o 108 the failing cmpxchg() for the next iteration of the loop, an approach 121 that provides the compiler much less scope for 109 that provides the compiler much less scope for mischievous optimizations. 122 Capturing the return value from cmpxchg() also 110 Capturing the return value from cmpxchg() also saves a memory reference 123 in many cases. 111 in many cases. 124 112 125 In theory, plain C-language loads can also be 113 In theory, plain C-language loads can also be used for this use case. 126 However, in practice this will have the disadv 114 However, in practice this will have the disadvantage of causing KCSAN 127 to generate false positives because KCSAN will 115 to generate false positives because KCSAN will have no way of knowing 128 that the resulting data race was intentional. 116 that the resulting data race was intentional. 129 117 130 118 131 Reads Feeding Into Error-Tolerant Heuristics 119 Reads Feeding Into Error-Tolerant Heuristics 132 120 133 Values from some reads feed into heuristics th 121 Values from some reads feed into heuristics that can tolerate occasional 134 errors. Such reads can use data_race(), thus 122 errors. Such reads can use data_race(), thus allowing KCSAN to focus on 135 the other accesses to the relevant shared vari 123 the other accesses to the relevant shared variables. But please note 136 that data_race() loads are subject to load fus 124 that data_race() loads are subject to load fusing, which can result in 137 consistent errors, which in turn are quite cap 125 consistent errors, which in turn are quite capable of breaking heuristics. 138 Therefore use of data_race() should be limited 126 Therefore use of data_race() should be limited to cases where some other 139 code (such as a barrier() call) will force the 127 code (such as a barrier() call) will force the occasional reload. 140 128 141 Note that this use case requires that the heur << 142 any possible error. In contrast, if the heuri << 143 confused by one or more of the possible errone << 144 instead of data_race(). << 145 << 146 In theory, plain C-language loads can also be 129 In theory, plain C-language loads can also be used for this use case. 147 However, in practice this will have the disadv 130 However, in practice this will have the disadvantage of causing KCSAN 148 to generate false positives because KCSAN will 131 to generate false positives because KCSAN will have no way of knowing 149 that the resulting data race was intentional. 132 that the resulting data race was intentional. 150 133 151 134 152 Writes Setting Values Feeding Into Error-Toler 135 Writes Setting Values Feeding Into Error-Tolerant Heuristics 153 136 154 The values read into error-tolerant heuristics 137 The values read into error-tolerant heuristics come from somewhere, 155 for example, from sysfs. This means that some 138 for example, from sysfs. This means that some code in sysfs writes 156 to this same variable, and these writes can al 139 to this same variable, and these writes can also use data_race(). 157 After all, if the heuristic can tolerate the o 140 After all, if the heuristic can tolerate the occasional bogus value 158 due to compiler-mangled reads, it can also tol 141 due to compiler-mangled reads, it can also tolerate the occasional 159 compiler-mangled write, at least assuming that 142 compiler-mangled write, at least assuming that the proper value is in 160 place once the write completes. 143 place once the write completes. 161 144 162 Plain C-language stores can also be used for t 145 Plain C-language stores can also be used for this use case. However, 163 in kernels built with CONFIG_KCSAN_ASSUME_PLAI 146 in kernels built with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n, this 164 will have the disadvantage of causing KCSAN to 147 will have the disadvantage of causing KCSAN to generate false positives 165 because KCSAN will have no way of knowing that 148 because KCSAN will have no way of knowing that the resulting data race 166 was intentional. 149 was intentional. 167 150 168 151 169 Use of Plain C-Language Accesses 152 Use of Plain C-Language Accesses 170 -------------------------------- 153 -------------------------------- 171 154 172 Here are some example situations where plain C 155 Here are some example situations where plain C-language accesses should 173 used instead of READ_ONCE(), WRITE_ONCE(), and 156 used instead of READ_ONCE(), WRITE_ONCE(), and data_race(): 174 157 175 1. Accesses protected by mutual exclusion 158 1. Accesses protected by mutual exclusion, including strict locking 176 and sequence locking. 159 and sequence locking. 177 160 178 2. Initialization-time and cleanup-time a 161 2. Initialization-time and cleanup-time accesses. This covers a 179 wide variety of situations, including 162 wide variety of situations, including the uniprocessor phase of 180 system boot, variables to be used by n 163 system boot, variables to be used by not-yet-spawned kthreads, 181 structures not yet published to refere 164 structures not yet published to reference-counted or RCU-protected 182 data structures, and the cleanup side 165 data structures, and the cleanup side of any of these situations. 183 166 184 3. Per-CPU variables that are not accesse 167 3. Per-CPU variables that are not accessed from other CPUs. 185 168 186 4. Private per-task variables, including 169 4. Private per-task variables, including on-stack variables, some 187 fields in the task_struct structure, a 170 fields in the task_struct structure, and task-private heap data. 188 171 189 5. Any other loads for which there is not 172 5. Any other loads for which there is not supposed to be a concurrent 190 store to that same variable. 173 store to that same variable. 191 174 192 6. Any other stores for which there shoul 175 6. Any other stores for which there should be neither concurrent 193 loads nor concurrent stores to that sa 176 loads nor concurrent stores to that same variable. 194 177 195 But note that KCSAN makes two explicit 178 But note that KCSAN makes two explicit exceptions to this rule 196 by default, refraining from flagging p 179 by default, refraining from flagging plain C-language stores: 197 180 198 a. No matter what. You can overr 181 a. No matter what. You can override this default by building 199 with CONFIG_KCSAN_ASSUME_PLAIN 182 with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n. 200 183 201 b. When the store writes the valu 184 b. When the store writes the value already contained in 202 that variable. You can overri 185 that variable. You can override this default by building 203 with CONFIG_KCSAN_REPORT_VALUE 186 with CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=n. 204 187 205 c. When one of the stores is in a 188 c. When one of the stores is in an interrupt handler and 206 the other in the interrupted c 189 the other in the interrupted code. You can override this 207 default by building with CONFI 190 default by building with CONFIG_KCSAN_INTERRUPT_WATCHER=y. 208 191 209 Note that it is important to use plain C-langu 192 Note that it is important to use plain C-language accesses in these cases, 210 because doing otherwise prevents KCSAN from de 193 because doing otherwise prevents KCSAN from detecting violations of your 211 code's synchronization rules. 194 code's synchronization rules. 212 195 213 196 214 Use of __data_racy << 215 ------------------ << 216 << 217 Adding the __data_racy type qualifier to the d << 218 causes KCSAN to treat all accesses to that var << 219 enclosed by data_race(). However, __data_racy << 220 compiler, though one could imagine hardened ke << 221 __data_racy type qualifier as if it was the vo << 222 << 223 Note well that __data_racy is subject to the s << 224 rules as are other type qualifiers such as con << 225 For example: << 226 << 227 int __data_racy *p; // Pointer to data << 228 int *__data_racy p; // Data-racy point << 229 << 230 << 231 ACCESS-DOCUMENTATION OPTIONS 197 ACCESS-DOCUMENTATION OPTIONS 232 ============================ 198 ============================ 233 199 234 It is important to comment marked accesses so 200 It is important to comment marked accesses so that people reading your 235 code, yourself included, are reminded of the s 201 code, yourself included, are reminded of the synchronization design. 236 However, it is even more important to comment 202 However, it is even more important to comment plain C-language accesses 237 that are intentionally involved in data races. 203 that are intentionally involved in data races. Such comments are 238 needed to remind people reading your code, aga 204 needed to remind people reading your code, again, yourself included, 239 of how the compiler has been prevented from op 205 of how the compiler has been prevented from optimizing those accesses 240 into concurrency bugs. 206 into concurrency bugs. 241 207 242 It is also possible to tell KCSAN about your s 208 It is also possible to tell KCSAN about your synchronization design. 243 For example, ASSERT_EXCLUSIVE_ACCESS(foo) tell 209 For example, ASSERT_EXCLUSIVE_ACCESS(foo) tells KCSAN that any 244 concurrent access to variable foo by any other 210 concurrent access to variable foo by any other CPU is an error, even 245 if that concurrent access is marked with READ_ 211 if that concurrent access is marked with READ_ONCE(). In addition, 246 ASSERT_EXCLUSIVE_WRITER(foo) tells KCSAN that 212 ASSERT_EXCLUSIVE_WRITER(foo) tells KCSAN that although it is OK for there 247 to be concurrent reads from foo from other CPU 213 to be concurrent reads from foo from other CPUs, it is an error for some 248 other CPU to be concurrently writing to foo, e 214 other CPU to be concurrently writing to foo, even if that concurrent 249 write is marked with data_race() or WRITE_ONCE 215 write is marked with data_race() or WRITE_ONCE(). 250 216 251 Note that although KCSAN will call out data ra 217 Note that although KCSAN will call out data races involving either 252 ASSERT_EXCLUSIVE_ACCESS() or ASSERT_EXCLUSIVE_ 218 ASSERT_EXCLUSIVE_ACCESS() or ASSERT_EXCLUSIVE_WRITER() on the one hand 253 and data_race() writes on the other, KCSAN wil 219 and data_race() writes on the other, KCSAN will not report the location 254 of these data_race() writes. 220 of these data_race() writes. 255 221 256 222 257 EXAMPLES 223 EXAMPLES 258 ======== 224 ======== 259 225 260 As noted earlier, the goal is to prevent the c 226 As noted earlier, the goal is to prevent the compiler from destroying 261 your concurrent algorithm, to help the human r 227 your concurrent algorithm, to help the human reader, and to inform 262 KCSAN of aspects of your concurrency design. 228 KCSAN of aspects of your concurrency design. This section looks at a 263 few examples showing how this can be done. 229 few examples showing how this can be done. 264 230 265 231 266 Lock Protection With Lockless Diagnostic Acces 232 Lock Protection With Lockless Diagnostic Access 267 ---------------------------------------------- 233 ----------------------------------------------- 268 234 269 For example, suppose a shared variable "foo" i 235 For example, suppose a shared variable "foo" is read only while a 270 reader-writer spinlock is read-held, written o 236 reader-writer spinlock is read-held, written only while that same 271 spinlock is write-held, except that it is also 237 spinlock is write-held, except that it is also read locklessly for 272 diagnostic purposes. The code might look as f 238 diagnostic purposes. The code might look as follows: 273 239 274 int foo; 240 int foo; 275 DEFINE_RWLOCK(foo_rwlock); 241 DEFINE_RWLOCK(foo_rwlock); 276 242 277 void update_foo(int newval) 243 void update_foo(int newval) 278 { 244 { 279 write_lock(&foo_rwlock); 245 write_lock(&foo_rwlock); 280 foo = newval; 246 foo = newval; 281 do_something(newval); 247 do_something(newval); 282 write_unlock(&foo_rwlock); 248 write_unlock(&foo_rwlock); 283 } 249 } 284 250 285 int read_foo(void) 251 int read_foo(void) 286 { 252 { 287 int ret; 253 int ret; 288 254 289 read_lock(&foo_rwlock); 255 read_lock(&foo_rwlock); 290 do_something_else(); 256 do_something_else(); 291 ret = foo; 257 ret = foo; 292 read_unlock(&foo_rwlock); 258 read_unlock(&foo_rwlock); 293 return ret; 259 return ret; 294 } 260 } 295 261 296 void read_foo_diagnostic(void) !! 262 int read_foo_diagnostic(void) 297 { 263 { 298 pr_info("Current value of foo: !! 264 return data_race(foo); 299 } 265 } 300 266 301 The reader-writer lock prevents the compiler f 267 The reader-writer lock prevents the compiler from introducing concurrency 302 bugs into any part of the main algorithm using 268 bugs into any part of the main algorithm using foo, which means that 303 the accesses to foo within both update_foo() a 269 the accesses to foo within both update_foo() and read_foo() can (and 304 should) be plain C-language accesses. One ben 270 should) be plain C-language accesses. One benefit of making them be 305 plain C-language accesses is that KCSAN can de 271 plain C-language accesses is that KCSAN can detect any erroneous lockless 306 reads from or updates to foo. The data_race() 272 reads from or updates to foo. The data_race() in read_foo_diagnostic() 307 tells KCSAN that data races are expected, and 273 tells KCSAN that data races are expected, and should be silently 308 ignored. This data_race() also tells the huma 274 ignored. This data_race() also tells the human reading the code that 309 read_foo_diagnostic() might sometimes return a 275 read_foo_diagnostic() might sometimes return a bogus value. 310 276 311 If it is necessary to suppress compiler optimi !! 277 However, please note that your kernel must be built with 312 buggy lockless writes, read_foo_diagnostic() c !! 278 CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n in order for KCSAN to 313 !! 279 detect a buggy lockless write. If you need KCSAN to detect such a 314 void read_foo_diagnostic(void) !! 280 write even if that write did not change the value of foo, you also 315 { !! 281 need CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=n. If you need KCSAN to 316 pr_info("Current value of foo: !! 282 detect such a write happening in an interrupt handler running on the 317 } !! 283 same CPU doing the legitimate lock-protected write, you also need 318 !! 284 CONFIG_KCSAN_INTERRUPT_WATCHER=y. With some or all of these Kconfig 319 Alternatively, given that KCSAN is to ignore a !! 285 options set properly, KCSAN can be quite helpful, although it is not 320 this function can be marked __no_kcsan and the !! 286 necessarily a full replacement for hardware watchpoints. On the other 321 !! 287 hand, neither are hardware watchpoints a full replacement for KCSAN 322 void __no_kcsan read_foo_diagnostic(vo !! 288 because it is not always easy to tell hardware watchpoint to conditionally 323 { !! 289 trap on accesses. 324 pr_info("Current value of foo: << 325 } << 326 << 327 However, in order for KCSAN to detect buggy lo << 328 must be built with CONFIG_KCSAN_ASSUME_PLAIN_W << 329 need KCSAN to detect such a write even if that << 330 the value of foo, you also need CONFIG_KCSAN_R << 331 If you need KCSAN to detect such a write happe << 332 running on the same CPU doing the legitimate l << 333 also need CONFIG_KCSAN_INTERRUPT_WATCHER=y. W << 334 Kconfig options set properly, KCSAN can be qui << 335 it is not necessarily a full replacement for h << 336 On the other hand, neither are hardware watchp << 337 for KCSAN because it is not always easy to tel << 338 conditionally trap on accesses. << 339 290 340 291 341 Lock-Protected Writes With Lockless Reads 292 Lock-Protected Writes With Lockless Reads 342 ----------------------------------------- 293 ----------------------------------------- 343 294 344 For another example, suppose a shared variable 295 For another example, suppose a shared variable "foo" is updated only 345 while holding a spinlock, but is read lockless 296 while holding a spinlock, but is read locklessly. The code might look 346 as follows: 297 as follows: 347 298 348 int foo; 299 int foo; 349 DEFINE_SPINLOCK(foo_lock); 300 DEFINE_SPINLOCK(foo_lock); 350 301 351 void update_foo(int newval) 302 void update_foo(int newval) 352 { 303 { 353 spin_lock(&foo_lock); 304 spin_lock(&foo_lock); 354 WRITE_ONCE(foo, newval); 305 WRITE_ONCE(foo, newval); 355 ASSERT_EXCLUSIVE_WRITER(foo); 306 ASSERT_EXCLUSIVE_WRITER(foo); 356 do_something(newval); 307 do_something(newval); 357 spin_unlock(&foo_wlock); 308 spin_unlock(&foo_wlock); 358 } 309 } 359 310 360 int read_foo(void) 311 int read_foo(void) 361 { 312 { 362 do_something_else(); 313 do_something_else(); 363 return READ_ONCE(foo); 314 return READ_ONCE(foo); 364 } 315 } 365 316 366 Because foo is read locklessly, all accesses a 317 Because foo is read locklessly, all accesses are marked. The purpose 367 of the ASSERT_EXCLUSIVE_WRITER() is to allow K 318 of the ASSERT_EXCLUSIVE_WRITER() is to allow KCSAN to check for a buggy 368 concurrent write, whether marked or not. !! 319 concurrent lockless write. 369 << 370 << 371 Lock-Protected Writes With Heuristic Lockless << 372 ---------------------------------------------- << 373 << 374 For another example, suppose that the code can << 375 a per-data-structure lock, but there are times << 376 is required. These times are indicated via a << 377 might look as follows, and is based loosely on << 378 nf_conntrack_all_lock(), and nf_conntrack_all_ << 379 << 380 bool global_flag; << 381 DEFINE_SPINLOCK(global_lock); << 382 struct foo { << 383 spinlock_t f_lock; << 384 int f_data; << 385 }; << 386 << 387 /* All foo structures are in the follo << 388 int nfoo; << 389 struct foo *foo_array; << 390 << 391 void do_something_locked(struct foo *f << 392 { << 393 /* This works even if data_rac << 394 if (!data_race(global_flag)) { << 395 spin_lock(&fp->f_lock) << 396 if (!smp_load_acquire( << 397 do_something(f << 398 spin_unlock(&f << 399 return; << 400 } << 401 spin_unlock(&fp->f_loc << 402 } << 403 spin_lock(&global_lock); << 404 /* global_lock held, thus glob << 405 spin_lock(&fp->f_lock); << 406 spin_unlock(&global_lock); << 407 /* << 408 * global_flag might be set he << 409 * will wait for ->f_lock to b << 410 */ << 411 do_something(fp); << 412 spin_unlock(&fp->f_lock); << 413 } << 414 << 415 void begin_global(void) << 416 { << 417 int i; << 418 << 419 spin_lock(&global_lock); << 420 WRITE_ONCE(global_flag, true); << 421 for (i = 0; i < nfoo; i++) { << 422 /* << 423 * Wait for pre-existi << 424 * a time to avoid loc << 425 */ << 426 spin_lock(&fp->f_lock) << 427 spin_unlock(&fp->f_loc << 428 } << 429 } << 430 << 431 void end_global(void) << 432 { << 433 smp_store_release(&global_flag << 434 spin_unlock(&global_lock); << 435 } << 436 << 437 All code paths leading from the do_something_l << 438 read from global_flag acquire a lock, so endle << 439 happen. << 440 << 441 If the value read from global_flag is true, th << 442 rechecked while holding ->f_lock, which, if gl << 443 prevents begin_global() from completing. It i << 444 do_something(). << 445 << 446 Otherwise, if either value read from global_fl << 447 global_lock is acquired global_flag must be fa << 448 ->f_lock will prevent any call to begin_global << 449 means that it is safe to release global_lock a << 450 << 451 For this to work, only those foo structures in << 452 to do_something_locked(). The reason for this << 453 with begin_global() relies on momentarily hold << 454 every foo structure. << 455 << 456 The smp_load_acquire() and smp_store_release() << 457 changes to a foo structure between calls to be << 458 end_global() are carried out without holding t << 459 The smp_load_acquire() and smp_store_release() << 460 invocation of do_something() from do_something << 461 changes. << 462 320 463 321 464 Lockless Reads and Writes 322 Lockless Reads and Writes 465 ------------------------- 323 ------------------------- 466 324 467 For another example, suppose a shared variable 325 For another example, suppose a shared variable "foo" is both read and 468 updated locklessly. The code might look as fo 326 updated locklessly. The code might look as follows: 469 327 470 int foo; 328 int foo; 471 329 472 int update_foo(int newval) 330 int update_foo(int newval) 473 { 331 { 474 int ret; 332 int ret; 475 333 476 ret = xchg(&foo, newval); 334 ret = xchg(&foo, newval); 477 do_something(newval); 335 do_something(newval); 478 return ret; 336 return ret; 479 } 337 } 480 338 481 int read_foo(void) 339 int read_foo(void) 482 { 340 { 483 do_something_else(); 341 do_something_else(); 484 return READ_ONCE(foo); 342 return READ_ONCE(foo); 485 } 343 } 486 344 487 Because foo is accessed locklessly, all access 345 Because foo is accessed locklessly, all accesses are marked. It does 488 not make sense to use ASSERT_EXCLUSIVE_WRITER( 346 not make sense to use ASSERT_EXCLUSIVE_WRITER() in this case because 489 there really can be concurrent lockless writer 347 there really can be concurrent lockless writers. KCSAN would 490 flag any concurrent plain C-language reads fro 348 flag any concurrent plain C-language reads from foo, and given 491 CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n, als 349 CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n, also any concurrent plain 492 C-language writes to foo. 350 C-language writes to foo. 493 351 494 352 495 Lockless Reads and Writes, But With Single-Thr 353 Lockless Reads and Writes, But With Single-Threaded Initialization 496 ---------------------------------------------- 354 ------------------------------------------------------------------ 497 355 498 For yet another example, suppose that foo is i 356 For yet another example, suppose that foo is initialized in a 499 single-threaded manner, but that a number of k 357 single-threaded manner, but that a number of kthreads are then created 500 that locklessly and concurrently access foo. 358 that locklessly and concurrently access foo. Some snippets of this code 501 might look as follows: 359 might look as follows: 502 360 503 int foo; 361 int foo; 504 362 505 void initialize_foo(int initval, int n 363 void initialize_foo(int initval, int nkthreads) 506 { 364 { 507 int i; 365 int i; 508 366 509 foo = initval; 367 foo = initval; 510 ASSERT_EXCLUSIVE_ACCESS(foo); 368 ASSERT_EXCLUSIVE_ACCESS(foo); 511 for (i = 0; i < nkthreads; i++ 369 for (i = 0; i < nkthreads; i++) 512 kthread_run(access_foo 370 kthread_run(access_foo_concurrently, ...); 513 } 371 } 514 372 515 /* Called from access_foo_concurrently 373 /* Called from access_foo_concurrently(). */ 516 int update_foo(int newval) 374 int update_foo(int newval) 517 { 375 { 518 int ret; 376 int ret; 519 377 520 ret = xchg(&foo, newval); 378 ret = xchg(&foo, newval); 521 do_something(newval); 379 do_something(newval); 522 return ret; 380 return ret; 523 } 381 } 524 382 525 /* Also called from access_foo_concurr 383 /* Also called from access_foo_concurrently(). */ 526 int read_foo(void) 384 int read_foo(void) 527 { 385 { 528 do_something_else(); 386 do_something_else(); 529 return READ_ONCE(foo); 387 return READ_ONCE(foo); 530 } 388 } 531 389 532 The initialize_foo() uses a plain C-language w 390 The initialize_foo() uses a plain C-language write to foo because there 533 are not supposed to be concurrent accesses dur 391 are not supposed to be concurrent accesses during initialization. The 534 ASSERT_EXCLUSIVE_ACCESS() allows KCSAN to flag 392 ASSERT_EXCLUSIVE_ACCESS() allows KCSAN to flag buggy concurrent unmarked 535 reads, and the ASSERT_EXCLUSIVE_ACCESS() call 393 reads, and the ASSERT_EXCLUSIVE_ACCESS() call further allows KCSAN to 536 flag buggy concurrent writes, even if: (1) Th 394 flag buggy concurrent writes, even if: (1) Those writes are marked or 537 (2) The kernel was built with CONFIG_KCSAN_ASS 395 (2) The kernel was built with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=y. 538 396 539 397 540 Checking Stress-Test Race Coverage 398 Checking Stress-Test Race Coverage 541 ---------------------------------- 399 ---------------------------------- 542 400 543 When designing stress tests it is important to 401 When designing stress tests it is important to ensure that race conditions 544 of interest really do occur. For example, con 402 of interest really do occur. For example, consider the following code 545 fragment: 403 fragment: 546 404 547 int foo; 405 int foo; 548 406 549 int update_foo(int newval) 407 int update_foo(int newval) 550 { 408 { 551 return xchg(&foo, newval); 409 return xchg(&foo, newval); 552 } 410 } 553 411 554 int xor_shift_foo(int shift, int mask) 412 int xor_shift_foo(int shift, int mask) 555 { 413 { 556 int old, new, newold; 414 int old, new, newold; 557 415 558 newold = data_race(foo); /* Ch 416 newold = data_race(foo); /* Checked by cmpxchg(). */ 559 do { 417 do { 560 old = newold; 418 old = newold; 561 new = (old << shift) ^ 419 new = (old << shift) ^ mask; 562 newold = cmpxchg(&foo, 420 newold = cmpxchg(&foo, old, new); 563 } while (newold != old); 421 } while (newold != old); 564 return old; 422 return old; 565 } 423 } 566 424 567 int read_foo(void) 425 int read_foo(void) 568 { 426 { 569 return READ_ONCE(foo); 427 return READ_ONCE(foo); 570 } 428 } 571 429 572 If it is possible for update_foo(), xor_shift_ 430 If it is possible for update_foo(), xor_shift_foo(), and read_foo() to be 573 invoked concurrently, the stress test should f 431 invoked concurrently, the stress test should force this concurrency to 574 actually happen. KCSAN can evaluate the stres 432 actually happen. KCSAN can evaluate the stress test when the above code 575 is modified to read as follows: 433 is modified to read as follows: 576 434 577 int foo; 435 int foo; 578 436 579 int update_foo(int newval) 437 int update_foo(int newval) 580 { 438 { 581 ASSERT_EXCLUSIVE_ACCESS(foo); 439 ASSERT_EXCLUSIVE_ACCESS(foo); 582 return xchg(&foo, newval); 440 return xchg(&foo, newval); 583 } 441 } 584 442 585 int xor_shift_foo(int shift, int mask) 443 int xor_shift_foo(int shift, int mask) 586 { 444 { 587 int old, new, newold; 445 int old, new, newold; 588 446 589 newold = data_race(foo); /* Ch 447 newold = data_race(foo); /* Checked by cmpxchg(). */ 590 do { 448 do { 591 old = newold; 449 old = newold; 592 new = (old << shift) ^ 450 new = (old << shift) ^ mask; 593 ASSERT_EXCLUSIVE_ACCES 451 ASSERT_EXCLUSIVE_ACCESS(foo); 594 newold = cmpxchg(&foo, 452 newold = cmpxchg(&foo, old, new); 595 } while (newold != old); 453 } while (newold != old); 596 return old; 454 return old; 597 } 455 } 598 456 599 457 600 int read_foo(void) 458 int read_foo(void) 601 { 459 { 602 ASSERT_EXCLUSIVE_ACCESS(foo); 460 ASSERT_EXCLUSIVE_ACCESS(foo); 603 return READ_ONCE(foo); 461 return READ_ONCE(foo); 604 } 462 } 605 463 606 If a given stress-test run does not result in 464 If a given stress-test run does not result in KCSAN complaints from 607 each possible pair of ASSERT_EXCLUSIVE_ACCESS( 465 each possible pair of ASSERT_EXCLUSIVE_ACCESS() invocations, the 608 stress test needs improvement. If the stress 466 stress test needs improvement. If the stress test was to be evaluated 609 on a regular basis, it would be wise to place 467 on a regular basis, it would be wise to place the above instances of 610 ASSERT_EXCLUSIVE_ACCESS() under #ifdef so that 468 ASSERT_EXCLUSIVE_ACCESS() under #ifdef so that they did not result in 611 false positives when not evaluating the stress 469 false positives when not evaluating the stress test. 612 470 613 471 614 REFERENCES 472 REFERENCES 615 ========== 473 ========== 616 474 617 [1] "Concurrency bugs should fear the big bad 475 [1] "Concurrency bugs should fear the big bad data-race detector (part 2)" 618 https://lwn.net/Articles/816854/ 476 https://lwn.net/Articles/816854/ 619 477 620 [2] "The Kernel Concurrency Sanitizer" !! 478 [2] "Who's afraid of a big bad optimizing compiler?" 621 https://www.linuxfoundation.org/webinars/t << 622 << 623 [3] "Who's afraid of a big bad optimizing comp << 624 https://lwn.net/Articles/793253/ 479 https://lwn.net/Articles/793253/
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.