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