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