xref: /openbmc/linux/arch/arm64/kernel/mte.c (revision 0a94608f)
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 
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 	mte_clear_page_tags(page_address(page));
60 }
61 
62 void mte_sync_tags(pte_t old_pte, pte_t pte)
63 {
64 	struct page *page = pte_page(pte);
65 	long i, nr_pages = compound_nr(page);
66 	bool check_swap = nr_pages == 1;
67 	bool pte_is_tagged = pte_tagged(pte);
68 
69 	/* Early out if there's nothing to do */
70 	if (!check_swap && !pte_is_tagged)
71 		return;
72 
73 	/* if PG_mte_tagged is set, tags have already been initialised */
74 	for (i = 0; i < nr_pages; i++, page++) {
75 		if (!test_and_set_bit(PG_mte_tagged, &page->flags))
76 			mte_sync_page_tags(page, old_pte, check_swap,
77 					   pte_is_tagged);
78 	}
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 (test_bit(PG_mte_tagged, &page1->flags) ||
100 	    test_bit(PG_mte_tagged, &page2->flags))
101 		return addr1 != addr2;
102 
103 	return ret;
104 }
105 
106 static inline void __mte_enable_kernel(const char *mode, unsigned long tcf)
107 {
108 	/* Enable MTE Sync Mode for EL1. */
109 	sysreg_clear_set(sctlr_el1, SCTLR_ELx_TCF_MASK, 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_ELx_TCF_SYNC);
126 }
127 
128 void mte_enable_kernel_async(void)
129 {
130 	__mte_enable_kernel("asynchronous", SCTLR_ELx_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_ELx_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 |= SCTLR_EL1_TCF0_ASYMM;
220 	else if (resolved_mte_tcf & MTE_CTRL_TCF_ASYNC)
221 		sctlr |= SCTLR_EL1_TCF0_ASYNC;
222 	else if (resolved_mte_tcf & MTE_CTRL_TCF_SYNC)
223 		sctlr |= 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 void __init kasan_hw_tags_enable(struct alt_instr *alt, __le32 *origptr,
243 				 __le32 *updptr, int nr_inst)
244 {
245 	BUG_ON(nr_inst != 1); /* Branch -> NOP */
246 
247 	if (kasan_hw_tags_enabled())
248 		*updptr = cpu_to_le32(aarch64_insn_gen_nop());
249 }
250 
251 void mte_thread_init_user(void)
252 {
253 	if (!system_supports_mte())
254 		return;
255 
256 	/* clear any pending asynchronous tag fault */
257 	dsb(ish);
258 	write_sysreg_s(0, SYS_TFSRE0_EL1);
259 	clear_thread_flag(TIF_MTE_ASYNC_FAULT);
260 	/* disable tag checking and reset tag generation mask */
261 	set_mte_ctrl(current, 0);
262 }
263 
264 void mte_thread_switch(struct task_struct *next)
265 {
266 	if (!system_supports_mte())
267 		return;
268 
269 	mte_update_sctlr_user(next);
270 	mte_update_gcr_excl(next);
271 
272 	/* TCO may not have been disabled on exception entry for the current task. */
273 	mte_disable_tco_entry(next);
274 
275 	/*
276 	 * Check if an async tag exception occurred at EL1.
277 	 *
278 	 * Note: On the context switch path we rely on the dsb() present
279 	 * in __switch_to() to guarantee that the indirect writes to TFSR_EL1
280 	 * are synchronized before this point.
281 	 */
282 	isb();
283 	mte_check_tfsr_el1();
284 }
285 
286 void mte_suspend_enter(void)
287 {
288 	if (!system_supports_mte())
289 		return;
290 
291 	/*
292 	 * The barriers are required to guarantee that the indirect writes
293 	 * to TFSR_EL1 are synchronized before we report the state.
294 	 */
295 	dsb(nsh);
296 	isb();
297 
298 	/* Report SYS_TFSR_EL1 before suspend entry */
299 	mte_check_tfsr_el1();
300 }
301 
302 long set_mte_ctrl(struct task_struct *task, unsigned long arg)
303 {
304 	u64 mte_ctrl = (~((arg & PR_MTE_TAG_MASK) >> PR_MTE_TAG_SHIFT) &
305 			SYS_GCR_EL1_EXCL_MASK) << MTE_CTRL_GCR_USER_EXCL_SHIFT;
306 
307 	if (!system_supports_mte())
308 		return 0;
309 
310 	if (arg & PR_MTE_TCF_ASYNC)
311 		mte_ctrl |= MTE_CTRL_TCF_ASYNC;
312 	if (arg & PR_MTE_TCF_SYNC)
313 		mte_ctrl |= MTE_CTRL_TCF_SYNC;
314 
315 	/*
316 	 * If the system supports it and both sync and async modes are
317 	 * specified then implicitly enable asymmetric mode.
318 	 * Userspace could see a mix of both sync and async anyway due
319 	 * to differing or changing defaults on CPUs.
320 	 */
321 	if (cpus_have_cap(ARM64_MTE_ASYMM) &&
322 	    (arg & PR_MTE_TCF_ASYNC) &&
323 	    (arg & PR_MTE_TCF_SYNC))
324 		mte_ctrl |= MTE_CTRL_TCF_ASYMM;
325 
326 	task->thread.mte_ctrl = mte_ctrl;
327 	if (task == current) {
328 		preempt_disable();
329 		mte_update_sctlr_user(task);
330 		mte_update_gcr_excl(task);
331 		update_sctlr_el1(task->thread.sctlr_user);
332 		preempt_enable();
333 	}
334 
335 	return 0;
336 }
337 
338 long get_mte_ctrl(struct task_struct *task)
339 {
340 	unsigned long ret;
341 	u64 mte_ctrl = task->thread.mte_ctrl;
342 	u64 incl = (~mte_ctrl >> MTE_CTRL_GCR_USER_EXCL_SHIFT) &
343 		   SYS_GCR_EL1_EXCL_MASK;
344 
345 	if (!system_supports_mte())
346 		return 0;
347 
348 	ret = incl << PR_MTE_TAG_SHIFT;
349 	if (mte_ctrl & MTE_CTRL_TCF_ASYNC)
350 		ret |= PR_MTE_TCF_ASYNC;
351 	if (mte_ctrl & MTE_CTRL_TCF_SYNC)
352 		ret |= PR_MTE_TCF_SYNC;
353 
354 	return ret;
355 }
356 
357 /*
358  * Access MTE tags in another process' address space as given in mm. Update
359  * the number of tags copied. Return 0 if any tags copied, error otherwise.
360  * Inspired by __access_remote_vm().
361  */
362 static int __access_remote_tags(struct mm_struct *mm, unsigned long addr,
363 				struct iovec *kiov, unsigned int gup_flags)
364 {
365 	struct vm_area_struct *vma;
366 	void __user *buf = kiov->iov_base;
367 	size_t len = kiov->iov_len;
368 	int ret;
369 	int write = gup_flags & FOLL_WRITE;
370 
371 	if (!access_ok(buf, len))
372 		return -EFAULT;
373 
374 	if (mmap_read_lock_killable(mm))
375 		return -EIO;
376 
377 	while (len) {
378 		unsigned long tags, offset;
379 		void *maddr;
380 		struct page *page = NULL;
381 
382 		ret = get_user_pages_remote(mm, addr, 1, gup_flags, &page,
383 					    &vma, NULL);
384 		if (ret <= 0)
385 			break;
386 
387 		/*
388 		 * Only copy tags if the page has been mapped as PROT_MTE
389 		 * (PG_mte_tagged set). Otherwise the tags are not valid and
390 		 * not accessible to user. Moreover, an mprotect(PROT_MTE)
391 		 * would cause the existing tags to be cleared if the page
392 		 * was never mapped with PROT_MTE.
393 		 */
394 		if (!(vma->vm_flags & VM_MTE)) {
395 			ret = -EOPNOTSUPP;
396 			put_page(page);
397 			break;
398 		}
399 		WARN_ON_ONCE(!test_bit(PG_mte_tagged, &page->flags));
400 
401 		/* limit access to the end of the page */
402 		offset = offset_in_page(addr);
403 		tags = min(len, (PAGE_SIZE - offset) / MTE_GRANULE_SIZE);
404 
405 		maddr = page_address(page);
406 		if (write) {
407 			tags = mte_copy_tags_from_user(maddr + offset, buf, tags);
408 			set_page_dirty_lock(page);
409 		} else {
410 			tags = mte_copy_tags_to_user(buf, maddr + offset, tags);
411 		}
412 		put_page(page);
413 
414 		/* error accessing the tracer's buffer */
415 		if (!tags)
416 			break;
417 
418 		len -= tags;
419 		buf += tags;
420 		addr += tags * MTE_GRANULE_SIZE;
421 	}
422 	mmap_read_unlock(mm);
423 
424 	/* return an error if no tags copied */
425 	kiov->iov_len = buf - kiov->iov_base;
426 	if (!kiov->iov_len) {
427 		/* check for error accessing the tracee's address space */
428 		if (ret <= 0)
429 			return -EIO;
430 		else
431 			return -EFAULT;
432 	}
433 
434 	return 0;
435 }
436 
437 /*
438  * Copy MTE tags in another process' address space at 'addr' to/from tracer's
439  * iovec buffer. Return 0 on success. Inspired by ptrace_access_vm().
440  */
441 static int access_remote_tags(struct task_struct *tsk, unsigned long addr,
442 			      struct iovec *kiov, unsigned int gup_flags)
443 {
444 	struct mm_struct *mm;
445 	int ret;
446 
447 	mm = get_task_mm(tsk);
448 	if (!mm)
449 		return -EPERM;
450 
451 	if (!tsk->ptrace || (current != tsk->parent) ||
452 	    ((get_dumpable(mm) != SUID_DUMP_USER) &&
453 	     !ptracer_capable(tsk, mm->user_ns))) {
454 		mmput(mm);
455 		return -EPERM;
456 	}
457 
458 	ret = __access_remote_tags(mm, addr, kiov, gup_flags);
459 	mmput(mm);
460 
461 	return ret;
462 }
463 
464 int mte_ptrace_copy_tags(struct task_struct *child, long request,
465 			 unsigned long addr, unsigned long data)
466 {
467 	int ret;
468 	struct iovec kiov;
469 	struct iovec __user *uiov = (void __user *)data;
470 	unsigned int gup_flags = FOLL_FORCE;
471 
472 	if (!system_supports_mte())
473 		return -EIO;
474 
475 	if (get_user(kiov.iov_base, &uiov->iov_base) ||
476 	    get_user(kiov.iov_len, &uiov->iov_len))
477 		return -EFAULT;
478 
479 	if (request == PTRACE_POKEMTETAGS)
480 		gup_flags |= FOLL_WRITE;
481 
482 	/* align addr to the MTE tag granule */
483 	addr &= MTE_GRANULE_MASK;
484 
485 	ret = access_remote_tags(child, addr, &kiov, gup_flags);
486 	if (!ret)
487 		ret = put_user(kiov.iov_len, &uiov->iov_len);
488 
489 	return ret;
490 }
491 
492 static ssize_t mte_tcf_preferred_show(struct device *dev,
493 				      struct device_attribute *attr, char *buf)
494 {
495 	switch (per_cpu(mte_tcf_preferred, dev->id)) {
496 	case MTE_CTRL_TCF_ASYNC:
497 		return sysfs_emit(buf, "async\n");
498 	case MTE_CTRL_TCF_SYNC:
499 		return sysfs_emit(buf, "sync\n");
500 	case MTE_CTRL_TCF_ASYMM:
501 		return sysfs_emit(buf, "asymm\n");
502 	default:
503 		return sysfs_emit(buf, "???\n");
504 	}
505 }
506 
507 static ssize_t mte_tcf_preferred_store(struct device *dev,
508 				       struct device_attribute *attr,
509 				       const char *buf, size_t count)
510 {
511 	u64 tcf;
512 
513 	if (sysfs_streq(buf, "async"))
514 		tcf = MTE_CTRL_TCF_ASYNC;
515 	else if (sysfs_streq(buf, "sync"))
516 		tcf = MTE_CTRL_TCF_SYNC;
517 	else if (cpus_have_cap(ARM64_MTE_ASYMM) && sysfs_streq(buf, "asymm"))
518 		tcf = MTE_CTRL_TCF_ASYMM;
519 	else
520 		return -EINVAL;
521 
522 	device_lock(dev);
523 	per_cpu(mte_tcf_preferred, dev->id) = tcf;
524 	device_unlock(dev);
525 
526 	return count;
527 }
528 static DEVICE_ATTR_RW(mte_tcf_preferred);
529 
530 static int register_mte_tcf_preferred_sysctl(void)
531 {
532 	unsigned int cpu;
533 
534 	if (!system_supports_mte())
535 		return 0;
536 
537 	for_each_possible_cpu(cpu) {
538 		per_cpu(mte_tcf_preferred, cpu) = MTE_CTRL_TCF_ASYNC;
539 		device_create_file(get_cpu_device(cpu),
540 				   &dev_attr_mte_tcf_preferred);
541 	}
542 
543 	return 0;
544 }
545 subsys_initcall(register_mte_tcf_preferred_sysctl);
546