kcov.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. // SPDX-License-Identifier: GPL-2.0
  2. #define pr_fmt(fmt) "kcov: " fmt
  3. #define DISABLE_BRANCH_PROFILING
  4. #include <linux/atomic.h>
  5. #include <linux/compiler.h>
  6. #include <linux/errno.h>
  7. #include <linux/export.h>
  8. #include <linux/types.h>
  9. #include <linux/file.h>
  10. #include <linux/fs.h>
  11. #include <linux/hashtable.h>
  12. #include <linux/init.h>
  13. #include <linux/jiffies.h>
  14. #include <linux/kmsan-checks.h>
  15. #include <linux/mm.h>
  16. #include <linux/preempt.h>
  17. #include <linux/printk.h>
  18. #include <linux/sched.h>
  19. #include <linux/slab.h>
  20. #include <linux/spinlock.h>
  21. #include <linux/vmalloc.h>
  22. #include <linux/debugfs.h>
  23. #include <linux/uaccess.h>
  24. #include <linux/kcov.h>
  25. #include <linux/refcount.h>
  26. #include <linux/log2.h>
  27. #include <asm/setup.h>
  28. #define kcov_debug(fmt, ...) pr_debug("%s: " fmt, __func__, ##__VA_ARGS__)
  29. /* Number of 64-bit words written per one comparison: */
  30. #define KCOV_WORDS_PER_CMP 4
  31. /*
  32. * kcov descriptor (one per opened debugfs file).
  33. * State transitions of the descriptor:
  34. * - initial state after open()
  35. * - then there must be a single ioctl(KCOV_INIT_TRACE) call
  36. * - then, mmap() call (several calls are allowed but not useful)
  37. * - then, ioctl(KCOV_ENABLE, arg), where arg is
  38. * KCOV_TRACE_PC - to trace only the PCs
  39. * or
  40. * KCOV_TRACE_CMP - to trace only the comparison operands
  41. * - then, ioctl(KCOV_DISABLE) to disable the task.
  42. * Enabling/disabling ioctls can be repeated (only one task a time allowed).
  43. */
  44. struct kcov {
  45. /*
  46. * Reference counter. We keep one for:
  47. * - opened file descriptor
  48. * - task with enabled coverage (we can't unwire it from another task)
  49. * - each code section for remote coverage collection
  50. */
  51. refcount_t refcount;
  52. /* The lock protects mode, size, area and t. */
  53. spinlock_t lock;
  54. enum kcov_mode mode;
  55. /* Size of arena (in long's). */
  56. unsigned int size;
  57. /* Coverage buffer shared with user space. */
  58. void *area;
  59. /* Task for which we collect coverage, or NULL. */
  60. struct task_struct *t;
  61. /* Collecting coverage from remote (background) threads. */
  62. bool remote;
  63. /* Size of remote area (in long's). */
  64. unsigned int remote_size;
  65. /*
  66. * Sequence is incremented each time kcov is reenabled, used by
  67. * kcov_remote_stop(), see the comment there.
  68. */
  69. int sequence;
  70. };
  71. struct kcov_remote_area {
  72. struct list_head list;
  73. unsigned int size;
  74. };
  75. struct kcov_remote {
  76. u64 handle;
  77. struct kcov *kcov;
  78. struct hlist_node hnode;
  79. };
  80. static DEFINE_SPINLOCK(kcov_remote_lock);
  81. static DEFINE_HASHTABLE(kcov_remote_map, 4);
  82. static struct list_head kcov_remote_areas = LIST_HEAD_INIT(kcov_remote_areas);
  83. struct kcov_percpu_data {
  84. void *irq_area;
  85. local_lock_t lock;
  86. unsigned int saved_mode;
  87. unsigned int saved_size;
  88. void *saved_area;
  89. struct kcov *saved_kcov;
  90. int saved_sequence;
  91. };
  92. static DEFINE_PER_CPU(struct kcov_percpu_data, kcov_percpu_data) = {
  93. .lock = INIT_LOCAL_LOCK(lock),
  94. };
  95. /* Must be called with kcov_remote_lock locked. */
  96. static struct kcov_remote *kcov_remote_find(u64 handle)
  97. {
  98. struct kcov_remote *remote;
  99. hash_for_each_possible(kcov_remote_map, remote, hnode, handle) {
  100. if (remote->handle == handle)
  101. return remote;
  102. }
  103. return NULL;
  104. }
  105. /* Must be called with kcov_remote_lock locked. */
  106. static struct kcov_remote *kcov_remote_add(struct kcov *kcov, u64 handle)
  107. {
  108. struct kcov_remote *remote;
  109. if (kcov_remote_find(handle))
  110. return ERR_PTR(-EEXIST);
  111. remote = kmalloc(sizeof(*remote), GFP_ATOMIC);
  112. if (!remote)
  113. return ERR_PTR(-ENOMEM);
  114. remote->handle = handle;
  115. remote->kcov = kcov;
  116. hash_add(kcov_remote_map, &remote->hnode, handle);
  117. return remote;
  118. }
  119. /* Must be called with kcov_remote_lock locked. */
  120. static struct kcov_remote_area *kcov_remote_area_get(unsigned int size)
  121. {
  122. struct kcov_remote_area *area;
  123. struct list_head *pos;
  124. list_for_each(pos, &kcov_remote_areas) {
  125. area = list_entry(pos, struct kcov_remote_area, list);
  126. if (area->size == size) {
  127. list_del(&area->list);
  128. return area;
  129. }
  130. }
  131. return NULL;
  132. }
  133. /* Must be called with kcov_remote_lock locked. */
  134. static void kcov_remote_area_put(struct kcov_remote_area *area,
  135. unsigned int size)
  136. {
  137. INIT_LIST_HEAD(&area->list);
  138. area->size = size;
  139. list_add(&area->list, &kcov_remote_areas);
  140. /*
  141. * KMSAN doesn't instrument this file, so it may not know area->list
  142. * is initialized. Unpoison it explicitly to avoid reports in
  143. * kcov_remote_area_get().
  144. */
  145. kmsan_unpoison_memory(&area->list, sizeof(area->list));
  146. }
  147. /*
  148. * Unlike in_serving_softirq(), this function returns false when called during
  149. * a hardirq or an NMI that happened in the softirq context.
  150. */
  151. static __always_inline bool in_softirq_really(void)
  152. {
  153. return in_serving_softirq() && !in_hardirq() && !in_nmi();
  154. }
  155. static notrace bool check_kcov_mode(enum kcov_mode needed_mode, struct task_struct *t)
  156. {
  157. unsigned int mode;
  158. /*
  159. * We are interested in code coverage as a function of a syscall inputs,
  160. * so we ignore code executed in interrupts, unless we are in a remote
  161. * coverage collection section in a softirq.
  162. */
  163. if (!in_task() && !(in_softirq_really() && t->kcov_softirq))
  164. return false;
  165. mode = READ_ONCE(t->kcov_mode);
  166. /*
  167. * There is some code that runs in interrupts but for which
  168. * in_interrupt() returns false (e.g. preempt_schedule_irq()).
  169. * READ_ONCE()/barrier() effectively provides load-acquire wrt
  170. * interrupts, there are paired barrier()/WRITE_ONCE() in
  171. * kcov_start().
  172. */
  173. barrier();
  174. return mode == needed_mode;
  175. }
  176. static notrace unsigned long canonicalize_ip(unsigned long ip)
  177. {
  178. #ifdef CONFIG_RANDOMIZE_BASE
  179. ip -= kaslr_offset();
  180. #endif
  181. return ip;
  182. }
  183. /*
  184. * Entry point from instrumented code.
  185. * This is called once per basic-block/edge.
  186. */
  187. void notrace __sanitizer_cov_trace_pc(void)
  188. {
  189. struct task_struct *t;
  190. unsigned long *area;
  191. unsigned long ip = canonicalize_ip(_RET_IP_);
  192. unsigned long pos;
  193. t = current;
  194. if (!check_kcov_mode(KCOV_MODE_TRACE_PC, t))
  195. return;
  196. area = t->kcov_area;
  197. /* The first 64-bit word is the number of subsequent PCs. */
  198. pos = READ_ONCE(area[0]) + 1;
  199. if (likely(pos < t->kcov_size)) {
  200. /* Previously we write pc before updating pos. However, some
  201. * early interrupt code could bypass check_kcov_mode() check
  202. * and invoke __sanitizer_cov_trace_pc(). If such interrupt is
  203. * raised between writing pc and updating pos, the pc could be
  204. * overitten by the recursive __sanitizer_cov_trace_pc().
  205. * Update pos before writing pc to avoid such interleaving.
  206. */
  207. WRITE_ONCE(area[0], pos);
  208. barrier();
  209. area[pos] = ip;
  210. }
  211. }
  212. EXPORT_SYMBOL(__sanitizer_cov_trace_pc);
  213. #ifdef CONFIG_KCOV_ENABLE_COMPARISONS
  214. static void notrace write_comp_data(u64 type, u64 arg1, u64 arg2, u64 ip)
  215. {
  216. struct task_struct *t;
  217. u64 *area;
  218. u64 count, start_index, end_pos, max_pos;
  219. t = current;
  220. if (!check_kcov_mode(KCOV_MODE_TRACE_CMP, t))
  221. return;
  222. ip = canonicalize_ip(ip);
  223. /*
  224. * We write all comparison arguments and types as u64.
  225. * The buffer was allocated for t->kcov_size unsigned longs.
  226. */
  227. area = (u64 *)t->kcov_area;
  228. max_pos = t->kcov_size * sizeof(unsigned long);
  229. count = READ_ONCE(area[0]);
  230. /* Every record is KCOV_WORDS_PER_CMP 64-bit words. */
  231. start_index = 1 + count * KCOV_WORDS_PER_CMP;
  232. end_pos = (start_index + KCOV_WORDS_PER_CMP) * sizeof(u64);
  233. if (likely(end_pos <= max_pos)) {
  234. /* See comment in __sanitizer_cov_trace_pc(). */
  235. WRITE_ONCE(area[0], count + 1);
  236. barrier();
  237. area[start_index] = type;
  238. area[start_index + 1] = arg1;
  239. area[start_index + 2] = arg2;
  240. area[start_index + 3] = ip;
  241. }
  242. }
  243. void notrace __sanitizer_cov_trace_cmp1(u8 arg1, u8 arg2)
  244. {
  245. write_comp_data(KCOV_CMP_SIZE(0), arg1, arg2, _RET_IP_);
  246. }
  247. EXPORT_SYMBOL(__sanitizer_cov_trace_cmp1);
  248. void notrace __sanitizer_cov_trace_cmp2(u16 arg1, u16 arg2)
  249. {
  250. write_comp_data(KCOV_CMP_SIZE(1), arg1, arg2, _RET_IP_);
  251. }
  252. EXPORT_SYMBOL(__sanitizer_cov_trace_cmp2);
  253. void notrace __sanitizer_cov_trace_cmp4(u32 arg1, u32 arg2)
  254. {
  255. write_comp_data(KCOV_CMP_SIZE(2), arg1, arg2, _RET_IP_);
  256. }
  257. EXPORT_SYMBOL(__sanitizer_cov_trace_cmp4);
  258. void notrace __sanitizer_cov_trace_cmp8(kcov_u64 arg1, kcov_u64 arg2)
  259. {
  260. write_comp_data(KCOV_CMP_SIZE(3), arg1, arg2, _RET_IP_);
  261. }
  262. EXPORT_SYMBOL(__sanitizer_cov_trace_cmp8);
  263. void notrace __sanitizer_cov_trace_const_cmp1(u8 arg1, u8 arg2)
  264. {
  265. write_comp_data(KCOV_CMP_SIZE(0) | KCOV_CMP_CONST, arg1, arg2,
  266. _RET_IP_);
  267. }
  268. EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp1);
  269. void notrace __sanitizer_cov_trace_const_cmp2(u16 arg1, u16 arg2)
  270. {
  271. write_comp_data(KCOV_CMP_SIZE(1) | KCOV_CMP_CONST, arg1, arg2,
  272. _RET_IP_);
  273. }
  274. EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp2);
  275. void notrace __sanitizer_cov_trace_const_cmp4(u32 arg1, u32 arg2)
  276. {
  277. write_comp_data(KCOV_CMP_SIZE(2) | KCOV_CMP_CONST, arg1, arg2,
  278. _RET_IP_);
  279. }
  280. EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp4);
  281. void notrace __sanitizer_cov_trace_const_cmp8(kcov_u64 arg1, kcov_u64 arg2)
  282. {
  283. write_comp_data(KCOV_CMP_SIZE(3) | KCOV_CMP_CONST, arg1, arg2,
  284. _RET_IP_);
  285. }
  286. EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp8);
  287. void notrace __sanitizer_cov_trace_switch(kcov_u64 val, void *arg)
  288. {
  289. u64 i;
  290. u64 *cases = arg;
  291. u64 count = cases[0];
  292. u64 size = cases[1];
  293. u64 type = KCOV_CMP_CONST;
  294. switch (size) {
  295. case 8:
  296. type |= KCOV_CMP_SIZE(0);
  297. break;
  298. case 16:
  299. type |= KCOV_CMP_SIZE(1);
  300. break;
  301. case 32:
  302. type |= KCOV_CMP_SIZE(2);
  303. break;
  304. case 64:
  305. type |= KCOV_CMP_SIZE(3);
  306. break;
  307. default:
  308. return;
  309. }
  310. for (i = 0; i < count; i++)
  311. write_comp_data(type, cases[i + 2], val, _RET_IP_);
  312. }
  313. EXPORT_SYMBOL(__sanitizer_cov_trace_switch);
  314. #endif /* ifdef CONFIG_KCOV_ENABLE_COMPARISONS */
  315. static void kcov_start(struct task_struct *t, struct kcov *kcov,
  316. unsigned int size, void *area, enum kcov_mode mode,
  317. int sequence)
  318. {
  319. kcov_debug("t = %px, size = %u, area = %px\n", t, size, area);
  320. t->kcov = kcov;
  321. /* Cache in task struct for performance. */
  322. t->kcov_size = size;
  323. t->kcov_area = area;
  324. t->kcov_sequence = sequence;
  325. /* See comment in check_kcov_mode(). */
  326. barrier();
  327. WRITE_ONCE(t->kcov_mode, mode);
  328. }
  329. static void kcov_stop(struct task_struct *t)
  330. {
  331. WRITE_ONCE(t->kcov_mode, KCOV_MODE_DISABLED);
  332. barrier();
  333. t->kcov = NULL;
  334. t->kcov_size = 0;
  335. t->kcov_area = NULL;
  336. }
  337. static void kcov_task_reset(struct task_struct *t)
  338. {
  339. kcov_stop(t);
  340. t->kcov_sequence = 0;
  341. t->kcov_handle = 0;
  342. }
  343. void kcov_task_init(struct task_struct *t)
  344. {
  345. kcov_task_reset(t);
  346. t->kcov_handle = current->kcov_handle;
  347. }
  348. static void kcov_reset(struct kcov *kcov)
  349. {
  350. kcov->t = NULL;
  351. kcov->mode = KCOV_MODE_INIT;
  352. kcov->remote = false;
  353. kcov->remote_size = 0;
  354. kcov->sequence++;
  355. }
  356. static void kcov_remote_reset(struct kcov *kcov)
  357. {
  358. int bkt;
  359. struct kcov_remote *remote;
  360. struct hlist_node *tmp;
  361. unsigned long flags;
  362. spin_lock_irqsave(&kcov_remote_lock, flags);
  363. hash_for_each_safe(kcov_remote_map, bkt, tmp, remote, hnode) {
  364. if (remote->kcov != kcov)
  365. continue;
  366. hash_del(&remote->hnode);
  367. kfree(remote);
  368. }
  369. /* Do reset before unlock to prevent races with kcov_remote_start(). */
  370. kcov_reset(kcov);
  371. spin_unlock_irqrestore(&kcov_remote_lock, flags);
  372. }
  373. static void kcov_disable(struct task_struct *t, struct kcov *kcov)
  374. {
  375. kcov_task_reset(t);
  376. if (kcov->remote)
  377. kcov_remote_reset(kcov);
  378. else
  379. kcov_reset(kcov);
  380. }
  381. static void kcov_get(struct kcov *kcov)
  382. {
  383. refcount_inc(&kcov->refcount);
  384. }
  385. static void kcov_put(struct kcov *kcov)
  386. {
  387. if (refcount_dec_and_test(&kcov->refcount)) {
  388. kcov_remote_reset(kcov);
  389. vfree(kcov->area);
  390. kfree(kcov);
  391. }
  392. }
  393. void kcov_task_exit(struct task_struct *t)
  394. {
  395. struct kcov *kcov;
  396. unsigned long flags;
  397. kcov = t->kcov;
  398. if (kcov == NULL)
  399. return;
  400. spin_lock_irqsave(&kcov->lock, flags);
  401. kcov_debug("t = %px, kcov->t = %px\n", t, kcov->t);
  402. /*
  403. * For KCOV_ENABLE devices we want to make sure that t->kcov->t == t,
  404. * which comes down to:
  405. * WARN_ON(!kcov->remote && kcov->t != t);
  406. *
  407. * For KCOV_REMOTE_ENABLE devices, the exiting task is either:
  408. *
  409. * 1. A remote task between kcov_remote_start() and kcov_remote_stop().
  410. * In this case we should print a warning right away, since a task
  411. * shouldn't be exiting when it's in a kcov coverage collection
  412. * section. Here t points to the task that is collecting remote
  413. * coverage, and t->kcov->t points to the thread that created the
  414. * kcov device. Which means that to detect this case we need to
  415. * check that t != t->kcov->t, and this gives us the following:
  416. * WARN_ON(kcov->remote && kcov->t != t);
  417. *
  418. * 2. The task that created kcov exiting without calling KCOV_DISABLE,
  419. * and then again we make sure that t->kcov->t == t:
  420. * WARN_ON(kcov->remote && kcov->t != t);
  421. *
  422. * By combining all three checks into one we get:
  423. */
  424. if (WARN_ON(kcov->t != t)) {
  425. spin_unlock_irqrestore(&kcov->lock, flags);
  426. return;
  427. }
  428. /* Just to not leave dangling references behind. */
  429. kcov_disable(t, kcov);
  430. spin_unlock_irqrestore(&kcov->lock, flags);
  431. kcov_put(kcov);
  432. }
  433. static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)
  434. {
  435. int res = 0;
  436. struct kcov *kcov = vma->vm_file->private_data;
  437. unsigned long size, off;
  438. struct page *page;
  439. unsigned long flags;
  440. spin_lock_irqsave(&kcov->lock, flags);
  441. size = kcov->size * sizeof(unsigned long);
  442. if (kcov->area == NULL || vma->vm_pgoff != 0 ||
  443. vma->vm_end - vma->vm_start != size) {
  444. res = -EINVAL;
  445. goto exit;
  446. }
  447. spin_unlock_irqrestore(&kcov->lock, flags);
  448. vm_flags_set(vma, VM_DONTEXPAND);
  449. for (off = 0; off < size; off += PAGE_SIZE) {
  450. page = vmalloc_to_page(kcov->area + off);
  451. res = vm_insert_page(vma, vma->vm_start + off, page);
  452. if (res) {
  453. pr_warn_once("kcov: vm_insert_page() failed\n");
  454. return res;
  455. }
  456. }
  457. return 0;
  458. exit:
  459. spin_unlock_irqrestore(&kcov->lock, flags);
  460. return res;
  461. }
  462. static int kcov_open(struct inode *inode, struct file *filep)
  463. {
  464. struct kcov *kcov;
  465. kcov = kzalloc(sizeof(*kcov), GFP_KERNEL);
  466. if (!kcov)
  467. return -ENOMEM;
  468. kcov->mode = KCOV_MODE_DISABLED;
  469. kcov->sequence = 1;
  470. refcount_set(&kcov->refcount, 1);
  471. spin_lock_init(&kcov->lock);
  472. filep->private_data = kcov;
  473. return nonseekable_open(inode, filep);
  474. }
  475. static int kcov_close(struct inode *inode, struct file *filep)
  476. {
  477. kcov_put(filep->private_data);
  478. return 0;
  479. }
  480. static int kcov_get_mode(unsigned long arg)
  481. {
  482. if (arg == KCOV_TRACE_PC)
  483. return KCOV_MODE_TRACE_PC;
  484. else if (arg == KCOV_TRACE_CMP)
  485. #ifdef CONFIG_KCOV_ENABLE_COMPARISONS
  486. return KCOV_MODE_TRACE_CMP;
  487. #else
  488. return -ENOTSUPP;
  489. #endif
  490. else
  491. return -EINVAL;
  492. }
  493. /*
  494. * Fault in a lazily-faulted vmalloc area before it can be used by
  495. * __santizer_cov_trace_pc(), to avoid recursion issues if any code on the
  496. * vmalloc fault handling path is instrumented.
  497. */
  498. static void kcov_fault_in_area(struct kcov *kcov)
  499. {
  500. unsigned long stride = PAGE_SIZE / sizeof(unsigned long);
  501. unsigned long *area = kcov->area;
  502. unsigned long offset;
  503. for (offset = 0; offset < kcov->size; offset += stride)
  504. READ_ONCE(area[offset]);
  505. }
  506. static inline bool kcov_check_handle(u64 handle, bool common_valid,
  507. bool uncommon_valid, bool zero_valid)
  508. {
  509. if (handle & ~(KCOV_SUBSYSTEM_MASK | KCOV_INSTANCE_MASK))
  510. return false;
  511. switch (handle & KCOV_SUBSYSTEM_MASK) {
  512. case KCOV_SUBSYSTEM_COMMON:
  513. return (handle & KCOV_INSTANCE_MASK) ?
  514. common_valid : zero_valid;
  515. case KCOV_SUBSYSTEM_USB:
  516. return uncommon_valid;
  517. default:
  518. return false;
  519. }
  520. return false;
  521. }
  522. static int kcov_ioctl_locked(struct kcov *kcov, unsigned int cmd,
  523. unsigned long arg)
  524. {
  525. struct task_struct *t;
  526. unsigned long flags, unused;
  527. int mode, i;
  528. struct kcov_remote_arg *remote_arg;
  529. struct kcov_remote *remote;
  530. switch (cmd) {
  531. case KCOV_ENABLE:
  532. /*
  533. * Enable coverage for the current task.
  534. * At this point user must have been enabled trace mode,
  535. * and mmapped the file. Coverage collection is disabled only
  536. * at task exit or voluntary by KCOV_DISABLE. After that it can
  537. * be enabled for another task.
  538. */
  539. if (kcov->mode != KCOV_MODE_INIT || !kcov->area)
  540. return -EINVAL;
  541. t = current;
  542. if (kcov->t != NULL || t->kcov != NULL)
  543. return -EBUSY;
  544. mode = kcov_get_mode(arg);
  545. if (mode < 0)
  546. return mode;
  547. kcov_fault_in_area(kcov);
  548. kcov->mode = mode;
  549. kcov_start(t, kcov, kcov->size, kcov->area, kcov->mode,
  550. kcov->sequence);
  551. kcov->t = t;
  552. /* Put either in kcov_task_exit() or in KCOV_DISABLE. */
  553. kcov_get(kcov);
  554. return 0;
  555. case KCOV_DISABLE:
  556. /* Disable coverage for the current task. */
  557. unused = arg;
  558. if (unused != 0 || current->kcov != kcov)
  559. return -EINVAL;
  560. t = current;
  561. if (WARN_ON(kcov->t != t))
  562. return -EINVAL;
  563. kcov_disable(t, kcov);
  564. kcov_put(kcov);
  565. return 0;
  566. case KCOV_REMOTE_ENABLE:
  567. if (kcov->mode != KCOV_MODE_INIT || !kcov->area)
  568. return -EINVAL;
  569. t = current;
  570. if (kcov->t != NULL || t->kcov != NULL)
  571. return -EBUSY;
  572. remote_arg = (struct kcov_remote_arg *)arg;
  573. mode = kcov_get_mode(remote_arg->trace_mode);
  574. if (mode < 0)
  575. return mode;
  576. if ((unsigned long)remote_arg->area_size >
  577. LONG_MAX / sizeof(unsigned long))
  578. return -EINVAL;
  579. kcov->mode = mode;
  580. t->kcov = kcov;
  581. t->kcov_mode = KCOV_MODE_REMOTE;
  582. kcov->t = t;
  583. kcov->remote = true;
  584. kcov->remote_size = remote_arg->area_size;
  585. spin_lock_irqsave(&kcov_remote_lock, flags);
  586. for (i = 0; i < remote_arg->num_handles; i++) {
  587. if (!kcov_check_handle(remote_arg->handles[i],
  588. false, true, false)) {
  589. spin_unlock_irqrestore(&kcov_remote_lock,
  590. flags);
  591. kcov_disable(t, kcov);
  592. return -EINVAL;
  593. }
  594. remote = kcov_remote_add(kcov, remote_arg->handles[i]);
  595. if (IS_ERR(remote)) {
  596. spin_unlock_irqrestore(&kcov_remote_lock,
  597. flags);
  598. kcov_disable(t, kcov);
  599. return PTR_ERR(remote);
  600. }
  601. }
  602. if (remote_arg->common_handle) {
  603. if (!kcov_check_handle(remote_arg->common_handle,
  604. true, false, false)) {
  605. spin_unlock_irqrestore(&kcov_remote_lock,
  606. flags);
  607. kcov_disable(t, kcov);
  608. return -EINVAL;
  609. }
  610. remote = kcov_remote_add(kcov,
  611. remote_arg->common_handle);
  612. if (IS_ERR(remote)) {
  613. spin_unlock_irqrestore(&kcov_remote_lock,
  614. flags);
  615. kcov_disable(t, kcov);
  616. return PTR_ERR(remote);
  617. }
  618. t->kcov_handle = remote_arg->common_handle;
  619. }
  620. spin_unlock_irqrestore(&kcov_remote_lock, flags);
  621. /* Put either in kcov_task_exit() or in KCOV_DISABLE. */
  622. kcov_get(kcov);
  623. return 0;
  624. default:
  625. return -ENOTTY;
  626. }
  627. }
  628. static long kcov_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
  629. {
  630. struct kcov *kcov;
  631. int res;
  632. struct kcov_remote_arg *remote_arg = NULL;
  633. unsigned int remote_num_handles;
  634. unsigned long remote_arg_size;
  635. unsigned long size, flags;
  636. void *area;
  637. kcov = filep->private_data;
  638. switch (cmd) {
  639. case KCOV_INIT_TRACE:
  640. /*
  641. * Enable kcov in trace mode and setup buffer size.
  642. * Must happen before anything else.
  643. *
  644. * First check the size argument - it must be at least 2
  645. * to hold the current position and one PC.
  646. */
  647. size = arg;
  648. if (size < 2 || size > INT_MAX / sizeof(unsigned long))
  649. return -EINVAL;
  650. area = vmalloc_user(size * sizeof(unsigned long));
  651. if (area == NULL)
  652. return -ENOMEM;
  653. spin_lock_irqsave(&kcov->lock, flags);
  654. if (kcov->mode != KCOV_MODE_DISABLED) {
  655. spin_unlock_irqrestore(&kcov->lock, flags);
  656. vfree(area);
  657. return -EBUSY;
  658. }
  659. kcov->area = area;
  660. kcov->size = size;
  661. kcov->mode = KCOV_MODE_INIT;
  662. spin_unlock_irqrestore(&kcov->lock, flags);
  663. return 0;
  664. case KCOV_REMOTE_ENABLE:
  665. if (get_user(remote_num_handles, (unsigned __user *)(arg +
  666. offsetof(struct kcov_remote_arg, num_handles))))
  667. return -EFAULT;
  668. if (remote_num_handles > KCOV_REMOTE_MAX_HANDLES)
  669. return -EINVAL;
  670. remote_arg_size = struct_size(remote_arg, handles,
  671. remote_num_handles);
  672. remote_arg = memdup_user((void __user *)arg, remote_arg_size);
  673. if (IS_ERR(remote_arg))
  674. return PTR_ERR(remote_arg);
  675. if (remote_arg->num_handles != remote_num_handles) {
  676. kfree(remote_arg);
  677. return -EINVAL;
  678. }
  679. arg = (unsigned long)remote_arg;
  680. fallthrough;
  681. default:
  682. /*
  683. * All other commands can be normally executed under a spin lock, so we
  684. * obtain and release it here in order to simplify kcov_ioctl_locked().
  685. */
  686. spin_lock_irqsave(&kcov->lock, flags);
  687. res = kcov_ioctl_locked(kcov, cmd, arg);
  688. spin_unlock_irqrestore(&kcov->lock, flags);
  689. kfree(remote_arg);
  690. return res;
  691. }
  692. }
  693. static const struct file_operations kcov_fops = {
  694. .open = kcov_open,
  695. .unlocked_ioctl = kcov_ioctl,
  696. .compat_ioctl = kcov_ioctl,
  697. .mmap = kcov_mmap,
  698. .release = kcov_close,
  699. };
  700. /*
  701. * kcov_remote_start() and kcov_remote_stop() can be used to annotate a section
  702. * of code in a kernel background thread or in a softirq to allow kcov to be
  703. * used to collect coverage from that part of code.
  704. *
  705. * The handle argument of kcov_remote_start() identifies a code section that is
  706. * used for coverage collection. A userspace process passes this handle to
  707. * KCOV_REMOTE_ENABLE ioctl to make the used kcov device start collecting
  708. * coverage for the code section identified by this handle.
  709. *
  710. * The usage of these annotations in the kernel code is different depending on
  711. * the type of the kernel thread whose code is being annotated.
  712. *
  713. * For global kernel threads that are spawned in a limited number of instances
  714. * (e.g. one USB hub_event() worker thread is spawned per USB HCD) and for
  715. * softirqs, each instance must be assigned a unique 4-byte instance id. The
  716. * instance id is then combined with a 1-byte subsystem id to get a handle via
  717. * kcov_remote_handle(subsystem_id, instance_id).
  718. *
  719. * For local kernel threads that are spawned from system calls handler when a
  720. * user interacts with some kernel interface (e.g. vhost workers), a handle is
  721. * passed from a userspace process as the common_handle field of the
  722. * kcov_remote_arg struct (note, that the user must generate a handle by using
  723. * kcov_remote_handle() with KCOV_SUBSYSTEM_COMMON as the subsystem id and an
  724. * arbitrary 4-byte non-zero number as the instance id). This common handle
  725. * then gets saved into the task_struct of the process that issued the
  726. * KCOV_REMOTE_ENABLE ioctl. When this process issues system calls that spawn
  727. * kernel threads, the common handle must be retrieved via kcov_common_handle()
  728. * and passed to the spawned threads via custom annotations. Those kernel
  729. * threads must in turn be annotated with kcov_remote_start(common_handle) and
  730. * kcov_remote_stop(). All of the threads that are spawned by the same process
  731. * obtain the same handle, hence the name "common".
  732. *
  733. * See Documentation/dev-tools/kcov.rst for more details.
  734. *
  735. * Internally, kcov_remote_start() looks up the kcov device associated with the
  736. * provided handle, allocates an area for coverage collection, and saves the
  737. * pointers to kcov and area into the current task_struct to allow coverage to
  738. * be collected via __sanitizer_cov_trace_pc().
  739. * In turns kcov_remote_stop() clears those pointers from task_struct to stop
  740. * collecting coverage and copies all collected coverage into the kcov area.
  741. */
  742. static inline bool kcov_mode_enabled(unsigned int mode)
  743. {
  744. return (mode & ~KCOV_IN_CTXSW) != KCOV_MODE_DISABLED;
  745. }
  746. static void kcov_remote_softirq_start(struct task_struct *t)
  747. {
  748. struct kcov_percpu_data *data = this_cpu_ptr(&kcov_percpu_data);
  749. unsigned int mode;
  750. mode = READ_ONCE(t->kcov_mode);
  751. barrier();
  752. if (kcov_mode_enabled(mode)) {
  753. data->saved_mode = mode;
  754. data->saved_size = t->kcov_size;
  755. data->saved_area = t->kcov_area;
  756. data->saved_sequence = t->kcov_sequence;
  757. data->saved_kcov = t->kcov;
  758. kcov_stop(t);
  759. }
  760. }
  761. static void kcov_remote_softirq_stop(struct task_struct *t)
  762. {
  763. struct kcov_percpu_data *data = this_cpu_ptr(&kcov_percpu_data);
  764. if (data->saved_kcov) {
  765. kcov_start(t, data->saved_kcov, data->saved_size,
  766. data->saved_area, data->saved_mode,
  767. data->saved_sequence);
  768. data->saved_mode = 0;
  769. data->saved_size = 0;
  770. data->saved_area = NULL;
  771. data->saved_sequence = 0;
  772. data->saved_kcov = NULL;
  773. }
  774. }
  775. void kcov_remote_start(u64 handle)
  776. {
  777. struct task_struct *t = current;
  778. struct kcov_remote *remote;
  779. struct kcov *kcov;
  780. unsigned int mode;
  781. void *area;
  782. unsigned int size;
  783. int sequence;
  784. unsigned long flags;
  785. if (WARN_ON(!kcov_check_handle(handle, true, true, true)))
  786. return;
  787. if (!in_task() && !in_softirq_really())
  788. return;
  789. local_lock_irqsave(&kcov_percpu_data.lock, flags);
  790. /*
  791. * Check that kcov_remote_start() is not called twice in background
  792. * threads nor called by user tasks (with enabled kcov).
  793. */
  794. mode = READ_ONCE(t->kcov_mode);
  795. if (WARN_ON(in_task() && kcov_mode_enabled(mode))) {
  796. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  797. return;
  798. }
  799. /*
  800. * Check that kcov_remote_start() is not called twice in softirqs.
  801. * Note, that kcov_remote_start() can be called from a softirq that
  802. * happened while collecting coverage from a background thread.
  803. */
  804. if (WARN_ON(in_serving_softirq() && t->kcov_softirq)) {
  805. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  806. return;
  807. }
  808. spin_lock(&kcov_remote_lock);
  809. remote = kcov_remote_find(handle);
  810. if (!remote) {
  811. spin_unlock(&kcov_remote_lock);
  812. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  813. return;
  814. }
  815. kcov_debug("handle = %llx, context: %s\n", handle,
  816. in_task() ? "task" : "softirq");
  817. kcov = remote->kcov;
  818. /* Put in kcov_remote_stop(). */
  819. kcov_get(kcov);
  820. /*
  821. * Read kcov fields before unlock to prevent races with
  822. * KCOV_DISABLE / kcov_remote_reset().
  823. */
  824. mode = kcov->mode;
  825. sequence = kcov->sequence;
  826. if (in_task()) {
  827. size = kcov->remote_size;
  828. area = kcov_remote_area_get(size);
  829. } else {
  830. size = CONFIG_KCOV_IRQ_AREA_SIZE;
  831. area = this_cpu_ptr(&kcov_percpu_data)->irq_area;
  832. }
  833. spin_unlock(&kcov_remote_lock);
  834. /* Can only happen when in_task(). */
  835. if (!area) {
  836. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  837. area = vmalloc(size * sizeof(unsigned long));
  838. if (!area) {
  839. kcov_put(kcov);
  840. return;
  841. }
  842. local_lock_irqsave(&kcov_percpu_data.lock, flags);
  843. }
  844. /* Reset coverage size. */
  845. *(u64 *)area = 0;
  846. if (in_serving_softirq()) {
  847. kcov_remote_softirq_start(t);
  848. t->kcov_softirq = 1;
  849. }
  850. kcov_start(t, kcov, size, area, mode, sequence);
  851. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  852. }
  853. EXPORT_SYMBOL(kcov_remote_start);
  854. static void kcov_move_area(enum kcov_mode mode, void *dst_area,
  855. unsigned int dst_area_size, void *src_area)
  856. {
  857. u64 word_size = sizeof(unsigned long);
  858. u64 count_size, entry_size_log;
  859. u64 dst_len, src_len;
  860. void *dst_entries, *src_entries;
  861. u64 dst_occupied, dst_free, bytes_to_move, entries_moved;
  862. kcov_debug("%px %u <= %px %lu\n",
  863. dst_area, dst_area_size, src_area, *(unsigned long *)src_area);
  864. switch (mode) {
  865. case KCOV_MODE_TRACE_PC:
  866. dst_len = READ_ONCE(*(unsigned long *)dst_area);
  867. src_len = *(unsigned long *)src_area;
  868. count_size = sizeof(unsigned long);
  869. entry_size_log = __ilog2_u64(sizeof(unsigned long));
  870. break;
  871. case KCOV_MODE_TRACE_CMP:
  872. dst_len = READ_ONCE(*(u64 *)dst_area);
  873. src_len = *(u64 *)src_area;
  874. count_size = sizeof(u64);
  875. BUILD_BUG_ON(!is_power_of_2(KCOV_WORDS_PER_CMP));
  876. entry_size_log = __ilog2_u64(sizeof(u64) * KCOV_WORDS_PER_CMP);
  877. break;
  878. default:
  879. WARN_ON(1);
  880. return;
  881. }
  882. /* As arm can't divide u64 integers use log of entry size. */
  883. if (dst_len > ((dst_area_size * word_size - count_size) >>
  884. entry_size_log))
  885. return;
  886. dst_occupied = count_size + (dst_len << entry_size_log);
  887. dst_free = dst_area_size * word_size - dst_occupied;
  888. bytes_to_move = min(dst_free, src_len << entry_size_log);
  889. dst_entries = dst_area + dst_occupied;
  890. src_entries = src_area + count_size;
  891. memcpy(dst_entries, src_entries, bytes_to_move);
  892. entries_moved = bytes_to_move >> entry_size_log;
  893. switch (mode) {
  894. case KCOV_MODE_TRACE_PC:
  895. WRITE_ONCE(*(unsigned long *)dst_area, dst_len + entries_moved);
  896. break;
  897. case KCOV_MODE_TRACE_CMP:
  898. WRITE_ONCE(*(u64 *)dst_area, dst_len + entries_moved);
  899. break;
  900. default:
  901. break;
  902. }
  903. }
  904. /* See the comment before kcov_remote_start() for usage details. */
  905. void kcov_remote_stop(void)
  906. {
  907. struct task_struct *t = current;
  908. struct kcov *kcov;
  909. unsigned int mode;
  910. void *area;
  911. unsigned int size;
  912. int sequence;
  913. unsigned long flags;
  914. if (!in_task() && !in_softirq_really())
  915. return;
  916. local_lock_irqsave(&kcov_percpu_data.lock, flags);
  917. mode = READ_ONCE(t->kcov_mode);
  918. barrier();
  919. if (!kcov_mode_enabled(mode)) {
  920. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  921. return;
  922. }
  923. /*
  924. * When in softirq, check if the corresponding kcov_remote_start()
  925. * actually found the remote handle and started collecting coverage.
  926. */
  927. if (in_serving_softirq() && !t->kcov_softirq) {
  928. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  929. return;
  930. }
  931. /* Make sure that kcov_softirq is only set when in softirq. */
  932. if (WARN_ON(!in_serving_softirq() && t->kcov_softirq)) {
  933. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  934. return;
  935. }
  936. kcov = t->kcov;
  937. area = t->kcov_area;
  938. size = t->kcov_size;
  939. sequence = t->kcov_sequence;
  940. kcov_stop(t);
  941. if (in_serving_softirq()) {
  942. t->kcov_softirq = 0;
  943. kcov_remote_softirq_stop(t);
  944. }
  945. spin_lock(&kcov->lock);
  946. /*
  947. * KCOV_DISABLE could have been called between kcov_remote_start()
  948. * and kcov_remote_stop(), hence the sequence check.
  949. */
  950. if (sequence == kcov->sequence && kcov->remote)
  951. kcov_move_area(kcov->mode, kcov->area, kcov->size, area);
  952. spin_unlock(&kcov->lock);
  953. if (in_task()) {
  954. spin_lock(&kcov_remote_lock);
  955. kcov_remote_area_put(area, size);
  956. spin_unlock(&kcov_remote_lock);
  957. }
  958. local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
  959. /* Get in kcov_remote_start(). */
  960. kcov_put(kcov);
  961. }
  962. EXPORT_SYMBOL(kcov_remote_stop);
  963. /* See the comment before kcov_remote_start() for usage details. */
  964. u64 kcov_common_handle(void)
  965. {
  966. if (!in_task())
  967. return 0;
  968. return current->kcov_handle;
  969. }
  970. EXPORT_SYMBOL(kcov_common_handle);
  971. #ifdef CONFIG_KCOV_SELFTEST
  972. static void __init selftest(void)
  973. {
  974. unsigned long start;
  975. pr_err("running self test\n");
  976. /*
  977. * Test that interrupts don't produce spurious coverage.
  978. * The coverage callback filters out interrupt code, but only
  979. * after the handler updates preempt count. Some code periodically
  980. * leaks out of that section and leads to spurious coverage.
  981. * It's hard to call the actual interrupt handler directly,
  982. * so we just loop here for a bit waiting for a timer interrupt.
  983. * We set kcov_mode to enable tracing, but don't setup the area,
  984. * so any attempt to trace will crash. Note: we must not call any
  985. * potentially traced functions in this region.
  986. */
  987. start = jiffies;
  988. current->kcov_mode = KCOV_MODE_TRACE_PC;
  989. while ((jiffies - start) * MSEC_PER_SEC / HZ < 300)
  990. ;
  991. current->kcov_mode = 0;
  992. pr_err("done running self test\n");
  993. }
  994. #endif
  995. static int __init kcov_init(void)
  996. {
  997. int cpu;
  998. for_each_possible_cpu(cpu) {
  999. void *area = vmalloc_node(CONFIG_KCOV_IRQ_AREA_SIZE *
  1000. sizeof(unsigned long), cpu_to_node(cpu));
  1001. if (!area)
  1002. return -ENOMEM;
  1003. per_cpu_ptr(&kcov_percpu_data, cpu)->irq_area = area;
  1004. }
  1005. /*
  1006. * The kcov debugfs file won't ever get removed and thus,
  1007. * there is no need to protect it against removal races. The
  1008. * use of debugfs_create_file_unsafe() is actually safe here.
  1009. */
  1010. debugfs_create_file_unsafe("kcov", 0600, NULL, NULL, &kcov_fops);
  1011. #ifdef CONFIG_KCOV_SELFTEST
  1012. selftest();
  1013. #endif
  1014. return 0;
  1015. }
  1016. device_initcall(kcov_init);