core.c 48 KB

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