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