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