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