xref: /linux-6.15/arch/arm64/kernel/mte.c (revision e5af50a5)
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 /* Whether the MTE asynchronous mode is enabled. */
30 DEFINE_STATIC_KEY_FALSE(mte_async_mode);
31 EXPORT_SYMBOL_GPL(mte_async_mode);
32 #endif
33 
34 static void mte_sync_page_tags(struct page *page, pte_t old_pte,
35 			       bool check_swap, bool pte_is_tagged)
36 {
37 	if (check_swap && is_swap_pte(old_pte)) {
38 		swp_entry_t entry = pte_to_swp_entry(old_pte);
39 
40 		if (!non_swap_entry(entry) && mte_restore_tags(entry, page))
41 			return;
42 	}
43 
44 	if (!pte_is_tagged)
45 		return;
46 
47 	page_kasan_tag_reset(page);
48 	/*
49 	 * We need smp_wmb() in between setting the flags and clearing the
50 	 * tags because if another thread reads page->flags and builds a
51 	 * tagged address out of it, there is an actual dependency to the
52 	 * memory access, but on the current thread we do not guarantee that
53 	 * the new page->flags are visible before the tags were updated.
54 	 */
55 	smp_wmb();
56 	mte_clear_page_tags(page_address(page));
57 }
58 
59 void mte_sync_tags(pte_t old_pte, pte_t pte)
60 {
61 	struct page *page = pte_page(pte);
62 	long i, nr_pages = compound_nr(page);
63 	bool check_swap = nr_pages == 1;
64 	bool pte_is_tagged = pte_tagged(pte);
65 
66 	/* Early out if there's nothing to do */
67 	if (!check_swap && !pte_is_tagged)
68 		return;
69 
70 	/* if PG_mte_tagged is set, tags have already been initialised */
71 	for (i = 0; i < nr_pages; i++, page++) {
72 		if (!test_and_set_bit(PG_mte_tagged, &page->flags))
73 			mte_sync_page_tags(page, old_pte, check_swap,
74 					   pte_is_tagged);
75 	}
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 (test_bit(PG_mte_tagged, &page1->flags) ||
97 	    test_bit(PG_mte_tagged, &page2->flags))
98 		return addr1 != addr2;
99 
100 	return ret;
101 }
102 
103 static inline void __mte_enable_kernel(const char *mode, unsigned long tcf)
104 {
105 	/* Enable MTE Sync Mode for EL1. */
106 	sysreg_clear_set(sctlr_el1, SCTLR_ELx_TCF_MASK, 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_mode(),
120 			"MTE async mode enabled system wide!");
121 
122 	__mte_enable_kernel("synchronous", SCTLR_ELx_TCF_SYNC);
123 }
124 
125 void mte_enable_kernel_async(void)
126 {
127 	__mte_enable_kernel("asynchronous", SCTLR_ELx_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_mode())
138 		static_branch_enable(&mte_async_mode);
139 }
140 #endif
141 
142 #ifdef CONFIG_KASAN_HW_TAGS
143 void mte_check_tfsr_el1(void)
144 {
145 	u64 tfsr_el1 = read_sysreg_s(SYS_TFSR_EL1);
146 
147 	if (unlikely(tfsr_el1 & SYS_TFSR_EL1_TF1)) {
148 		/*
149 		 * Note: isb() is not required after this direct write
150 		 * because there is no indirect read subsequent to it
151 		 * (per ARM DDI 0487F.c table D13-1).
152 		 */
153 		write_sysreg_s(0, SYS_TFSR_EL1);
154 
155 		kasan_report_async();
156 	}
157 }
158 #endif
159 
160 static void mte_update_sctlr_user(struct task_struct *task)
161 {
162 	/*
163 	 * This must be called with preemption disabled and can only be called
164 	 * on the current or next task since the CPU must match where the thread
165 	 * is going to run. The caller is responsible for calling
166 	 * update_sctlr_el1() later in the same preemption disabled block.
167 	 */
168 	unsigned long sctlr = task->thread.sctlr_user;
169 	unsigned long mte_ctrl = task->thread.mte_ctrl;
170 	unsigned long pref, resolved_mte_tcf;
171 
172 	pref = __this_cpu_read(mte_tcf_preferred);
173 	resolved_mte_tcf = (mte_ctrl & pref) ? pref : mte_ctrl;
174 	sctlr &= ~SCTLR_EL1_TCF0_MASK;
175 	if (resolved_mte_tcf & MTE_CTRL_TCF_ASYNC)
176 		sctlr |= SCTLR_EL1_TCF0_ASYNC;
177 	else if (resolved_mte_tcf & MTE_CTRL_TCF_SYNC)
178 		sctlr |= SCTLR_EL1_TCF0_SYNC;
179 	task->thread.sctlr_user = sctlr;
180 }
181 
182 static void mte_update_gcr_excl(struct task_struct *task)
183 {
184 	/*
185 	 * SYS_GCR_EL1 will be set to current->thread.mte_ctrl value by
186 	 * mte_set_user_gcr() in kernel_exit, but only if KASAN is enabled.
187 	 */
188 	if (kasan_hw_tags_enabled())
189 		return;
190 
191 	write_sysreg_s(
192 		((task->thread.mte_ctrl >> MTE_CTRL_GCR_USER_EXCL_SHIFT) &
193 		 SYS_GCR_EL1_EXCL_MASK) | SYS_GCR_EL1_RRND,
194 		SYS_GCR_EL1);
195 }
196 
197 void __init kasan_hw_tags_enable(struct alt_instr *alt, __le32 *origptr,
198 				 __le32 *updptr, int nr_inst)
199 {
200 	BUG_ON(nr_inst != 1); /* Branch -> NOP */
201 
202 	if (kasan_hw_tags_enabled())
203 		*updptr = cpu_to_le32(aarch64_insn_gen_nop());
204 }
205 
206 void mte_thread_init_user(void)
207 {
208 	if (!system_supports_mte())
209 		return;
210 
211 	/* clear any pending asynchronous tag fault */
212 	dsb(ish);
213 	write_sysreg_s(0, SYS_TFSRE0_EL1);
214 	clear_thread_flag(TIF_MTE_ASYNC_FAULT);
215 	/* disable tag checking and reset tag generation mask */
216 	set_mte_ctrl(current, 0);
217 }
218 
219 void mte_thread_switch(struct task_struct *next)
220 {
221 	if (!system_supports_mte())
222 		return;
223 
224 	mte_update_sctlr_user(next);
225 	mte_update_gcr_excl(next);
226 
227 	/*
228 	 * Check if an async tag exception occurred at EL1.
229 	 *
230 	 * Note: On the context switch path we rely on the dsb() present
231 	 * in __switch_to() to guarantee that the indirect writes to TFSR_EL1
232 	 * are synchronized before this point.
233 	 */
234 	isb();
235 	mte_check_tfsr_el1();
236 }
237 
238 void mte_suspend_enter(void)
239 {
240 	if (!system_supports_mte())
241 		return;
242 
243 	/*
244 	 * The barriers are required to guarantee that the indirect writes
245 	 * to TFSR_EL1 are synchronized before we report the state.
246 	 */
247 	dsb(nsh);
248 	isb();
249 
250 	/* Report SYS_TFSR_EL1 before suspend entry */
251 	mte_check_tfsr_el1();
252 }
253 
254 long set_mte_ctrl(struct task_struct *task, unsigned long arg)
255 {
256 	u64 mte_ctrl = (~((arg & PR_MTE_TAG_MASK) >> PR_MTE_TAG_SHIFT) &
257 			SYS_GCR_EL1_EXCL_MASK) << MTE_CTRL_GCR_USER_EXCL_SHIFT;
258 
259 	if (!system_supports_mte())
260 		return 0;
261 
262 	if (arg & PR_MTE_TCF_ASYNC)
263 		mte_ctrl |= MTE_CTRL_TCF_ASYNC;
264 	if (arg & PR_MTE_TCF_SYNC)
265 		mte_ctrl |= MTE_CTRL_TCF_SYNC;
266 
267 	task->thread.mte_ctrl = mte_ctrl;
268 	if (task == current) {
269 		preempt_disable();
270 		mte_update_sctlr_user(task);
271 		mte_update_gcr_excl(task);
272 		update_sctlr_el1(task->thread.sctlr_user);
273 		preempt_enable();
274 	}
275 
276 	return 0;
277 }
278 
279 long get_mte_ctrl(struct task_struct *task)
280 {
281 	unsigned long ret;
282 	u64 mte_ctrl = task->thread.mte_ctrl;
283 	u64 incl = (~mte_ctrl >> MTE_CTRL_GCR_USER_EXCL_SHIFT) &
284 		   SYS_GCR_EL1_EXCL_MASK;
285 
286 	if (!system_supports_mte())
287 		return 0;
288 
289 	ret = incl << PR_MTE_TAG_SHIFT;
290 	if (mte_ctrl & MTE_CTRL_TCF_ASYNC)
291 		ret |= PR_MTE_TCF_ASYNC;
292 	if (mte_ctrl & MTE_CTRL_TCF_SYNC)
293 		ret |= PR_MTE_TCF_SYNC;
294 
295 	return ret;
296 }
297 
298 /*
299  * Access MTE tags in another process' address space as given in mm. Update
300  * the number of tags copied. Return 0 if any tags copied, error otherwise.
301  * Inspired by __access_remote_vm().
302  */
303 static int __access_remote_tags(struct mm_struct *mm, unsigned long addr,
304 				struct iovec *kiov, unsigned int gup_flags)
305 {
306 	struct vm_area_struct *vma;
307 	void __user *buf = kiov->iov_base;
308 	size_t len = kiov->iov_len;
309 	int ret;
310 	int write = gup_flags & FOLL_WRITE;
311 
312 	if (!access_ok(buf, len))
313 		return -EFAULT;
314 
315 	if (mmap_read_lock_killable(mm))
316 		return -EIO;
317 
318 	while (len) {
319 		unsigned long tags, offset;
320 		void *maddr;
321 		struct page *page = NULL;
322 
323 		ret = get_user_pages_remote(mm, addr, 1, gup_flags, &page,
324 					    &vma, NULL);
325 		if (ret <= 0)
326 			break;
327 
328 		/*
329 		 * Only copy tags if the page has been mapped as PROT_MTE
330 		 * (PG_mte_tagged set). Otherwise the tags are not valid and
331 		 * not accessible to user. Moreover, an mprotect(PROT_MTE)
332 		 * would cause the existing tags to be cleared if the page
333 		 * was never mapped with PROT_MTE.
334 		 */
335 		if (!(vma->vm_flags & VM_MTE)) {
336 			ret = -EOPNOTSUPP;
337 			put_page(page);
338 			break;
339 		}
340 		WARN_ON_ONCE(!test_bit(PG_mte_tagged, &page->flags));
341 
342 		/* limit access to the end of the page */
343 		offset = offset_in_page(addr);
344 		tags = min(len, (PAGE_SIZE - offset) / MTE_GRANULE_SIZE);
345 
346 		maddr = page_address(page);
347 		if (write) {
348 			tags = mte_copy_tags_from_user(maddr + offset, buf, tags);
349 			set_page_dirty_lock(page);
350 		} else {
351 			tags = mte_copy_tags_to_user(buf, maddr + offset, tags);
352 		}
353 		put_page(page);
354 
355 		/* error accessing the tracer's buffer */
356 		if (!tags)
357 			break;
358 
359 		len -= tags;
360 		buf += tags;
361 		addr += tags * MTE_GRANULE_SIZE;
362 	}
363 	mmap_read_unlock(mm);
364 
365 	/* return an error if no tags copied */
366 	kiov->iov_len = buf - kiov->iov_base;
367 	if (!kiov->iov_len) {
368 		/* check for error accessing the tracee's address space */
369 		if (ret <= 0)
370 			return -EIO;
371 		else
372 			return -EFAULT;
373 	}
374 
375 	return 0;
376 }
377 
378 /*
379  * Copy MTE tags in another process' address space at 'addr' to/from tracer's
380  * iovec buffer. Return 0 on success. Inspired by ptrace_access_vm().
381  */
382 static int access_remote_tags(struct task_struct *tsk, unsigned long addr,
383 			      struct iovec *kiov, unsigned int gup_flags)
384 {
385 	struct mm_struct *mm;
386 	int ret;
387 
388 	mm = get_task_mm(tsk);
389 	if (!mm)
390 		return -EPERM;
391 
392 	if (!tsk->ptrace || (current != tsk->parent) ||
393 	    ((get_dumpable(mm) != SUID_DUMP_USER) &&
394 	     !ptracer_capable(tsk, mm->user_ns))) {
395 		mmput(mm);
396 		return -EPERM;
397 	}
398 
399 	ret = __access_remote_tags(mm, addr, kiov, gup_flags);
400 	mmput(mm);
401 
402 	return ret;
403 }
404 
405 int mte_ptrace_copy_tags(struct task_struct *child, long request,
406 			 unsigned long addr, unsigned long data)
407 {
408 	int ret;
409 	struct iovec kiov;
410 	struct iovec __user *uiov = (void __user *)data;
411 	unsigned int gup_flags = FOLL_FORCE;
412 
413 	if (!system_supports_mte())
414 		return -EIO;
415 
416 	if (get_user(kiov.iov_base, &uiov->iov_base) ||
417 	    get_user(kiov.iov_len, &uiov->iov_len))
418 		return -EFAULT;
419 
420 	if (request == PTRACE_POKEMTETAGS)
421 		gup_flags |= FOLL_WRITE;
422 
423 	/* align addr to the MTE tag granule */
424 	addr &= MTE_GRANULE_MASK;
425 
426 	ret = access_remote_tags(child, addr, &kiov, gup_flags);
427 	if (!ret)
428 		ret = put_user(kiov.iov_len, &uiov->iov_len);
429 
430 	return ret;
431 }
432 
433 static ssize_t mte_tcf_preferred_show(struct device *dev,
434 				      struct device_attribute *attr, char *buf)
435 {
436 	switch (per_cpu(mte_tcf_preferred, dev->id)) {
437 	case MTE_CTRL_TCF_ASYNC:
438 		return sysfs_emit(buf, "async\n");
439 	case MTE_CTRL_TCF_SYNC:
440 		return sysfs_emit(buf, "sync\n");
441 	default:
442 		return sysfs_emit(buf, "???\n");
443 	}
444 }
445 
446 static ssize_t mte_tcf_preferred_store(struct device *dev,
447 				       struct device_attribute *attr,
448 				       const char *buf, size_t count)
449 {
450 	u64 tcf;
451 
452 	if (sysfs_streq(buf, "async"))
453 		tcf = MTE_CTRL_TCF_ASYNC;
454 	else if (sysfs_streq(buf, "sync"))
455 		tcf = MTE_CTRL_TCF_SYNC;
456 	else
457 		return -EINVAL;
458 
459 	device_lock(dev);
460 	per_cpu(mte_tcf_preferred, dev->id) = tcf;
461 	device_unlock(dev);
462 
463 	return count;
464 }
465 static DEVICE_ATTR_RW(mte_tcf_preferred);
466 
467 static int register_mte_tcf_preferred_sysctl(void)
468 {
469 	unsigned int cpu;
470 
471 	if (!system_supports_mte())
472 		return 0;
473 
474 	for_each_possible_cpu(cpu) {
475 		per_cpu(mte_tcf_preferred, cpu) = MTE_CTRL_TCF_ASYNC;
476 		device_create_file(get_cpu_device(cpu),
477 				   &dev_attr_mte_tcf_preferred);
478 	}
479 
480 	return 0;
481 }
482 subsys_initcall(register_mte_tcf_preferred_sysctl);
483