• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2020 ARM Ltd.
4  */
5 
6 #include <linux/bitops.h>
7 #include <linux/cpu.h>
8 #include <linux/kernel.h>
9 #include <linux/mm.h>
10 #include <linux/prctl.h>
11 #include <linux/sched.h>
12 #include <linux/sched/mm.h>
13 #include <linux/string.h>
14 #include <linux/swap.h>
15 #include <linux/swapops.h>
16 #include <linux/thread_info.h>
17 #include <linux/types.h>
18 #include <linux/uio.h>
19 
20 #include <asm/barrier.h>
21 #include <asm/cpufeature.h>
22 #include <asm/mte.h>
23 #include <asm/ptrace.h>
24 #include <asm/sysreg.h>
25 
26 static DEFINE_PER_CPU_READ_MOSTLY(u64, mte_tcf_preferred);
27 
28 #ifdef CONFIG_KASAN_HW_TAGS
29 /*
30  * The asynchronous and asymmetric MTE modes have the same behavior for
31  * store operations. This flag is set when either of these modes is enabled.
32  */
33 DEFINE_STATIC_KEY_FALSE(mte_async_or_asymm_mode);
34 EXPORT_SYMBOL_GPL(mte_async_or_asymm_mode);
35 #endif
36 
mte_sync_page_tags(struct page * page,pte_t old_pte,bool check_swap,bool pte_is_tagged)37 static void mte_sync_page_tags(struct page *page, pte_t old_pte,
38 			       bool check_swap, bool pte_is_tagged)
39 {
40 	if (check_swap && is_swap_pte(old_pte)) {
41 		swp_entry_t entry = pte_to_swp_entry(old_pte);
42 
43 		if (!non_swap_entry(entry) && mte_restore_tags(entry, page))
44 			return;
45 	}
46 
47 	if (!pte_is_tagged)
48 		return;
49 
50 	page_kasan_tag_reset(page);
51 	/*
52 	 * We need smp_wmb() in between setting the flags and clearing the
53 	 * tags because if another thread reads page->flags and builds a
54 	 * tagged address out of it, there is an actual dependency to the
55 	 * memory access, but on the current thread we do not guarantee that
56 	 * the new page->flags are visible before the tags were updated.
57 	 */
58 	smp_wmb();
59 	/*
60 	 * Test PG_mte_tagged again in case it was racing with another
61 	 * set_pte_at().
62 	 */
63 	if (!test_and_set_bit(PG_mte_tagged, &page->flags))
64 		mte_clear_page_tags(page_address(page));
65 }
66 
mte_sync_tags(pte_t old_pte,pte_t pte)67 void mte_sync_tags(pte_t old_pte, pte_t pte)
68 {
69 	struct page *page = pte_page(pte);
70 	long i, nr_pages = compound_nr(page);
71 	bool check_swap = nr_pages == 1;
72 	bool pte_is_tagged = pte_tagged(pte);
73 
74 	/* Early out if there's nothing to do */
75 	if (!check_swap && !pte_is_tagged)
76 		return;
77 
78 	/* if PG_mte_tagged is set, tags have already been initialised */
79 	for (i = 0; i < nr_pages; i++, page++) {
80 		if (!test_bit(PG_mte_tagged, &page->flags))
81 			mte_sync_page_tags(page, old_pte, check_swap,
82 					   pte_is_tagged);
83 	}
84 
85 	/* ensure the tags are visible before the PTE is set */
86 	smp_wmb();
87 }
88 
memcmp_pages(struct page * page1,struct page * page2)89 int memcmp_pages(struct page *page1, struct page *page2)
90 {
91 	char *addr1, *addr2;
92 	int ret;
93 
94 	addr1 = page_address(page1);
95 	addr2 = page_address(page2);
96 	ret = memcmp(addr1, addr2, PAGE_SIZE);
97 
98 	if (!system_supports_mte() || ret)
99 		return ret;
100 
101 	/*
102 	 * If the page content is identical but at least one of the pages is
103 	 * tagged, return non-zero to avoid KSM merging. If only one of the
104 	 * pages is tagged, set_pte_at() may zero or change the tags of the
105 	 * other page via mte_sync_tags().
106 	 */
107 	if (test_bit(PG_mte_tagged, &page1->flags) ||
108 	    test_bit(PG_mte_tagged, &page2->flags))
109 		return addr1 != addr2;
110 
111 	return ret;
112 }
113 
__mte_enable_kernel(const char * mode,unsigned long tcf)114 static inline void __mte_enable_kernel(const char *mode, unsigned long tcf)
115 {
116 	/* Enable MTE Sync Mode for EL1. */
117 	sysreg_clear_set(sctlr_el1, SCTLR_ELx_TCF_MASK, tcf);
118 	isb();
119 
120 	pr_info_once("MTE: enabled in %s mode at EL1\n", mode);
121 }
122 
123 #ifdef CONFIG_KASAN_HW_TAGS
mte_enable_kernel_sync(void)124 void mte_enable_kernel_sync(void)
125 {
126 	/*
127 	 * Make sure we enter this function when no PE has set
128 	 * async mode previously.
129 	 */
130 	WARN_ONCE(system_uses_mte_async_or_asymm_mode(),
131 			"MTE async mode enabled system wide!");
132 
133 	__mte_enable_kernel("synchronous", SCTLR_ELx_TCF_SYNC);
134 }
135 
mte_enable_kernel_async(void)136 void mte_enable_kernel_async(void)
137 {
138 	__mte_enable_kernel("asynchronous", SCTLR_ELx_TCF_ASYNC);
139 
140 	/*
141 	 * MTE async mode is set system wide by the first PE that
142 	 * executes this function.
143 	 *
144 	 * Note: If in future KASAN acquires a runtime switching
145 	 * mode in between sync and async, this strategy needs
146 	 * to be reviewed.
147 	 */
148 	if (!system_uses_mte_async_or_asymm_mode())
149 		static_branch_enable(&mte_async_or_asymm_mode);
150 }
151 
mte_enable_kernel_asymm(void)152 void mte_enable_kernel_asymm(void)
153 {
154 	if (cpus_have_cap(ARM64_MTE_ASYMM)) {
155 		__mte_enable_kernel("asymmetric", SCTLR_ELx_TCF_ASYMM);
156 
157 		/*
158 		 * MTE asymm mode behaves as async mode for store
159 		 * operations. The mode is set system wide by the
160 		 * first PE that executes this function.
161 		 *
162 		 * Note: If in future KASAN acquires a runtime switching
163 		 * mode in between sync and async, this strategy needs
164 		 * to be reviewed.
165 		 */
166 		if (!system_uses_mte_async_or_asymm_mode())
167 			static_branch_enable(&mte_async_or_asymm_mode);
168 	} else {
169 		/*
170 		 * If the CPU does not support MTE asymmetric mode the
171 		 * kernel falls back on synchronous mode which is the
172 		 * default for kasan=on.
173 		 */
174 		mte_enable_kernel_sync();
175 	}
176 }
177 #endif
178 
179 #ifdef CONFIG_KASAN_HW_TAGS
mte_check_tfsr_el1(void)180 void mte_check_tfsr_el1(void)
181 {
182 	u64 tfsr_el1 = read_sysreg_s(SYS_TFSR_EL1);
183 
184 	if (unlikely(tfsr_el1 & SYS_TFSR_EL1_TF1)) {
185 		/*
186 		 * Note: isb() is not required after this direct write
187 		 * because there is no indirect read subsequent to it
188 		 * (per ARM DDI 0487F.c table D13-1).
189 		 */
190 		write_sysreg_s(0, SYS_TFSR_EL1);
191 
192 		kasan_report_async();
193 	}
194 }
195 #endif
196 
197 /*
198  * This is where we actually resolve the system and process MTE mode
199  * configuration into an actual value in SCTLR_EL1 that affects
200  * userspace.
201  */
mte_update_sctlr_user(struct task_struct * task)202 static void mte_update_sctlr_user(struct task_struct *task)
203 {
204 	/*
205 	 * This must be called with preemption disabled and can only be called
206 	 * on the current or next task since the CPU must match where the thread
207 	 * is going to run. The caller is responsible for calling
208 	 * update_sctlr_el1() later in the same preemption disabled block.
209 	 */
210 	unsigned long sctlr = task->thread.sctlr_user;
211 	unsigned long mte_ctrl = task->thread.mte_ctrl;
212 	unsigned long pref, resolved_mte_tcf;
213 
214 	pref = __this_cpu_read(mte_tcf_preferred);
215 	/*
216 	 * If there is no overlap between the system preferred and
217 	 * program requested values go with what was requested.
218 	 */
219 	resolved_mte_tcf = (mte_ctrl & pref) ? pref : mte_ctrl;
220 	sctlr &= ~SCTLR_EL1_TCF0_MASK;
221 	/*
222 	 * Pick an actual setting. The order in which we check for
223 	 * set bits and map into register values determines our
224 	 * default order.
225 	 */
226 	if (resolved_mte_tcf & MTE_CTRL_TCF_ASYMM)
227 		sctlr |= SCTLR_EL1_TCF0_ASYMM;
228 	else if (resolved_mte_tcf & MTE_CTRL_TCF_ASYNC)
229 		sctlr |= SCTLR_EL1_TCF0_ASYNC;
230 	else if (resolved_mte_tcf & MTE_CTRL_TCF_SYNC)
231 		sctlr |= SCTLR_EL1_TCF0_SYNC;
232 	task->thread.sctlr_user = sctlr;
233 }
234 
mte_update_gcr_excl(struct task_struct * task)235 static void mte_update_gcr_excl(struct task_struct *task)
236 {
237 	/*
238 	 * SYS_GCR_EL1 will be set to current->thread.mte_ctrl value by
239 	 * mte_set_user_gcr() in kernel_exit, but only if KASAN is enabled.
240 	 */
241 	if (kasan_hw_tags_enabled())
242 		return;
243 
244 	write_sysreg_s(
245 		((task->thread.mte_ctrl >> MTE_CTRL_GCR_USER_EXCL_SHIFT) &
246 		 SYS_GCR_EL1_EXCL_MASK) | SYS_GCR_EL1_RRND,
247 		SYS_GCR_EL1);
248 }
249 
kasan_hw_tags_enable(struct alt_instr * alt,__le32 * origptr,__le32 * updptr,int nr_inst)250 void __init kasan_hw_tags_enable(struct alt_instr *alt, __le32 *origptr,
251 				 __le32 *updptr, int nr_inst)
252 {
253 	BUG_ON(nr_inst != 1); /* Branch -> NOP */
254 
255 	if (kasan_hw_tags_enabled())
256 		*updptr = cpu_to_le32(aarch64_insn_gen_nop());
257 }
258 
mte_thread_init_user(void)259 void mte_thread_init_user(void)
260 {
261 	if (!system_supports_mte())
262 		return;
263 
264 	/* clear any pending asynchronous tag fault */
265 	dsb(ish);
266 	write_sysreg_s(0, SYS_TFSRE0_EL1);
267 	clear_thread_flag(TIF_MTE_ASYNC_FAULT);
268 	/* disable tag checking and reset tag generation mask */
269 	set_mte_ctrl(current, 0);
270 }
271 
mte_thread_switch(struct task_struct * next)272 void mte_thread_switch(struct task_struct *next)
273 {
274 	if (!system_supports_mte())
275 		return;
276 
277 	mte_update_sctlr_user(next);
278 	mte_update_gcr_excl(next);
279 
280 	/*
281 	 * Check if an async tag exception occurred at EL1.
282 	 *
283 	 * Note: On the context switch path we rely on the dsb() present
284 	 * in __switch_to() to guarantee that the indirect writes to TFSR_EL1
285 	 * are synchronized before this point.
286 	 */
287 	isb();
288 	mte_check_tfsr_el1();
289 }
290 
mte_cpu_setup(void)291 void mte_cpu_setup(void)
292 {
293 	u64 rgsr;
294 
295 	/*
296 	 * CnP must be enabled only after the MAIR_EL1 register has been set
297 	 * up. Inconsistent MAIR_EL1 between CPUs sharing the same TLB may
298 	 * lead to the wrong memory type being used for a brief window during
299 	 * CPU power-up.
300 	 *
301 	 * CnP is not a boot feature so MTE gets enabled before CnP, but let's
302 	 * make sure that is the case.
303 	 */
304 	BUG_ON(read_sysreg(ttbr0_el1) & TTBR_CNP_BIT);
305 	BUG_ON(read_sysreg(ttbr1_el1) & TTBR_CNP_BIT);
306 
307 	/* Normal Tagged memory type at the corresponding MAIR index */
308 	sysreg_clear_set(mair_el1,
309 			 MAIR_ATTRIDX(MAIR_ATTR_MASK, MT_NORMAL_TAGGED),
310 			 MAIR_ATTRIDX(MAIR_ATTR_NORMAL_TAGGED,
311 				      MT_NORMAL_TAGGED));
312 
313 	write_sysreg_s(KERNEL_GCR_EL1, SYS_GCR_EL1);
314 
315 	/*
316 	 * If GCR_EL1.RRND=1 is implemented the same way as RRND=0, then
317 	 * RGSR_EL1.SEED must be non-zero for IRG to produce
318 	 * pseudorandom numbers. As RGSR_EL1 is UNKNOWN out of reset, we
319 	 * must initialize it.
320 	 */
321 	rgsr = (read_sysreg(CNTVCT_EL0) & SYS_RGSR_EL1_SEED_MASK) <<
322 	       SYS_RGSR_EL1_SEED_SHIFT;
323 	if (rgsr == 0)
324 		rgsr = 1 << SYS_RGSR_EL1_SEED_SHIFT;
325 	write_sysreg_s(rgsr, SYS_RGSR_EL1);
326 
327 	/* clear any pending tag check faults in TFSR*_EL1 */
328 	write_sysreg_s(0, SYS_TFSR_EL1);
329 	write_sysreg_s(0, SYS_TFSRE0_EL1);
330 
331 	local_flush_tlb_all();
332 }
333 
mte_suspend_enter(void)334 void mte_suspend_enter(void)
335 {
336 	if (!system_supports_mte())
337 		return;
338 
339 	/*
340 	 * The barriers are required to guarantee that the indirect writes
341 	 * to TFSR_EL1 are synchronized before we report the state.
342 	 */
343 	dsb(nsh);
344 	isb();
345 
346 	/* Report SYS_TFSR_EL1 before suspend entry */
347 	mte_check_tfsr_el1();
348 }
349 
mte_suspend_exit(void)350 void mte_suspend_exit(void)
351 {
352 	if (!system_supports_mte())
353 		return;
354 
355 	mte_cpu_setup();
356 }
357 
set_mte_ctrl(struct task_struct * task,unsigned long arg)358 long set_mte_ctrl(struct task_struct *task, unsigned long arg)
359 {
360 	u64 mte_ctrl = (~((arg & PR_MTE_TAG_MASK) >> PR_MTE_TAG_SHIFT) &
361 			SYS_GCR_EL1_EXCL_MASK) << MTE_CTRL_GCR_USER_EXCL_SHIFT;
362 
363 	if (!system_supports_mte())
364 		return 0;
365 
366 	if (arg & PR_MTE_TCF_ASYNC)
367 		mte_ctrl |= MTE_CTRL_TCF_ASYNC;
368 	if (arg & PR_MTE_TCF_SYNC)
369 		mte_ctrl |= MTE_CTRL_TCF_SYNC;
370 
371 	/*
372 	 * If the system supports it and both sync and async modes are
373 	 * specified then implicitly enable asymmetric mode.
374 	 * Userspace could see a mix of both sync and async anyway due
375 	 * to differing or changing defaults on CPUs.
376 	 */
377 	if (cpus_have_cap(ARM64_MTE_ASYMM) &&
378 	    (arg & PR_MTE_TCF_ASYNC) &&
379 	    (arg & PR_MTE_TCF_SYNC))
380 		mte_ctrl |= MTE_CTRL_TCF_ASYMM;
381 
382 	task->thread.mte_ctrl = mte_ctrl;
383 	if (task == current) {
384 		preempt_disable();
385 		mte_update_sctlr_user(task);
386 		mte_update_gcr_excl(task);
387 		update_sctlr_el1(task->thread.sctlr_user);
388 		preempt_enable();
389 	}
390 
391 	return 0;
392 }
393 
get_mte_ctrl(struct task_struct * task)394 long get_mte_ctrl(struct task_struct *task)
395 {
396 	unsigned long ret;
397 	u64 mte_ctrl = task->thread.mte_ctrl;
398 	u64 incl = (~mte_ctrl >> MTE_CTRL_GCR_USER_EXCL_SHIFT) &
399 		   SYS_GCR_EL1_EXCL_MASK;
400 
401 	if (!system_supports_mte())
402 		return 0;
403 
404 	ret = incl << PR_MTE_TAG_SHIFT;
405 	if (mte_ctrl & MTE_CTRL_TCF_ASYNC)
406 		ret |= PR_MTE_TCF_ASYNC;
407 	if (mte_ctrl & MTE_CTRL_TCF_SYNC)
408 		ret |= PR_MTE_TCF_SYNC;
409 
410 	return ret;
411 }
412 
413 /*
414  * Access MTE tags in another process' address space as given in mm. Update
415  * the number of tags copied. Return 0 if any tags copied, error otherwise.
416  * Inspired by __access_remote_vm().
417  */
__access_remote_tags(struct mm_struct * mm,unsigned long addr,struct iovec * kiov,unsigned int gup_flags)418 static int __access_remote_tags(struct mm_struct *mm, unsigned long addr,
419 				struct iovec *kiov, unsigned int gup_flags)
420 {
421 	struct vm_area_struct *vma;
422 	void __user *buf = kiov->iov_base;
423 	size_t len = kiov->iov_len;
424 	int ret;
425 	int write = gup_flags & FOLL_WRITE;
426 
427 	if (!access_ok(buf, len))
428 		return -EFAULT;
429 
430 	if (mmap_read_lock_killable(mm))
431 		return -EIO;
432 
433 	while (len) {
434 		unsigned long tags, offset;
435 		void *maddr;
436 		struct page *page = NULL;
437 
438 		ret = get_user_pages_remote(mm, addr, 1, gup_flags, &page,
439 					    &vma, NULL);
440 		if (ret <= 0)
441 			break;
442 
443 		/*
444 		 * Only copy tags if the page has been mapped as PROT_MTE
445 		 * (PG_mte_tagged set). Otherwise the tags are not valid and
446 		 * not accessible to user. Moreover, an mprotect(PROT_MTE)
447 		 * would cause the existing tags to be cleared if the page
448 		 * was never mapped with PROT_MTE.
449 		 */
450 		if (!(vma->vm_flags & VM_MTE)) {
451 			ret = -EOPNOTSUPP;
452 			put_page(page);
453 			break;
454 		}
455 		WARN_ON_ONCE(!test_bit(PG_mte_tagged, &page->flags));
456 
457 		/* limit access to the end of the page */
458 		offset = offset_in_page(addr);
459 		tags = min(len, (PAGE_SIZE - offset) / MTE_GRANULE_SIZE);
460 
461 		maddr = page_address(page);
462 		if (write) {
463 			tags = mte_copy_tags_from_user(maddr + offset, buf, tags);
464 			set_page_dirty_lock(page);
465 		} else {
466 			tags = mte_copy_tags_to_user(buf, maddr + offset, tags);
467 		}
468 		put_page(page);
469 
470 		/* error accessing the tracer's buffer */
471 		if (!tags)
472 			break;
473 
474 		len -= tags;
475 		buf += tags;
476 		addr += tags * MTE_GRANULE_SIZE;
477 	}
478 	mmap_read_unlock(mm);
479 
480 	/* return an error if no tags copied */
481 	kiov->iov_len = buf - kiov->iov_base;
482 	if (!kiov->iov_len) {
483 		/* check for error accessing the tracee's address space */
484 		if (ret <= 0)
485 			return -EIO;
486 		else
487 			return -EFAULT;
488 	}
489 
490 	return 0;
491 }
492 
493 /*
494  * Copy MTE tags in another process' address space at 'addr' to/from tracer's
495  * iovec buffer. Return 0 on success. Inspired by ptrace_access_vm().
496  */
access_remote_tags(struct task_struct * tsk,unsigned long addr,struct iovec * kiov,unsigned int gup_flags)497 static int access_remote_tags(struct task_struct *tsk, unsigned long addr,
498 			      struct iovec *kiov, unsigned int gup_flags)
499 {
500 	struct mm_struct *mm;
501 	int ret;
502 
503 	mm = get_task_mm(tsk);
504 	if (!mm)
505 		return -EPERM;
506 
507 	if (!tsk->ptrace || (current != tsk->parent) ||
508 	    ((get_dumpable(mm) != SUID_DUMP_USER) &&
509 	     !ptracer_capable(tsk, mm->user_ns))) {
510 		mmput(mm);
511 		return -EPERM;
512 	}
513 
514 	ret = __access_remote_tags(mm, addr, kiov, gup_flags);
515 	mmput(mm);
516 
517 	return ret;
518 }
519 
mte_ptrace_copy_tags(struct task_struct * child,long request,unsigned long addr,unsigned long data)520 int mte_ptrace_copy_tags(struct task_struct *child, long request,
521 			 unsigned long addr, unsigned long data)
522 {
523 	int ret;
524 	struct iovec kiov;
525 	struct iovec __user *uiov = (void __user *)data;
526 	unsigned int gup_flags = FOLL_FORCE;
527 
528 	if (!system_supports_mte())
529 		return -EIO;
530 
531 	if (get_user(kiov.iov_base, &uiov->iov_base) ||
532 	    get_user(kiov.iov_len, &uiov->iov_len))
533 		return -EFAULT;
534 
535 	if (request == PTRACE_POKEMTETAGS)
536 		gup_flags |= FOLL_WRITE;
537 
538 	/* align addr to the MTE tag granule */
539 	addr &= MTE_GRANULE_MASK;
540 
541 	ret = access_remote_tags(child, addr, &kiov, gup_flags);
542 	if (!ret)
543 		ret = put_user(kiov.iov_len, &uiov->iov_len);
544 
545 	return ret;
546 }
547 
mte_tcf_preferred_show(struct device * dev,struct device_attribute * attr,char * buf)548 static ssize_t mte_tcf_preferred_show(struct device *dev,
549 				      struct device_attribute *attr, char *buf)
550 {
551 	switch (per_cpu(mte_tcf_preferred, dev->id)) {
552 	case MTE_CTRL_TCF_ASYNC:
553 		return sysfs_emit(buf, "async\n");
554 	case MTE_CTRL_TCF_SYNC:
555 		return sysfs_emit(buf, "sync\n");
556 	case MTE_CTRL_TCF_ASYMM:
557 		return sysfs_emit(buf, "asymm\n");
558 	default:
559 		return sysfs_emit(buf, "???\n");
560 	}
561 }
562 
mte_tcf_preferred_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)563 static ssize_t mte_tcf_preferred_store(struct device *dev,
564 				       struct device_attribute *attr,
565 				       const char *buf, size_t count)
566 {
567 	u64 tcf;
568 
569 	if (sysfs_streq(buf, "async"))
570 		tcf = MTE_CTRL_TCF_ASYNC;
571 	else if (sysfs_streq(buf, "sync"))
572 		tcf = MTE_CTRL_TCF_SYNC;
573 	else if (cpus_have_cap(ARM64_MTE_ASYMM) && sysfs_streq(buf, "asymm"))
574 		tcf = MTE_CTRL_TCF_ASYMM;
575 	else
576 		return -EINVAL;
577 
578 	device_lock(dev);
579 	per_cpu(mte_tcf_preferred, dev->id) = tcf;
580 	device_unlock(dev);
581 
582 	return count;
583 }
584 static DEVICE_ATTR_RW(mte_tcf_preferred);
585 
register_mte_tcf_preferred_sysctl(void)586 static int register_mte_tcf_preferred_sysctl(void)
587 {
588 	unsigned int cpu;
589 
590 	if (!system_supports_mte())
591 		return 0;
592 
593 	for_each_possible_cpu(cpu) {
594 		per_cpu(mte_tcf_preferred, cpu) = MTE_CTRL_TCF_ASYNC;
595 		device_create_file(get_cpu_device(cpu),
596 				   &dev_attr_mte_tcf_preferred);
597 	}
598 
599 	return 0;
600 }
601 subsys_initcall(register_mte_tcf_preferred_sysctl);
602