1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * KCSAN core runtime.
4 *
5 * Copyright (C) 2019, Google LLC.
6 */
7
8 #define pr_fmt(fmt) "kcsan: " fmt
9
10 #include <linux/atomic.h>
11 #include <linux/bug.h>
12 #include <linux/delay.h>
13 #include <linux/export.h>
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/list.h>
17 #include <linux/minmax.h>
18 #include <linux/moduleparam.h>
19 #include <linux/percpu.h>
20 #include <linux/preempt.h>
21 #include <linux/sched.h>
22 #include <linux/string.h>
23 #include <linux/uaccess.h>
24
25 #include "encoding.h"
26 #include "kcsan.h"
27 #include "permissive.h"
28
29 static bool kcsan_early_enable = IS_ENABLED(CONFIG_KCSAN_EARLY_ENABLE);
30 unsigned int kcsan_udelay_task = CONFIG_KCSAN_UDELAY_TASK;
31 unsigned int kcsan_udelay_interrupt = CONFIG_KCSAN_UDELAY_INTERRUPT;
32 static long kcsan_skip_watch = CONFIG_KCSAN_SKIP_WATCH;
33 static bool kcsan_interrupt_watcher = IS_ENABLED(CONFIG_KCSAN_INTERRUPT_WATCHER);
34
35 #ifdef MODULE_PARAM_PREFIX
36 #undef MODULE_PARAM_PREFIX
37 #endif
38 #define MODULE_PARAM_PREFIX "kcsan."
39 module_param_named(early_enable, kcsan_early_enable, bool, 0);
40 module_param_named(udelay_task, kcsan_udelay_task, uint, 0644);
41 module_param_named(udelay_interrupt, kcsan_udelay_interrupt, uint, 0644);
42 module_param_named(skip_watch, kcsan_skip_watch, long, 0644);
43 module_param_named(interrupt_watcher, kcsan_interrupt_watcher, bool, 0444);
44
45 #ifdef CONFIG_KCSAN_WEAK_MEMORY
46 static bool kcsan_weak_memory = true;
47 module_param_named(weak_memory, kcsan_weak_memory, bool, 0644);
48 #else
49 #define kcsan_weak_memory false
50 #endif
51
52 bool kcsan_enabled;
53
54 /* Per-CPU kcsan_ctx for interrupts */
55 static DEFINE_PER_CPU(struct kcsan_ctx, kcsan_cpu_ctx) = {
56 .scoped_accesses = {LIST_POISON1, NULL},
57 };
58
59 /*
60 * Helper macros to index into adjacent slots, starting from address slot
61 * itself, followed by the right and left slots.
62 *
63 * The purpose is 2-fold:
64 *
65 * 1. if during insertion the address slot is already occupied, check if
66 * any adjacent slots are free;
67 * 2. accesses that straddle a slot boundary due to size that exceeds a
68 * slot's range may check adjacent slots if any watchpoint matches.
69 *
70 * Note that accesses with very large size may still miss a watchpoint; however,
71 * given this should be rare, this is a reasonable trade-off to make, since this
72 * will avoid:
73 *
74 * 1. excessive contention between watchpoint checks and setup;
75 * 2. larger number of simultaneous watchpoints without sacrificing
76 * performance.
77 *
78 * Example: SLOT_IDX values for KCSAN_CHECK_ADJACENT=1, where i is [0, 1, 2]:
79 *
80 * slot=0: [ 1, 2, 0]
81 * slot=9: [10, 11, 9]
82 * slot=63: [64, 65, 63]
83 */
84 #define SLOT_IDX(slot, i) (slot + ((i + KCSAN_CHECK_ADJACENT) % NUM_SLOTS))
85
86 /*
87 * SLOT_IDX_FAST is used in the fast-path. Not first checking the address's primary
88 * slot (middle) is fine if we assume that races occur rarely. The set of
89 * indices {SLOT_IDX(slot, i) | i in [0, NUM_SLOTS)} is equivalent to
90 * {SLOT_IDX_FAST(slot, i) | i in [0, NUM_SLOTS)}.
91 */
92 #define SLOT_IDX_FAST(slot, i) (slot + i)
93
94 /*
95 * Watchpoints, with each entry encoded as defined in encoding.h: in order to be
96 * able to safely update and access a watchpoint without introducing locking
97 * overhead, we encode each watchpoint as a single atomic long. The initial
98 * zero-initialized state matches INVALID_WATCHPOINT.
99 *
100 * Add NUM_SLOTS-1 entries to account for overflow; this helps avoid having to
101 * use more complicated SLOT_IDX_FAST calculation with modulo in the fast-path.
102 */
103 static atomic_long_t watchpoints[CONFIG_KCSAN_NUM_WATCHPOINTS + NUM_SLOTS-1];
104
105 /*
106 * Instructions to skip watching counter, used in should_watch(). We use a
107 * per-CPU counter to avoid excessive contention.
108 */
109 static DEFINE_PER_CPU(long, kcsan_skip);
110
111 /* For kcsan_prandom_u32_max(). */
112 static DEFINE_PER_CPU(u32, kcsan_rand_state);
113
find_watchpoint(unsigned long addr,size_t size,bool expect_write,long * encoded_watchpoint)114 static __always_inline atomic_long_t *find_watchpoint(unsigned long addr,
115 size_t size,
116 bool expect_write,
117 long *encoded_watchpoint)
118 {
119 const int slot = watchpoint_slot(addr);
120 const unsigned long addr_masked = addr & WATCHPOINT_ADDR_MASK;
121 atomic_long_t *watchpoint;
122 unsigned long wp_addr_masked;
123 size_t wp_size;
124 bool is_write;
125 int i;
126
127 BUILD_BUG_ON(CONFIG_KCSAN_NUM_WATCHPOINTS < NUM_SLOTS);
128
129 for (i = 0; i < NUM_SLOTS; ++i) {
130 watchpoint = &watchpoints[SLOT_IDX_FAST(slot, i)];
131 *encoded_watchpoint = atomic_long_read(watchpoint);
132 if (!decode_watchpoint(*encoded_watchpoint, &wp_addr_masked,
133 &wp_size, &is_write))
134 continue;
135
136 if (expect_write && !is_write)
137 continue;
138
139 /* Check if the watchpoint matches the access. */
140 if (matching_access(wp_addr_masked, wp_size, addr_masked, size))
141 return watchpoint;
142 }
143
144 return NULL;
145 }
146
147 static inline atomic_long_t *
insert_watchpoint(unsigned long addr,size_t size,bool is_write)148 insert_watchpoint(unsigned long addr, size_t size, bool is_write)
149 {
150 const int slot = watchpoint_slot(addr);
151 const long encoded_watchpoint = encode_watchpoint(addr, size, is_write);
152 atomic_long_t *watchpoint;
153 int i;
154
155 /* Check slot index logic, ensuring we stay within array bounds. */
156 BUILD_BUG_ON(SLOT_IDX(0, 0) != KCSAN_CHECK_ADJACENT);
157 BUILD_BUG_ON(SLOT_IDX(0, KCSAN_CHECK_ADJACENT+1) != 0);
158 BUILD_BUG_ON(SLOT_IDX(CONFIG_KCSAN_NUM_WATCHPOINTS-1, KCSAN_CHECK_ADJACENT) != ARRAY_SIZE(watchpoints)-1);
159 BUILD_BUG_ON(SLOT_IDX(CONFIG_KCSAN_NUM_WATCHPOINTS-1, KCSAN_CHECK_ADJACENT+1) != ARRAY_SIZE(watchpoints) - NUM_SLOTS);
160
161 for (i = 0; i < NUM_SLOTS; ++i) {
162 long expect_val = INVALID_WATCHPOINT;
163
164 /* Try to acquire this slot. */
165 watchpoint = &watchpoints[SLOT_IDX(slot, i)];
166 if (atomic_long_try_cmpxchg_relaxed(watchpoint, &expect_val, encoded_watchpoint))
167 return watchpoint;
168 }
169
170 return NULL;
171 }
172
173 /*
174 * Return true if watchpoint was successfully consumed, false otherwise.
175 *
176 * This may return false if:
177 *
178 * 1. another thread already consumed the watchpoint;
179 * 2. the thread that set up the watchpoint already removed it;
180 * 3. the watchpoint was removed and then re-used.
181 */
182 static __always_inline bool
try_consume_watchpoint(atomic_long_t * watchpoint,long encoded_watchpoint)183 try_consume_watchpoint(atomic_long_t *watchpoint, long encoded_watchpoint)
184 {
185 return atomic_long_try_cmpxchg_relaxed(watchpoint, &encoded_watchpoint, CONSUMED_WATCHPOINT);
186 }
187
188 /* Return true if watchpoint was not touched, false if already consumed. */
consume_watchpoint(atomic_long_t * watchpoint)189 static inline bool consume_watchpoint(atomic_long_t *watchpoint)
190 {
191 return atomic_long_xchg_relaxed(watchpoint, CONSUMED_WATCHPOINT) != CONSUMED_WATCHPOINT;
192 }
193
194 /* Remove the watchpoint -- its slot may be reused after. */
remove_watchpoint(atomic_long_t * watchpoint)195 static inline void remove_watchpoint(atomic_long_t *watchpoint)
196 {
197 atomic_long_set(watchpoint, INVALID_WATCHPOINT);
198 }
199
get_ctx(void)200 static __always_inline struct kcsan_ctx *get_ctx(void)
201 {
202 /*
203 * In interrupts, use raw_cpu_ptr to avoid unnecessary checks, that would
204 * also result in calls that generate warnings in uaccess regions.
205 */
206 return in_task() ? ¤t->kcsan_ctx : raw_cpu_ptr(&kcsan_cpu_ctx);
207 }
208
209 static __always_inline void
210 check_access(const volatile void *ptr, size_t size, int type, unsigned long ip);
211
212 /* Check scoped accesses; never inline because this is a slow-path! */
kcsan_check_scoped_accesses(void)213 static noinline void kcsan_check_scoped_accesses(void)
214 {
215 struct kcsan_ctx *ctx = get_ctx();
216 struct kcsan_scoped_access *scoped_access;
217
218 if (ctx->disable_scoped)
219 return;
220
221 ctx->disable_scoped++;
222 list_for_each_entry(scoped_access, &ctx->scoped_accesses, list) {
223 check_access(scoped_access->ptr, scoped_access->size,
224 scoped_access->type, scoped_access->ip);
225 }
226 ctx->disable_scoped--;
227 }
228
229 /* Rules for generic atomic accesses. Called from fast-path. */
230 static __always_inline bool
is_atomic(struct kcsan_ctx * ctx,const volatile void * ptr,size_t size,int type)231 is_atomic(struct kcsan_ctx *ctx, const volatile void *ptr, size_t size, int type)
232 {
233 if (type & KCSAN_ACCESS_ATOMIC)
234 return true;
235
236 /*
237 * Unless explicitly declared atomic, never consider an assertion access
238 * as atomic. This allows using them also in atomic regions, such as
239 * seqlocks, without implicitly changing their semantics.
240 */
241 if (type & KCSAN_ACCESS_ASSERT)
242 return false;
243
244 if (IS_ENABLED(CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC) &&
245 (type & KCSAN_ACCESS_WRITE) && size <= sizeof(long) &&
246 !(type & KCSAN_ACCESS_COMPOUND) && IS_ALIGNED((unsigned long)ptr, size))
247 return true; /* Assume aligned writes up to word size are atomic. */
248
249 if (ctx->atomic_next > 0) {
250 /*
251 * Because we do not have separate contexts for nested
252 * interrupts, in case atomic_next is set, we simply assume that
253 * the outer interrupt set atomic_next. In the worst case, we
254 * will conservatively consider operations as atomic. This is a
255 * reasonable trade-off to make, since this case should be
256 * extremely rare; however, even if extremely rare, it could
257 * lead to false positives otherwise.
258 */
259 if ((hardirq_count() >> HARDIRQ_SHIFT) < 2)
260 --ctx->atomic_next; /* in task, or outer interrupt */
261 return true;
262 }
263
264 return ctx->atomic_nest_count > 0 || ctx->in_flat_atomic;
265 }
266
267 static __always_inline bool
should_watch(struct kcsan_ctx * ctx,const volatile void * ptr,size_t size,int type)268 should_watch(struct kcsan_ctx *ctx, const volatile void *ptr, size_t size, int type)
269 {
270 /*
271 * Never set up watchpoints when memory operations are atomic.
272 *
273 * Need to check this first, before kcsan_skip check below: (1) atomics
274 * should not count towards skipped instructions, and (2) to actually
275 * decrement kcsan_atomic_next for consecutive instruction stream.
276 */
277 if (is_atomic(ctx, ptr, size, type))
278 return false;
279
280 if (this_cpu_dec_return(kcsan_skip) >= 0)
281 return false;
282
283 /*
284 * NOTE: If we get here, kcsan_skip must always be reset in slow path
285 * via reset_kcsan_skip() to avoid underflow.
286 */
287
288 /* this operation should be watched */
289 return true;
290 }
291
292 /*
293 * Returns a pseudo-random number in interval [0, ep_ro). Simple linear
294 * congruential generator, using constants from "Numerical Recipes".
295 */
kcsan_prandom_u32_max(u32 ep_ro)296 static u32 kcsan_prandom_u32_max(u32 ep_ro)
297 {
298 u32 state = this_cpu_read(kcsan_rand_state);
299
300 state = 1664525 * state + 1013904223;
301 this_cpu_write(kcsan_rand_state, state);
302
303 return state % ep_ro;
304 }
305
reset_kcsan_skip(void)306 static inline void reset_kcsan_skip(void)
307 {
308 long skip_count = kcsan_skip_watch -
309 (IS_ENABLED(CONFIG_KCSAN_SKIP_WATCH_RANDOMIZE) ?
310 kcsan_prandom_u32_max(kcsan_skip_watch) :
311 0);
312 this_cpu_write(kcsan_skip, skip_count);
313 }
314
kcsan_is_enabled(struct kcsan_ctx * ctx)315 static __always_inline bool kcsan_is_enabled(struct kcsan_ctx *ctx)
316 {
317 return READ_ONCE(kcsan_enabled) && !ctx->disable_count;
318 }
319
320 /* Introduce delay depending on context and configuration. */
delay_access(int type)321 static void delay_access(int type)
322 {
323 unsigned int delay = in_task() ? kcsan_udelay_task : kcsan_udelay_interrupt;
324 /* For certain access types, skew the random delay to be longer. */
325 unsigned int skew_delay_order =
326 (type & (KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_ASSERT)) ? 1 : 0;
327
328 delay -= IS_ENABLED(CONFIG_KCSAN_DELAY_RANDOMIZE) ?
329 kcsan_prandom_u32_max(delay >> skew_delay_order) :
330 0;
331 udelay(delay);
332 }
333
334 /*
335 * Reads the instrumented memory for value change detection; value change
336 * detection is currently done for accesses up to a size of 8 bytes.
337 */
read_instrumented_memory(const volatile void * ptr,size_t size)338 static __always_inline u64 read_instrumented_memory(const volatile void *ptr, size_t size)
339 {
340 /*
341 * In the below we don't necessarily need the read of the location to
342 * be atomic, and we don't use READ_ONCE(), since all we need for race
343 * detection is to observe 2 different values.
344 *
345 * Furthermore, on certain architectures (such as arm64), READ_ONCE()
346 * may turn into more complex instructions than a plain load that cannot
347 * do unaligned accesses.
348 */
349 switch (size) {
350 case 1: return *(const volatile u8 *)ptr;
351 case 2: return *(const volatile u16 *)ptr;
352 case 4: return *(const volatile u32 *)ptr;
353 case 8: return *(const volatile u64 *)ptr;
354 default: return 0; /* Ignore; we do not diff the values. */
355 }
356 }
357
kcsan_save_irqtrace(struct task_struct * task)358 void kcsan_save_irqtrace(struct task_struct *task)
359 {
360 #ifdef CONFIG_TRACE_IRQFLAGS
361 task->kcsan_save_irqtrace = task->irqtrace;
362 #endif
363 }
364
kcsan_restore_irqtrace(struct task_struct * task)365 void kcsan_restore_irqtrace(struct task_struct *task)
366 {
367 #ifdef CONFIG_TRACE_IRQFLAGS
368 task->irqtrace = task->kcsan_save_irqtrace;
369 #endif
370 }
371
get_kcsan_stack_depth(void)372 static __always_inline int get_kcsan_stack_depth(void)
373 {
374 #ifdef CONFIG_KCSAN_WEAK_MEMORY
375 return current->kcsan_stack_depth;
376 #else
377 BUILD_BUG();
378 return 0;
379 #endif
380 }
381
add_kcsan_stack_depth(int val)382 static __always_inline void add_kcsan_stack_depth(int val)
383 {
384 #ifdef CONFIG_KCSAN_WEAK_MEMORY
385 current->kcsan_stack_depth += val;
386 #else
387 BUILD_BUG();
388 #endif
389 }
390
get_reorder_access(struct kcsan_ctx * ctx)391 static __always_inline struct kcsan_scoped_access *get_reorder_access(struct kcsan_ctx *ctx)
392 {
393 #ifdef CONFIG_KCSAN_WEAK_MEMORY
394 return ctx->disable_scoped ? NULL : &ctx->reorder_access;
395 #else
396 return NULL;
397 #endif
398 }
399
400 static __always_inline bool
find_reorder_access(struct kcsan_ctx * ctx,const volatile void * ptr,size_t size,int type,unsigned long ip)401 find_reorder_access(struct kcsan_ctx *ctx, const volatile void *ptr, size_t size,
402 int type, unsigned long ip)
403 {
404 struct kcsan_scoped_access *reorder_access = get_reorder_access(ctx);
405
406 if (!reorder_access)
407 return false;
408
409 /*
410 * Note: If accesses are repeated while reorder_access is identical,
411 * never matches the new access, because !(type & KCSAN_ACCESS_SCOPED).
412 */
413 return reorder_access->ptr == ptr && reorder_access->size == size &&
414 reorder_access->type == type && reorder_access->ip == ip;
415 }
416
417 static inline void
set_reorder_access(struct kcsan_ctx * ctx,const volatile void * ptr,size_t size,int type,unsigned long ip)418 set_reorder_access(struct kcsan_ctx *ctx, const volatile void *ptr, size_t size,
419 int type, unsigned long ip)
420 {
421 struct kcsan_scoped_access *reorder_access = get_reorder_access(ctx);
422
423 if (!reorder_access || !kcsan_weak_memory)
424 return;
425
426 /*
427 * To avoid nested interrupts or scheduler (which share kcsan_ctx)
428 * reading an inconsistent reorder_access, ensure that the below has
429 * exclusive access to reorder_access by disallowing concurrent use.
430 */
431 ctx->disable_scoped++;
432 barrier();
433 reorder_access->ptr = ptr;
434 reorder_access->size = size;
435 reorder_access->type = type | KCSAN_ACCESS_SCOPED;
436 reorder_access->ip = ip;
437 reorder_access->stack_depth = get_kcsan_stack_depth();
438 barrier();
439 ctx->disable_scoped--;
440 }
441
442 /*
443 * Pull everything together: check_access() below contains the performance
444 * critical operations; the fast-path (including check_access) functions should
445 * all be inlinable by the instrumentation functions.
446 *
447 * The slow-path (kcsan_found_watchpoint, kcsan_setup_watchpoint) are
448 * non-inlinable -- note that, we prefix these with "kcsan_" to ensure they can
449 * be filtered from the stacktrace, as well as give them unique names for the
450 * UACCESS whitelist of objtool. Each function uses user_access_save/restore(),
451 * since they do not access any user memory, but instrumentation is still
452 * emitted in UACCESS regions.
453 */
454
kcsan_found_watchpoint(const volatile void * ptr,size_t size,int type,unsigned long ip,atomic_long_t * watchpoint,long encoded_watchpoint)455 static noinline void kcsan_found_watchpoint(const volatile void *ptr,
456 size_t size,
457 int type,
458 unsigned long ip,
459 atomic_long_t *watchpoint,
460 long encoded_watchpoint)
461 {
462 const bool is_assert = (type & KCSAN_ACCESS_ASSERT) != 0;
463 struct kcsan_ctx *ctx = get_ctx();
464 unsigned long flags;
465 bool consumed;
466
467 /*
468 * We know a watchpoint exists. Let's try to keep the race-window
469 * between here and finally consuming the watchpoint below as small as
470 * possible -- avoid unneccessarily complex code until consumed.
471 */
472
473 if (!kcsan_is_enabled(ctx))
474 return;
475
476 /*
477 * The access_mask check relies on value-change comparison. To avoid
478 * reporting a race where e.g. the writer set up the watchpoint, but the
479 * reader has access_mask!=0, we have to ignore the found watchpoint.
480 *
481 * reorder_access is never created from an access with access_mask set.
482 */
483 if (ctx->access_mask && !find_reorder_access(ctx, ptr, size, type, ip))
484 return;
485
486 /*
487 * If the other thread does not want to ignore the access, and there was
488 * a value change as a result of this thread's operation, we will still
489 * generate a report of unknown origin.
490 *
491 * Use CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN=n to filter.
492 */
493 if (!is_assert && kcsan_ignore_address(ptr))
494 return;
495
496 /*
497 * Consuming the watchpoint must be guarded by kcsan_is_enabled() to
498 * avoid erroneously triggering reports if the context is disabled.
499 */
500 consumed = try_consume_watchpoint(watchpoint, encoded_watchpoint);
501
502 /* keep this after try_consume_watchpoint */
503 flags = user_access_save();
504
505 if (consumed) {
506 kcsan_save_irqtrace(current);
507 kcsan_report_set_info(ptr, size, type, ip, watchpoint - watchpoints);
508 kcsan_restore_irqtrace(current);
509 } else {
510 /*
511 * The other thread may not print any diagnostics, as it has
512 * already removed the watchpoint, or another thread consumed
513 * the watchpoint before this thread.
514 */
515 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_REPORT_RACES]);
516 }
517
518 if (is_assert)
519 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_ASSERT_FAILURES]);
520 else
521 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_DATA_RACES]);
522
523 user_access_restore(flags);
524 }
525
526 static noinline void
kcsan_setup_watchpoint(const volatile void * ptr,size_t size,int type,unsigned long ip)527 kcsan_setup_watchpoint(const volatile void *ptr, size_t size, int type, unsigned long ip)
528 {
529 const bool is_write = (type & KCSAN_ACCESS_WRITE) != 0;
530 const bool is_assert = (type & KCSAN_ACCESS_ASSERT) != 0;
531 atomic_long_t *watchpoint;
532 u64 old, new, diff;
533 enum kcsan_value_change value_change = KCSAN_VALUE_CHANGE_MAYBE;
534 bool interrupt_watcher = kcsan_interrupt_watcher;
535 unsigned long ua_flags = user_access_save();
536 struct kcsan_ctx *ctx = get_ctx();
537 unsigned long access_mask = ctx->access_mask;
538 unsigned long irq_flags = 0;
539 bool is_reorder_access;
540
541 /*
542 * Always reset kcsan_skip counter in slow-path to avoid underflow; see
543 * should_watch().
544 */
545 reset_kcsan_skip();
546
547 if (!kcsan_is_enabled(ctx))
548 goto out;
549
550 /*
551 * Check to-ignore addresses after kcsan_is_enabled(), as we may access
552 * memory that is not yet initialized during early boot.
553 */
554 if (!is_assert && kcsan_ignore_address(ptr))
555 goto out;
556
557 if (!check_encodable((unsigned long)ptr, size)) {
558 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_UNENCODABLE_ACCESSES]);
559 goto out;
560 }
561
562 /*
563 * The local CPU cannot observe reordering of its own accesses, and
564 * therefore we need to take care of 2 cases to avoid false positives:
565 *
566 * 1. Races of the reordered access with interrupts. To avoid, if
567 * the current access is reorder_access, disable interrupts.
568 * 2. Avoid races of scoped accesses from nested interrupts (below).
569 */
570 is_reorder_access = find_reorder_access(ctx, ptr, size, type, ip);
571 if (is_reorder_access)
572 interrupt_watcher = false;
573 /*
574 * Avoid races of scoped accesses from nested interrupts (or scheduler).
575 * Assume setting up a watchpoint for a non-scoped (normal) access that
576 * also conflicts with a current scoped access. In a nested interrupt,
577 * which shares the context, it would check a conflicting scoped access.
578 * To avoid, disable scoped access checking.
579 */
580 ctx->disable_scoped++;
581
582 /*
583 * Save and restore the IRQ state trace touched by KCSAN, since KCSAN's
584 * runtime is entered for every memory access, and potentially useful
585 * information is lost if dirtied by KCSAN.
586 */
587 kcsan_save_irqtrace(current);
588 if (!interrupt_watcher) {
589 local_irq_save(irq_flags);
590 /*
591 * NMIs can still fire, disable checking for all interrupt
592 * contexts.
593 */
594 raw_cpu_ptr(&kcsan_cpu_ctx)->disable_count++;
595 }
596
597 watchpoint = insert_watchpoint((unsigned long)ptr, size, is_write);
598 if (watchpoint == NULL) {
599 /*
600 * Out of capacity: the size of 'watchpoints', and the frequency
601 * with which should_watch() returns true should be tweaked so
602 * that this case happens very rarely.
603 */
604 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_NO_CAPACITY]);
605 goto out_unlock;
606 }
607
608 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_SETUP_WATCHPOINTS]);
609 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_USED_WATCHPOINTS]);
610
611 /*
612 * Read the current value, to later check and infer a race if the data
613 * was modified via a non-instrumented access, e.g. from a device.
614 */
615 old = is_reorder_access ? 0 : read_instrumented_memory(ptr, size);
616
617 /*
618 * Delay this thread, to increase probability of observing a racy
619 * conflicting access.
620 */
621 delay_access(type);
622
623 /*
624 * Re-read value, and check if it is as expected; if not, we infer a
625 * racy access.
626 */
627 if (!is_reorder_access) {
628 new = read_instrumented_memory(ptr, size);
629 } else {
630 /*
631 * Reordered accesses cannot be used for value change detection,
632 * because the memory location may no longer be accessible and
633 * could result in a fault.
634 */
635 new = 0;
636 access_mask = 0;
637 }
638
639 diff = old ^ new;
640 if (access_mask)
641 diff &= access_mask;
642
643 /*
644 * Check if we observed a value change.
645 *
646 * Also check if the data race should be ignored (the rules depend on
647 * non-zero diff); if it is to be ignored, the below rules for
648 * KCSAN_VALUE_CHANGE_MAYBE apply.
649 */
650 if (diff && !kcsan_ignore_data_race(size, type, old, new, diff))
651 value_change = KCSAN_VALUE_CHANGE_TRUE;
652
653 /* Check if this access raced with another. */
654 if (!consume_watchpoint(watchpoint)) {
655 /*
656 * Depending on the access type, map a value_change of MAYBE to
657 * TRUE (always report) or FALSE (never report).
658 */
659 if (value_change == KCSAN_VALUE_CHANGE_MAYBE) {
660 if (access_mask != 0) {
661 /*
662 * For access with access_mask, we require a
663 * value-change, as it is likely that races on
664 * ~access_mask bits are expected.
665 */
666 value_change = KCSAN_VALUE_CHANGE_FALSE;
667 } else if (size > 8 || is_assert) {
668 /* Always assume a value-change. */
669 value_change = KCSAN_VALUE_CHANGE_TRUE;
670 }
671 }
672
673 /*
674 * No need to increment 'data_races' counter, as the racing
675 * thread already did.
676 *
677 * Count 'assert_failures' for each failed ASSERT access,
678 * therefore both this thread and the racing thread may
679 * increment this counter.
680 */
681 if (is_assert && value_change == KCSAN_VALUE_CHANGE_TRUE)
682 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_ASSERT_FAILURES]);
683
684 kcsan_report_known_origin(ptr, size, type, ip,
685 value_change, watchpoint - watchpoints,
686 old, new, access_mask);
687 } else if (value_change == KCSAN_VALUE_CHANGE_TRUE) {
688 /* Inferring a race, since the value should not have changed. */
689
690 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_RACES_UNKNOWN_ORIGIN]);
691 if (is_assert)
692 atomic_long_inc(&kcsan_counters[KCSAN_COUNTER_ASSERT_FAILURES]);
693
694 if (IS_ENABLED(CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN) || is_assert) {
695 kcsan_report_unknown_origin(ptr, size, type, ip,
696 old, new, access_mask);
697 }
698 }
699
700 /*
701 * Remove watchpoint; must be after reporting, since the slot may be
702 * reused after this point.
703 */
704 remove_watchpoint(watchpoint);
705 atomic_long_dec(&kcsan_counters[KCSAN_COUNTER_USED_WATCHPOINTS]);
706
707 out_unlock:
708 if (!interrupt_watcher) {
709 raw_cpu_ptr(&kcsan_cpu_ctx)->disable_count--;
710 local_irq_restore(irq_flags);
711 }
712 kcsan_restore_irqtrace(current);
713 ctx->disable_scoped--;
714
715 /*
716 * Reordered accesses cannot be used for value change detection,
717 * therefore never consider for reordering if access_mask is set.
718 * ASSERT_EXCLUSIVE are not real accesses, ignore them as well.
719 */
720 if (!access_mask && !is_assert)
721 set_reorder_access(ctx, ptr, size, type, ip);
722 out:
723 user_access_restore(ua_flags);
724 }
725
726 static __always_inline void
check_access(const volatile void * ptr,size_t size,int type,unsigned long ip)727 check_access(const volatile void *ptr, size_t size, int type, unsigned long ip)
728 {
729 atomic_long_t *watchpoint;
730 long encoded_watchpoint;
731
732 /*
733 * Do nothing for 0 sized check; this comparison will be optimized out
734 * for constant sized instrumentation (__tsan_{read,write}N).
735 */
736 if (unlikely(size == 0))
737 return;
738
739 again:
740 /*
741 * Avoid user_access_save in fast-path: find_watchpoint is safe without
742 * user_access_save, as the address that ptr points to is only used to
743 * check if a watchpoint exists; ptr is never dereferenced.
744 */
745 watchpoint = find_watchpoint((unsigned long)ptr, size,
746 !(type & KCSAN_ACCESS_WRITE),
747 &encoded_watchpoint);
748 /*
749 * It is safe to check kcsan_is_enabled() after find_watchpoint in the
750 * slow-path, as long as no state changes that cause a race to be
751 * detected and reported have occurred until kcsan_is_enabled() is
752 * checked.
753 */
754
755 if (unlikely(watchpoint != NULL))
756 kcsan_found_watchpoint(ptr, size, type, ip, watchpoint, encoded_watchpoint);
757 else {
758 struct kcsan_ctx *ctx = get_ctx(); /* Call only once in fast-path. */
759
760 if (unlikely(should_watch(ctx, ptr, size, type))) {
761 kcsan_setup_watchpoint(ptr, size, type, ip);
762 return;
763 }
764
765 if (!(type & KCSAN_ACCESS_SCOPED)) {
766 struct kcsan_scoped_access *reorder_access = get_reorder_access(ctx);
767
768 if (reorder_access) {
769 /*
770 * reorder_access check: simulates reordering of
771 * the access after subsequent operations.
772 */
773 ptr = reorder_access->ptr;
774 type = reorder_access->type;
775 ip = reorder_access->ip;
776 /*
777 * Upon a nested interrupt, this context's
778 * reorder_access can be modified (shared ctx).
779 * We know that upon return, reorder_access is
780 * always invalidated by setting size to 0 via
781 * __tsan_func_exit(). Therefore we must read
782 * and check size after the other fields.
783 */
784 barrier();
785 size = READ_ONCE(reorder_access->size);
786 if (size)
787 goto again;
788 }
789 }
790
791 /*
792 * Always checked last, right before returning from runtime;
793 * if reorder_access is valid, checked after it was checked.
794 */
795 if (unlikely(ctx->scoped_accesses.prev))
796 kcsan_check_scoped_accesses();
797 }
798 }
799
800 /* === Public interface ===================================================== */
801
kcsan_init(void)802 void __init kcsan_init(void)
803 {
804 int cpu;
805
806 BUG_ON(!in_task());
807
808 for_each_possible_cpu(cpu)
809 per_cpu(kcsan_rand_state, cpu) = (u32)get_cycles();
810
811 /*
812 * We are in the init task, and no other tasks should be running;
813 * WRITE_ONCE without memory barrier is sufficient.
814 */
815 if (kcsan_early_enable) {
816 pr_info("enabled early\n");
817 WRITE_ONCE(kcsan_enabled, true);
818 }
819
820 if (IS_ENABLED(CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY) ||
821 IS_ENABLED(CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC) ||
822 IS_ENABLED(CONFIG_KCSAN_PERMISSIVE) ||
823 IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) {
824 pr_warn("non-strict mode configured - use CONFIG_KCSAN_STRICT=y to see all data races\n");
825 } else {
826 pr_info("strict mode configured\n");
827 }
828 }
829
830 /* === Exported interface =================================================== */
831
kcsan_disable_current(void)832 void kcsan_disable_current(void)
833 {
834 ++get_ctx()->disable_count;
835 }
836 EXPORT_SYMBOL(kcsan_disable_current);
837
kcsan_enable_current(void)838 void kcsan_enable_current(void)
839 {
840 if (get_ctx()->disable_count-- == 0) {
841 /*
842 * Warn if kcsan_enable_current() calls are unbalanced with
843 * kcsan_disable_current() calls, which causes disable_count to
844 * become negative and should not happen.
845 */
846 kcsan_disable_current(); /* restore to 0, KCSAN still enabled */
847 kcsan_disable_current(); /* disable to generate warning */
848 WARN(1, "Unbalanced %s()", __func__);
849 kcsan_enable_current();
850 }
851 }
852 EXPORT_SYMBOL(kcsan_enable_current);
853
kcsan_enable_current_nowarn(void)854 void kcsan_enable_current_nowarn(void)
855 {
856 if (get_ctx()->disable_count-- == 0)
857 kcsan_disable_current();
858 }
859 EXPORT_SYMBOL(kcsan_enable_current_nowarn);
860
kcsan_nestable_atomic_begin(void)861 void kcsan_nestable_atomic_begin(void)
862 {
863 /*
864 * Do *not* check and warn if we are in a flat atomic region: nestable
865 * and flat atomic regions are independent from each other.
866 * See include/linux/kcsan.h: struct kcsan_ctx comments for more
867 * comments.
868 */
869
870 ++get_ctx()->atomic_nest_count;
871 }
872 EXPORT_SYMBOL(kcsan_nestable_atomic_begin);
873
kcsan_nestable_atomic_end(void)874 void kcsan_nestable_atomic_end(void)
875 {
876 if (get_ctx()->atomic_nest_count-- == 0) {
877 /*
878 * Warn if kcsan_nestable_atomic_end() calls are unbalanced with
879 * kcsan_nestable_atomic_begin() calls, which causes
880 * atomic_nest_count to become negative and should not happen.
881 */
882 kcsan_nestable_atomic_begin(); /* restore to 0 */
883 kcsan_disable_current(); /* disable to generate warning */
884 WARN(1, "Unbalanced %s()", __func__);
885 kcsan_enable_current();
886 }
887 }
888 EXPORT_SYMBOL(kcsan_nestable_atomic_end);
889
kcsan_flat_atomic_begin(void)890 void kcsan_flat_atomic_begin(void)
891 {
892 get_ctx()->in_flat_atomic = true;
893 }
894 EXPORT_SYMBOL(kcsan_flat_atomic_begin);
895
kcsan_flat_atomic_end(void)896 void kcsan_flat_atomic_end(void)
897 {
898 get_ctx()->in_flat_atomic = false;
899 }
900 EXPORT_SYMBOL(kcsan_flat_atomic_end);
901
kcsan_atomic_next(int n)902 void kcsan_atomic_next(int n)
903 {
904 get_ctx()->atomic_next = n;
905 }
906 EXPORT_SYMBOL(kcsan_atomic_next);
907
kcsan_set_access_mask(unsigned long mask)908 void kcsan_set_access_mask(unsigned long mask)
909 {
910 get_ctx()->access_mask = mask;
911 }
912 EXPORT_SYMBOL(kcsan_set_access_mask);
913
914 struct kcsan_scoped_access *
kcsan_begin_scoped_access(const volatile void * ptr,size_t size,int type,struct kcsan_scoped_access * sa)915 kcsan_begin_scoped_access(const volatile void *ptr, size_t size, int type,
916 struct kcsan_scoped_access *sa)
917 {
918 struct kcsan_ctx *ctx = get_ctx();
919
920 check_access(ptr, size, type, _RET_IP_);
921
922 ctx->disable_count++; /* Disable KCSAN, in case list debugging is on. */
923
924 INIT_LIST_HEAD(&sa->list);
925 sa->ptr = ptr;
926 sa->size = size;
927 sa->type = type;
928 sa->ip = _RET_IP_;
929
930 if (!ctx->scoped_accesses.prev) /* Lazy initialize list head. */
931 INIT_LIST_HEAD(&ctx->scoped_accesses);
932 list_add(&sa->list, &ctx->scoped_accesses);
933
934 ctx->disable_count--;
935 return sa;
936 }
937 EXPORT_SYMBOL(kcsan_begin_scoped_access);
938
kcsan_end_scoped_access(struct kcsan_scoped_access * sa)939 void kcsan_end_scoped_access(struct kcsan_scoped_access *sa)
940 {
941 struct kcsan_ctx *ctx = get_ctx();
942
943 if (WARN(!ctx->scoped_accesses.prev, "Unbalanced %s()?", __func__))
944 return;
945
946 ctx->disable_count++; /* Disable KCSAN, in case list debugging is on. */
947
948 list_del(&sa->list);
949 if (list_empty(&ctx->scoped_accesses))
950 /*
951 * Ensure we do not enter kcsan_check_scoped_accesses()
952 * slow-path if unnecessary, and avoids requiring list_empty()
953 * in the fast-path (to avoid a READ_ONCE() and potential
954 * uaccess warning).
955 */
956 ctx->scoped_accesses.prev = NULL;
957
958 ctx->disable_count--;
959
960 check_access(sa->ptr, sa->size, sa->type, sa->ip);
961 }
962 EXPORT_SYMBOL(kcsan_end_scoped_access);
963
__kcsan_check_access(const volatile void * ptr,size_t size,int type)964 void __kcsan_check_access(const volatile void *ptr, size_t size, int type)
965 {
966 check_access(ptr, size, type, _RET_IP_);
967 }
968 EXPORT_SYMBOL(__kcsan_check_access);
969
970 #define DEFINE_MEMORY_BARRIER(name, order_before_cond) \
971 void __kcsan_##name(void) \
972 { \
973 struct kcsan_scoped_access *sa = get_reorder_access(get_ctx()); \
974 if (!sa) \
975 return; \
976 if (order_before_cond) \
977 sa->size = 0; \
978 } \
979 EXPORT_SYMBOL(__kcsan_##name)
980
981 DEFINE_MEMORY_BARRIER(mb, true);
982 DEFINE_MEMORY_BARRIER(wmb, sa->type & (KCSAN_ACCESS_WRITE | KCSAN_ACCESS_COMPOUND));
983 DEFINE_MEMORY_BARRIER(rmb, !(sa->type & KCSAN_ACCESS_WRITE) || (sa->type & KCSAN_ACCESS_COMPOUND));
984 DEFINE_MEMORY_BARRIER(release, true);
985
986 /*
987 * KCSAN uses the same instrumentation that is emitted by supported compilers
988 * for ThreadSanitizer (TSAN).
989 *
990 * When enabled, the compiler emits instrumentation calls (the functions
991 * prefixed with "__tsan" below) for all loads and stores that it generated;
992 * inline asm is not instrumented.
993 *
994 * Note that, not all supported compiler versions distinguish aligned/unaligned
995 * accesses, but e.g. recent versions of Clang do. We simply alias the unaligned
996 * version to the generic version, which can handle both.
997 */
998
999 #define DEFINE_TSAN_READ_WRITE(size) \
1000 void __tsan_read##size(void *ptr); \
1001 void __tsan_read##size(void *ptr) \
1002 { \
1003 check_access(ptr, size, 0, _RET_IP_); \
1004 } \
1005 EXPORT_SYMBOL(__tsan_read##size); \
1006 void __tsan_unaligned_read##size(void *ptr) \
1007 __alias(__tsan_read##size); \
1008 EXPORT_SYMBOL(__tsan_unaligned_read##size); \
1009 void __tsan_write##size(void *ptr); \
1010 void __tsan_write##size(void *ptr) \
1011 { \
1012 check_access(ptr, size, KCSAN_ACCESS_WRITE, _RET_IP_); \
1013 } \
1014 EXPORT_SYMBOL(__tsan_write##size); \
1015 void __tsan_unaligned_write##size(void *ptr) \
1016 __alias(__tsan_write##size); \
1017 EXPORT_SYMBOL(__tsan_unaligned_write##size); \
1018 void __tsan_read_write##size(void *ptr); \
1019 void __tsan_read_write##size(void *ptr) \
1020 { \
1021 check_access(ptr, size, \
1022 KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE, \
1023 _RET_IP_); \
1024 } \
1025 EXPORT_SYMBOL(__tsan_read_write##size); \
1026 void __tsan_unaligned_read_write##size(void *ptr) \
1027 __alias(__tsan_read_write##size); \
1028 EXPORT_SYMBOL(__tsan_unaligned_read_write##size)
1029
1030 DEFINE_TSAN_READ_WRITE(1);
1031 DEFINE_TSAN_READ_WRITE(2);
1032 DEFINE_TSAN_READ_WRITE(4);
1033 DEFINE_TSAN_READ_WRITE(8);
1034 DEFINE_TSAN_READ_WRITE(16);
1035
1036 void __tsan_read_range(void *ptr, size_t size);
__tsan_read_range(void * ptr,size_t size)1037 void __tsan_read_range(void *ptr, size_t size)
1038 {
1039 check_access(ptr, size, 0, _RET_IP_);
1040 }
1041 EXPORT_SYMBOL(__tsan_read_range);
1042
1043 void __tsan_write_range(void *ptr, size_t size);
__tsan_write_range(void * ptr,size_t size)1044 void __tsan_write_range(void *ptr, size_t size)
1045 {
1046 check_access(ptr, size, KCSAN_ACCESS_WRITE, _RET_IP_);
1047 }
1048 EXPORT_SYMBOL(__tsan_write_range);
1049
1050 /*
1051 * Use of explicit volatile is generally disallowed [1], however, volatile is
1052 * still used in various concurrent context, whether in low-level
1053 * synchronization primitives or for legacy reasons.
1054 * [1] https://lwn.net/Articles/233479/
1055 *
1056 * We only consider volatile accesses atomic if they are aligned and would pass
1057 * the size-check of compiletime_assert_rwonce_type().
1058 */
1059 #define DEFINE_TSAN_VOLATILE_READ_WRITE(size) \
1060 void __tsan_volatile_read##size(void *ptr); \
1061 void __tsan_volatile_read##size(void *ptr) \
1062 { \
1063 const bool is_atomic = size <= sizeof(long long) && \
1064 IS_ALIGNED((unsigned long)ptr, size); \
1065 if (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS) && is_atomic) \
1066 return; \
1067 check_access(ptr, size, is_atomic ? KCSAN_ACCESS_ATOMIC : 0, \
1068 _RET_IP_); \
1069 } \
1070 EXPORT_SYMBOL(__tsan_volatile_read##size); \
1071 void __tsan_unaligned_volatile_read##size(void *ptr) \
1072 __alias(__tsan_volatile_read##size); \
1073 EXPORT_SYMBOL(__tsan_unaligned_volatile_read##size); \
1074 void __tsan_volatile_write##size(void *ptr); \
1075 void __tsan_volatile_write##size(void *ptr) \
1076 { \
1077 const bool is_atomic = size <= sizeof(long long) && \
1078 IS_ALIGNED((unsigned long)ptr, size); \
1079 if (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS) && is_atomic) \
1080 return; \
1081 check_access(ptr, size, \
1082 KCSAN_ACCESS_WRITE | \
1083 (is_atomic ? KCSAN_ACCESS_ATOMIC : 0), \
1084 _RET_IP_); \
1085 } \
1086 EXPORT_SYMBOL(__tsan_volatile_write##size); \
1087 void __tsan_unaligned_volatile_write##size(void *ptr) \
1088 __alias(__tsan_volatile_write##size); \
1089 EXPORT_SYMBOL(__tsan_unaligned_volatile_write##size)
1090
1091 DEFINE_TSAN_VOLATILE_READ_WRITE(1);
1092 DEFINE_TSAN_VOLATILE_READ_WRITE(2);
1093 DEFINE_TSAN_VOLATILE_READ_WRITE(4);
1094 DEFINE_TSAN_VOLATILE_READ_WRITE(8);
1095 DEFINE_TSAN_VOLATILE_READ_WRITE(16);
1096
1097 /*
1098 * Function entry and exit are used to determine the validty of reorder_access.
1099 * Reordering of the access ends at the end of the function scope where the
1100 * access happened. This is done for two reasons:
1101 *
1102 * 1. Artificially limits the scope where missing barriers are detected.
1103 * This minimizes false positives due to uninstrumented functions that
1104 * contain the required barriers but were missed.
1105 *
1106 * 2. Simplifies generating the stack trace of the access.
1107 */
1108 void __tsan_func_entry(void *call_pc);
__tsan_func_entry(void * call_pc)1109 noinline void __tsan_func_entry(void *call_pc)
1110 {
1111 if (!IS_ENABLED(CONFIG_KCSAN_WEAK_MEMORY))
1112 return;
1113
1114 add_kcsan_stack_depth(1);
1115 }
1116 EXPORT_SYMBOL(__tsan_func_entry);
1117
1118 void __tsan_func_exit(void);
__tsan_func_exit(void)1119 noinline void __tsan_func_exit(void)
1120 {
1121 struct kcsan_scoped_access *reorder_access;
1122
1123 if (!IS_ENABLED(CONFIG_KCSAN_WEAK_MEMORY))
1124 return;
1125
1126 reorder_access = get_reorder_access(get_ctx());
1127 if (!reorder_access)
1128 goto out;
1129
1130 if (get_kcsan_stack_depth() <= reorder_access->stack_depth) {
1131 /*
1132 * Access check to catch cases where write without a barrier
1133 * (supposed release) was last access in function: because
1134 * instrumentation is inserted before the real access, a data
1135 * race due to the write giving up a c-s would only be caught if
1136 * we do the conflicting access after.
1137 */
1138 check_access(reorder_access->ptr, reorder_access->size,
1139 reorder_access->type, reorder_access->ip);
1140 reorder_access->size = 0;
1141 reorder_access->stack_depth = INT_MIN;
1142 }
1143 out:
1144 add_kcsan_stack_depth(-1);
1145 }
1146 EXPORT_SYMBOL(__tsan_func_exit);
1147
1148 void __tsan_init(void);
__tsan_init(void)1149 void __tsan_init(void)
1150 {
1151 }
1152 EXPORT_SYMBOL(__tsan_init);
1153
1154 /*
1155 * Instrumentation for atomic builtins (__atomic_*, __sync_*).
1156 *
1157 * Normal kernel code _should not_ be using them directly, but some
1158 * architectures may implement some or all atomics using the compilers'
1159 * builtins.
1160 *
1161 * Note: If an architecture decides to fully implement atomics using the
1162 * builtins, because they are implicitly instrumented by KCSAN (and KASAN,
1163 * etc.), implementing the ARCH_ATOMIC interface (to get instrumentation via
1164 * atomic-instrumented) is no longer necessary.
1165 *
1166 * TSAN instrumentation replaces atomic accesses with calls to any of the below
1167 * functions, whose job is to also execute the operation itself.
1168 */
1169
kcsan_atomic_builtin_memorder(int memorder)1170 static __always_inline void kcsan_atomic_builtin_memorder(int memorder)
1171 {
1172 if (memorder == __ATOMIC_RELEASE ||
1173 memorder == __ATOMIC_SEQ_CST ||
1174 memorder == __ATOMIC_ACQ_REL)
1175 __kcsan_release();
1176 }
1177
1178 #define DEFINE_TSAN_ATOMIC_LOAD_STORE(bits) \
1179 u##bits __tsan_atomic##bits##_load(const u##bits *ptr, int memorder); \
1180 u##bits __tsan_atomic##bits##_load(const u##bits *ptr, int memorder) \
1181 { \
1182 kcsan_atomic_builtin_memorder(memorder); \
1183 if (!IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) { \
1184 check_access(ptr, bits / BITS_PER_BYTE, KCSAN_ACCESS_ATOMIC, _RET_IP_); \
1185 } \
1186 return __atomic_load_n(ptr, memorder); \
1187 } \
1188 EXPORT_SYMBOL(__tsan_atomic##bits##_load); \
1189 void __tsan_atomic##bits##_store(u##bits *ptr, u##bits v, int memorder); \
1190 void __tsan_atomic##bits##_store(u##bits *ptr, u##bits v, int memorder) \
1191 { \
1192 kcsan_atomic_builtin_memorder(memorder); \
1193 if (!IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) { \
1194 check_access(ptr, bits / BITS_PER_BYTE, \
1195 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ATOMIC, _RET_IP_); \
1196 } \
1197 __atomic_store_n(ptr, v, memorder); \
1198 } \
1199 EXPORT_SYMBOL(__tsan_atomic##bits##_store)
1200
1201 #define DEFINE_TSAN_ATOMIC_RMW(op, bits, suffix) \
1202 u##bits __tsan_atomic##bits##_##op(u##bits *ptr, u##bits v, int memorder); \
1203 u##bits __tsan_atomic##bits##_##op(u##bits *ptr, u##bits v, int memorder) \
1204 { \
1205 kcsan_atomic_builtin_memorder(memorder); \
1206 if (!IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) { \
1207 check_access(ptr, bits / BITS_PER_BYTE, \
1208 KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE | \
1209 KCSAN_ACCESS_ATOMIC, _RET_IP_); \
1210 } \
1211 return __atomic_##op##suffix(ptr, v, memorder); \
1212 } \
1213 EXPORT_SYMBOL(__tsan_atomic##bits##_##op)
1214
1215 /*
1216 * Note: CAS operations are always classified as write, even in case they
1217 * fail. We cannot perform check_access() after a write, as it might lead to
1218 * false positives, in cases such as:
1219 *
1220 * T0: __atomic_compare_exchange_n(&p->flag, &old, 1, ...)
1221 *
1222 * T1: if (__atomic_load_n(&p->flag, ...)) {
1223 * modify *p;
1224 * p->flag = 0;
1225 * }
1226 *
1227 * The only downside is that, if there are 3 threads, with one CAS that
1228 * succeeds, another CAS that fails, and an unmarked racing operation, we may
1229 * point at the wrong CAS as the source of the race. However, if we assume that
1230 * all CAS can succeed in some other execution, the data race is still valid.
1231 */
1232 #define DEFINE_TSAN_ATOMIC_CMPXCHG(bits, strength, weak) \
1233 int __tsan_atomic##bits##_compare_exchange_##strength(u##bits *ptr, u##bits *exp, \
1234 u##bits val, int mo, int fail_mo); \
1235 int __tsan_atomic##bits##_compare_exchange_##strength(u##bits *ptr, u##bits *exp, \
1236 u##bits val, int mo, int fail_mo) \
1237 { \
1238 kcsan_atomic_builtin_memorder(mo); \
1239 if (!IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) { \
1240 check_access(ptr, bits / BITS_PER_BYTE, \
1241 KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE | \
1242 KCSAN_ACCESS_ATOMIC, _RET_IP_); \
1243 } \
1244 return __atomic_compare_exchange_n(ptr, exp, val, weak, mo, fail_mo); \
1245 } \
1246 EXPORT_SYMBOL(__tsan_atomic##bits##_compare_exchange_##strength)
1247
1248 #define DEFINE_TSAN_ATOMIC_CMPXCHG_VAL(bits) \
1249 u##bits __tsan_atomic##bits##_compare_exchange_val(u##bits *ptr, u##bits exp, u##bits val, \
1250 int mo, int fail_mo); \
1251 u##bits __tsan_atomic##bits##_compare_exchange_val(u##bits *ptr, u##bits exp, u##bits val, \
1252 int mo, int fail_mo) \
1253 { \
1254 kcsan_atomic_builtin_memorder(mo); \
1255 if (!IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) { \
1256 check_access(ptr, bits / BITS_PER_BYTE, \
1257 KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE | \
1258 KCSAN_ACCESS_ATOMIC, _RET_IP_); \
1259 } \
1260 __atomic_compare_exchange_n(ptr, &exp, val, 0, mo, fail_mo); \
1261 return exp; \
1262 } \
1263 EXPORT_SYMBOL(__tsan_atomic##bits##_compare_exchange_val)
1264
1265 #define DEFINE_TSAN_ATOMIC_OPS(bits) \
1266 DEFINE_TSAN_ATOMIC_LOAD_STORE(bits); \
1267 DEFINE_TSAN_ATOMIC_RMW(exchange, bits, _n); \
1268 DEFINE_TSAN_ATOMIC_RMW(fetch_add, bits, ); \
1269 DEFINE_TSAN_ATOMIC_RMW(fetch_sub, bits, ); \
1270 DEFINE_TSAN_ATOMIC_RMW(fetch_and, bits, ); \
1271 DEFINE_TSAN_ATOMIC_RMW(fetch_or, bits, ); \
1272 DEFINE_TSAN_ATOMIC_RMW(fetch_xor, bits, ); \
1273 DEFINE_TSAN_ATOMIC_RMW(fetch_nand, bits, ); \
1274 DEFINE_TSAN_ATOMIC_CMPXCHG(bits, strong, 0); \
1275 DEFINE_TSAN_ATOMIC_CMPXCHG(bits, weak, 1); \
1276 DEFINE_TSAN_ATOMIC_CMPXCHG_VAL(bits)
1277
1278 DEFINE_TSAN_ATOMIC_OPS(8);
1279 DEFINE_TSAN_ATOMIC_OPS(16);
1280 DEFINE_TSAN_ATOMIC_OPS(32);
1281 #ifdef CONFIG_64BIT
1282 DEFINE_TSAN_ATOMIC_OPS(64);
1283 #endif
1284
1285 void __tsan_atomic_thread_fence(int memorder);
__tsan_atomic_thread_fence(int memorder)1286 void __tsan_atomic_thread_fence(int memorder)
1287 {
1288 kcsan_atomic_builtin_memorder(memorder);
1289 __atomic_thread_fence(memorder);
1290 }
1291 EXPORT_SYMBOL(__tsan_atomic_thread_fence);
1292
1293 /*
1294 * In instrumented files, we emit instrumentation for barriers by mapping the
1295 * kernel barriers to an __atomic_signal_fence(), which is interpreted specially
1296 * and otherwise has no relation to a real __atomic_signal_fence(). No known
1297 * kernel code uses __atomic_signal_fence().
1298 *
1299 * Since fsanitize=thread instrumentation handles __atomic_signal_fence(), which
1300 * are turned into calls to __tsan_atomic_signal_fence(), such instrumentation
1301 * can be disabled via the __no_kcsan function attribute (vs. an explicit call
1302 * which could not). When __no_kcsan is requested, __atomic_signal_fence()
1303 * generates no code.
1304 *
1305 * Note: The result of using __atomic_signal_fence() with KCSAN enabled is
1306 * potentially limiting the compiler's ability to reorder operations; however,
1307 * if barriers were instrumented with explicit calls (without LTO), the compiler
1308 * couldn't optimize much anyway. The result of a hypothetical architecture
1309 * using __atomic_signal_fence() in normal code would be KCSAN false negatives.
1310 */
1311 void __tsan_atomic_signal_fence(int memorder);
__tsan_atomic_signal_fence(int memorder)1312 noinline void __tsan_atomic_signal_fence(int memorder)
1313 {
1314 switch (memorder) {
1315 case __KCSAN_BARRIER_TO_SIGNAL_FENCE_mb:
1316 __kcsan_mb();
1317 break;
1318 case __KCSAN_BARRIER_TO_SIGNAL_FENCE_wmb:
1319 __kcsan_wmb();
1320 break;
1321 case __KCSAN_BARRIER_TO_SIGNAL_FENCE_rmb:
1322 __kcsan_rmb();
1323 break;
1324 case __KCSAN_BARRIER_TO_SIGNAL_FENCE_release:
1325 __kcsan_release();
1326 break;
1327 default:
1328 break;
1329 }
1330 }
1331 EXPORT_SYMBOL(__tsan_atomic_signal_fence);
1332
1333 #ifdef __HAVE_ARCH_MEMSET
1334 void *__tsan_memset(void *s, int c, size_t count);
__tsan_memset(void * s,int c,size_t count)1335 noinline void *__tsan_memset(void *s, int c, size_t count)
1336 {
1337 /*
1338 * Instead of not setting up watchpoints where accessed size is greater
1339 * than MAX_ENCODABLE_SIZE, truncate checked size to MAX_ENCODABLE_SIZE.
1340 */
1341 size_t check_len = min_t(size_t, count, MAX_ENCODABLE_SIZE);
1342
1343 check_access(s, check_len, KCSAN_ACCESS_WRITE, _RET_IP_);
1344 return memset(s, c, count);
1345 }
1346 #else
1347 void *__tsan_memset(void *s, int c, size_t count) __alias(memset);
1348 #endif
1349 EXPORT_SYMBOL(__tsan_memset);
1350
1351 #ifdef __HAVE_ARCH_MEMMOVE
1352 void *__tsan_memmove(void *dst, const void *src, size_t len);
__tsan_memmove(void * dst,const void * src,size_t len)1353 noinline void *__tsan_memmove(void *dst, const void *src, size_t len)
1354 {
1355 size_t check_len = min_t(size_t, len, MAX_ENCODABLE_SIZE);
1356
1357 check_access(dst, check_len, KCSAN_ACCESS_WRITE, _RET_IP_);
1358 check_access(src, check_len, 0, _RET_IP_);
1359 return memmove(dst, src, len);
1360 }
1361 #else
1362 void *__tsan_memmove(void *dst, const void *src, size_t len) __alias(memmove);
1363 #endif
1364 EXPORT_SYMBOL(__tsan_memmove);
1365
1366 #ifdef __HAVE_ARCH_MEMCPY
1367 void *__tsan_memcpy(void *dst, const void *src, size_t len);
__tsan_memcpy(void * dst,const void * src,size_t len)1368 noinline void *__tsan_memcpy(void *dst, const void *src, size_t len)
1369 {
1370 size_t check_len = min_t(size_t, len, MAX_ENCODABLE_SIZE);
1371
1372 check_access(dst, check_len, KCSAN_ACCESS_WRITE, _RET_IP_);
1373 check_access(src, check_len, 0, _RET_IP_);
1374 return memcpy(dst, src, len);
1375 }
1376 #else
1377 void *__tsan_memcpy(void *dst, const void *src, size_t len) __alias(memcpy);
1378 #endif
1379 EXPORT_SYMBOL(__tsan_memcpy);
1380