xref: /openbmc/linux/arch/arm64/kernel/fpsimd.c (revision 51d11ea0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * FP/SIMD context switching and fault handling
4  *
5  * Copyright (C) 2012 ARM Ltd.
6  * Author: Catalin Marinas <catalin.marinas@arm.com>
7  */
8 
9 #include <linux/bitmap.h>
10 #include <linux/bitops.h>
11 #include <linux/bottom_half.h>
12 #include <linux/bug.h>
13 #include <linux/cache.h>
14 #include <linux/compat.h>
15 #include <linux/compiler.h>
16 #include <linux/cpu.h>
17 #include <linux/cpu_pm.h>
18 #include <linux/ctype.h>
19 #include <linux/kernel.h>
20 #include <linux/linkage.h>
21 #include <linux/irqflags.h>
22 #include <linux/init.h>
23 #include <linux/percpu.h>
24 #include <linux/prctl.h>
25 #include <linux/preempt.h>
26 #include <linux/ptrace.h>
27 #include <linux/sched/signal.h>
28 #include <linux/sched/task_stack.h>
29 #include <linux/signal.h>
30 #include <linux/slab.h>
31 #include <linux/stddef.h>
32 #include <linux/sysctl.h>
33 #include <linux/swab.h>
34 
35 #include <asm/esr.h>
36 #include <asm/exception.h>
37 #include <asm/fpsimd.h>
38 #include <asm/cpufeature.h>
39 #include <asm/cputype.h>
40 #include <asm/neon.h>
41 #include <asm/processor.h>
42 #include <asm/simd.h>
43 #include <asm/sigcontext.h>
44 #include <asm/sysreg.h>
45 #include <asm/traps.h>
46 #include <asm/virt.h>
47 
48 #define FPEXC_IOF	(1 << 0)
49 #define FPEXC_DZF	(1 << 1)
50 #define FPEXC_OFF	(1 << 2)
51 #define FPEXC_UFF	(1 << 3)
52 #define FPEXC_IXF	(1 << 4)
53 #define FPEXC_IDF	(1 << 7)
54 
55 /*
56  * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
57  *
58  * In order to reduce the number of times the FPSIMD state is needlessly saved
59  * and restored, we need to keep track of two things:
60  * (a) for each task, we need to remember which CPU was the last one to have
61  *     the task's FPSIMD state loaded into its FPSIMD registers;
62  * (b) for each CPU, we need to remember which task's userland FPSIMD state has
63  *     been loaded into its FPSIMD registers most recently, or whether it has
64  *     been used to perform kernel mode NEON in the meantime.
65  *
66  * For (a), we add a fpsimd_cpu field to thread_struct, which gets updated to
67  * the id of the current CPU every time the state is loaded onto a CPU. For (b),
68  * we add the per-cpu variable 'fpsimd_last_state' (below), which contains the
69  * address of the userland FPSIMD state of the task that was loaded onto the CPU
70  * the most recently, or NULL if kernel mode NEON has been performed after that.
71  *
72  * With this in place, we no longer have to restore the next FPSIMD state right
73  * when switching between tasks. Instead, we can defer this check to userland
74  * resume, at which time we verify whether the CPU's fpsimd_last_state and the
75  * task's fpsimd_cpu are still mutually in sync. If this is the case, we
76  * can omit the FPSIMD restore.
77  *
78  * As an optimization, we use the thread_info flag TIF_FOREIGN_FPSTATE to
79  * indicate whether or not the userland FPSIMD state of the current task is
80  * present in the registers. The flag is set unless the FPSIMD registers of this
81  * CPU currently contain the most recent userland FPSIMD state of the current
82  * task. If the task is behaving as a VMM, then this is will be managed by
83  * KVM which will clear it to indicate that the vcpu FPSIMD state is currently
84  * loaded on the CPU, allowing the state to be saved if a FPSIMD-aware
85  * softirq kicks in. Upon vcpu_put(), KVM will save the vcpu FP state and
86  * flag the register state as invalid.
87  *
88  * In order to allow softirq handlers to use FPSIMD, kernel_neon_begin() may
89  * save the task's FPSIMD context back to task_struct from softirq context.
90  * To prevent this from racing with the manipulation of the task's FPSIMD state
91  * from task context and thereby corrupting the state, it is necessary to
92  * protect any manipulation of a task's fpsimd_state or TIF_FOREIGN_FPSTATE
93  * flag with {, __}get_cpu_fpsimd_context(). This will still allow softirqs to
94  * run but prevent them to use FPSIMD.
95  *
96  * For a certain task, the sequence may look something like this:
97  * - the task gets scheduled in; if both the task's fpsimd_cpu field
98  *   contains the id of the current CPU, and the CPU's fpsimd_last_state per-cpu
99  *   variable points to the task's fpsimd_state, the TIF_FOREIGN_FPSTATE flag is
100  *   cleared, otherwise it is set;
101  *
102  * - the task returns to userland; if TIF_FOREIGN_FPSTATE is set, the task's
103  *   userland FPSIMD state is copied from memory to the registers, the task's
104  *   fpsimd_cpu field is set to the id of the current CPU, the current
105  *   CPU's fpsimd_last_state pointer is set to this task's fpsimd_state and the
106  *   TIF_FOREIGN_FPSTATE flag is cleared;
107  *
108  * - the task executes an ordinary syscall; upon return to userland, the
109  *   TIF_FOREIGN_FPSTATE flag will still be cleared, so no FPSIMD state is
110  *   restored;
111  *
112  * - the task executes a syscall which executes some NEON instructions; this is
113  *   preceded by a call to kernel_neon_begin(), which copies the task's FPSIMD
114  *   register contents to memory, clears the fpsimd_last_state per-cpu variable
115  *   and sets the TIF_FOREIGN_FPSTATE flag;
116  *
117  * - the task gets preempted after kernel_neon_end() is called; as we have not
118  *   returned from the 2nd syscall yet, TIF_FOREIGN_FPSTATE is still set so
119  *   whatever is in the FPSIMD registers is not saved to memory, but discarded.
120  */
121 
122 static DEFINE_PER_CPU(struct cpu_fp_state, fpsimd_last_state);
123 
124 __ro_after_init struct vl_info vl_info[ARM64_VEC_MAX] = {
125 #ifdef CONFIG_ARM64_SVE
126 	[ARM64_VEC_SVE] = {
127 		.type			= ARM64_VEC_SVE,
128 		.name			= "SVE",
129 		.min_vl			= SVE_VL_MIN,
130 		.max_vl			= SVE_VL_MIN,
131 		.max_virtualisable_vl	= SVE_VL_MIN,
132 	},
133 #endif
134 #ifdef CONFIG_ARM64_SME
135 	[ARM64_VEC_SME] = {
136 		.type			= ARM64_VEC_SME,
137 		.name			= "SME",
138 	},
139 #endif
140 };
141 
vec_vl_inherit_flag(enum vec_type type)142 static unsigned int vec_vl_inherit_flag(enum vec_type type)
143 {
144 	switch (type) {
145 	case ARM64_VEC_SVE:
146 		return TIF_SVE_VL_INHERIT;
147 	case ARM64_VEC_SME:
148 		return TIF_SME_VL_INHERIT;
149 	default:
150 		WARN_ON_ONCE(1);
151 		return 0;
152 	}
153 }
154 
155 struct vl_config {
156 	int __default_vl;		/* Default VL for tasks */
157 };
158 
159 static struct vl_config vl_config[ARM64_VEC_MAX];
160 
get_default_vl(enum vec_type type)161 static inline int get_default_vl(enum vec_type type)
162 {
163 	return READ_ONCE(vl_config[type].__default_vl);
164 }
165 
166 #ifdef CONFIG_ARM64_SVE
167 
get_sve_default_vl(void)168 static inline int get_sve_default_vl(void)
169 {
170 	return get_default_vl(ARM64_VEC_SVE);
171 }
172 
set_default_vl(enum vec_type type,int val)173 static inline void set_default_vl(enum vec_type type, int val)
174 {
175 	WRITE_ONCE(vl_config[type].__default_vl, val);
176 }
177 
set_sve_default_vl(int val)178 static inline void set_sve_default_vl(int val)
179 {
180 	set_default_vl(ARM64_VEC_SVE, val);
181 }
182 
183 static void __percpu *efi_sve_state;
184 
185 #else /* ! CONFIG_ARM64_SVE */
186 
187 /* Dummy declaration for code that will be optimised out: */
188 extern void __percpu *efi_sve_state;
189 
190 #endif /* ! CONFIG_ARM64_SVE */
191 
192 #ifdef CONFIG_ARM64_SME
193 
get_sme_default_vl(void)194 static int get_sme_default_vl(void)
195 {
196 	return get_default_vl(ARM64_VEC_SME);
197 }
198 
set_sme_default_vl(int val)199 static void set_sme_default_vl(int val)
200 {
201 	set_default_vl(ARM64_VEC_SME, val);
202 }
203 
204 static void sme_free(struct task_struct *);
205 
206 #else
207 
sme_free(struct task_struct * t)208 static inline void sme_free(struct task_struct *t) { }
209 
210 #endif
211 
212 DEFINE_PER_CPU(bool, fpsimd_context_busy);
213 EXPORT_PER_CPU_SYMBOL(fpsimd_context_busy);
214 
215 static void fpsimd_bind_task_to_cpu(void);
216 
__get_cpu_fpsimd_context(void)217 static void __get_cpu_fpsimd_context(void)
218 {
219 	bool busy = __this_cpu_xchg(fpsimd_context_busy, true);
220 
221 	WARN_ON(busy);
222 }
223 
224 /*
225  * Claim ownership of the CPU FPSIMD context for use by the calling context.
226  *
227  * The caller may freely manipulate the FPSIMD context metadata until
228  * put_cpu_fpsimd_context() is called.
229  *
230  * The double-underscore version must only be called if you know the task
231  * can't be preempted.
232  *
233  * On RT kernels local_bh_disable() is not sufficient because it only
234  * serializes soft interrupt related sections via a local lock, but stays
235  * preemptible. Disabling preemption is the right choice here as bottom
236  * half processing is always in thread context on RT kernels so it
237  * implicitly prevents bottom half processing as well.
238  */
get_cpu_fpsimd_context(void)239 static void get_cpu_fpsimd_context(void)
240 {
241 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
242 		local_bh_disable();
243 	else
244 		preempt_disable();
245 	__get_cpu_fpsimd_context();
246 }
247 
__put_cpu_fpsimd_context(void)248 static void __put_cpu_fpsimd_context(void)
249 {
250 	bool busy = __this_cpu_xchg(fpsimd_context_busy, false);
251 
252 	WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */
253 }
254 
255 /*
256  * Release the CPU FPSIMD context.
257  *
258  * Must be called from a context in which get_cpu_fpsimd_context() was
259  * previously called, with no call to put_cpu_fpsimd_context() in the
260  * meantime.
261  */
put_cpu_fpsimd_context(void)262 static void put_cpu_fpsimd_context(void)
263 {
264 	__put_cpu_fpsimd_context();
265 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
266 		local_bh_enable();
267 	else
268 		preempt_enable();
269 }
270 
have_cpu_fpsimd_context(void)271 static bool have_cpu_fpsimd_context(void)
272 {
273 	return !preemptible() && __this_cpu_read(fpsimd_context_busy);
274 }
275 
task_get_vl(const struct task_struct * task,enum vec_type type)276 unsigned int task_get_vl(const struct task_struct *task, enum vec_type type)
277 {
278 	return task->thread.vl[type];
279 }
280 
task_set_vl(struct task_struct * task,enum vec_type type,unsigned long vl)281 void task_set_vl(struct task_struct *task, enum vec_type type,
282 		 unsigned long vl)
283 {
284 	task->thread.vl[type] = vl;
285 }
286 
task_get_vl_onexec(const struct task_struct * task,enum vec_type type)287 unsigned int task_get_vl_onexec(const struct task_struct *task,
288 				enum vec_type type)
289 {
290 	return task->thread.vl_onexec[type];
291 }
292 
task_set_vl_onexec(struct task_struct * task,enum vec_type type,unsigned long vl)293 void task_set_vl_onexec(struct task_struct *task, enum vec_type type,
294 			unsigned long vl)
295 {
296 	task->thread.vl_onexec[type] = vl;
297 }
298 
299 /*
300  * TIF_SME controls whether a task can use SME without trapping while
301  * in userspace, when TIF_SME is set then we must have storage
302  * allocated in sve_state and sme_state to store the contents of both ZA
303  * and the SVE registers for both streaming and non-streaming modes.
304  *
305  * If both SVCR.ZA and SVCR.SM are disabled then at any point we
306  * may disable TIF_SME and reenable traps.
307  */
308 
309 
310 /*
311  * TIF_SVE controls whether a task can use SVE without trapping while
312  * in userspace, and also (together with TIF_SME) the way a task's
313  * FPSIMD/SVE state is stored in thread_struct.
314  *
315  * The kernel uses this flag to track whether a user task is actively
316  * using SVE, and therefore whether full SVE register state needs to
317  * be tracked.  If not, the cheaper FPSIMD context handling code can
318  * be used instead of the more costly SVE equivalents.
319  *
320  *  * TIF_SVE or SVCR.SM set:
321  *
322  *    The task can execute SVE instructions while in userspace without
323  *    trapping to the kernel.
324  *
325  *    During any syscall, the kernel may optionally clear TIF_SVE and
326  *    discard the vector state except for the FPSIMD subset.
327  *
328  *  * TIF_SVE clear:
329  *
330  *    An attempt by the user task to execute an SVE instruction causes
331  *    do_sve_acc() to be called, which does some preparation and then
332  *    sets TIF_SVE.
333  *
334  * During any syscall, the kernel may optionally clear TIF_SVE and
335  * discard the vector state except for the FPSIMD subset.
336  *
337  * The data will be stored in one of two formats:
338  *
339  *  * FPSIMD only - FP_STATE_FPSIMD:
340  *
341  *    When the FPSIMD only state stored task->thread.fp_type is set to
342  *    FP_STATE_FPSIMD, the FPSIMD registers V0-V31 are encoded in
343  *    task->thread.uw.fpsimd_state; bits [max : 128] for each of Z0-Z31 are
344  *    logically zero but not stored anywhere; P0-P15 and FFR are not
345  *    stored and have unspecified values from userspace's point of
346  *    view.  For hygiene purposes, the kernel zeroes them on next use,
347  *    but userspace is discouraged from relying on this.
348  *
349  *    task->thread.sve_state does not need to be non-NULL, valid or any
350  *    particular size: it must not be dereferenced and any data stored
351  *    there should be considered stale and not referenced.
352  *
353  *  * SVE state - FP_STATE_SVE:
354  *
355  *    When the full SVE state is stored task->thread.fp_type is set to
356  *    FP_STATE_SVE and Z0-Z31 (incorporating Vn in bits[127:0] or the
357  *    corresponding Zn), P0-P15 and FFR are encoded in in
358  *    task->thread.sve_state, formatted appropriately for vector
359  *    length task->thread.sve_vl or, if SVCR.SM is set,
360  *    task->thread.sme_vl. The storage for the vector registers in
361  *    task->thread.uw.fpsimd_state should be ignored.
362  *
363  *    task->thread.sve_state must point to a valid buffer at least
364  *    sve_state_size(task) bytes in size. The data stored in
365  *    task->thread.uw.fpsimd_state.vregs should be considered stale
366  *    and not referenced.
367  *
368  *  * FPSR and FPCR are always stored in task->thread.uw.fpsimd_state
369  *    irrespective of whether TIF_SVE is clear or set, since these are
370  *    not vector length dependent.
371  */
372 
373 /*
374  * Update current's FPSIMD/SVE registers from thread_struct.
375  *
376  * This function should be called only when the FPSIMD/SVE state in
377  * thread_struct is known to be up to date, when preparing to enter
378  * userspace.
379  */
task_fpsimd_load(void)380 static void task_fpsimd_load(void)
381 {
382 	bool restore_sve_regs = false;
383 	bool restore_ffr;
384 
385 	WARN_ON(!system_supports_fpsimd());
386 	WARN_ON(!have_cpu_fpsimd_context());
387 
388 	if (system_supports_sve() || system_supports_sme()) {
389 		switch (current->thread.fp_type) {
390 		case FP_STATE_FPSIMD:
391 			/* Stop tracking SVE for this task until next use. */
392 			if (test_and_clear_thread_flag(TIF_SVE))
393 				sve_user_disable();
394 			break;
395 		case FP_STATE_SVE:
396 			if (!thread_sm_enabled(&current->thread) &&
397 			    !WARN_ON_ONCE(!test_and_set_thread_flag(TIF_SVE)))
398 				sve_user_enable();
399 
400 			if (test_thread_flag(TIF_SVE))
401 				sve_set_vq(sve_vq_from_vl(task_get_sve_vl(current)) - 1);
402 
403 			restore_sve_regs = true;
404 			restore_ffr = true;
405 			break;
406 		default:
407 			/*
408 			 * This indicates either a bug in
409 			 * fpsimd_save() or memory corruption, we
410 			 * should always record an explicit format
411 			 * when we save. We always at least have the
412 			 * memory allocated for FPSMID registers so
413 			 * try that and hope for the best.
414 			 */
415 			WARN_ON_ONCE(1);
416 			clear_thread_flag(TIF_SVE);
417 			break;
418 		}
419 	}
420 
421 	/* Restore SME, override SVE register configuration if needed */
422 	if (system_supports_sme()) {
423 		unsigned long sme_vl = task_get_sme_vl(current);
424 
425 		/* Ensure VL is set up for restoring data */
426 		if (test_thread_flag(TIF_SME))
427 			sme_set_vq(sve_vq_from_vl(sme_vl) - 1);
428 
429 		write_sysreg_s(current->thread.svcr, SYS_SVCR);
430 
431 		if (thread_za_enabled(&current->thread))
432 			sme_load_state(current->thread.sme_state,
433 				       system_supports_sme2());
434 
435 		if (thread_sm_enabled(&current->thread))
436 			restore_ffr = system_supports_fa64();
437 	}
438 
439 	if (restore_sve_regs) {
440 		WARN_ON_ONCE(current->thread.fp_type != FP_STATE_SVE);
441 		sve_load_state(sve_pffr(&current->thread),
442 			       &current->thread.uw.fpsimd_state.fpsr,
443 			       restore_ffr);
444 	} else {
445 		WARN_ON_ONCE(current->thread.fp_type != FP_STATE_FPSIMD);
446 		fpsimd_load_state(&current->thread.uw.fpsimd_state);
447 	}
448 }
449 
450 /*
451  * Ensure FPSIMD/SVE storage in memory for the loaded context is up to
452  * date with respect to the CPU registers. Note carefully that the
453  * current context is the context last bound to the CPU stored in
454  * last, if KVM is involved this may be the guest VM context rather
455  * than the host thread for the VM pointed to by current. This means
456  * that we must always reference the state storage via last rather
457  * than via current, if we are saving KVM state then it will have
458  * ensured that the type of registers to save is set in last->to_save.
459  */
fpsimd_save(void)460 static void fpsimd_save(void)
461 {
462 	struct cpu_fp_state const *last =
463 		this_cpu_ptr(&fpsimd_last_state);
464 	/* set by fpsimd_bind_task_to_cpu() or fpsimd_bind_state_to_cpu() */
465 	bool save_sve_regs = false;
466 	bool save_ffr;
467 	unsigned int vl;
468 
469 	WARN_ON(!system_supports_fpsimd());
470 	WARN_ON(!have_cpu_fpsimd_context());
471 
472 	if (test_thread_flag(TIF_FOREIGN_FPSTATE))
473 		return;
474 
475 	/*
476 	 * If a task is in a syscall the ABI allows us to only
477 	 * preserve the state shared with FPSIMD so don't bother
478 	 * saving the full SVE state in that case.
479 	 */
480 	if ((last->to_save == FP_STATE_CURRENT && test_thread_flag(TIF_SVE) &&
481 	     !in_syscall(current_pt_regs())) ||
482 	    last->to_save == FP_STATE_SVE) {
483 		save_sve_regs = true;
484 		save_ffr = true;
485 		vl = last->sve_vl;
486 	}
487 
488 	if (system_supports_sme()) {
489 		u64 *svcr = last->svcr;
490 
491 		*svcr = read_sysreg_s(SYS_SVCR);
492 
493 		if (*svcr & SVCR_ZA_MASK)
494 			sme_save_state(last->sme_state,
495 				       system_supports_sme2());
496 
497 		/* If we are in streaming mode override regular SVE. */
498 		if (*svcr & SVCR_SM_MASK) {
499 			save_sve_regs = true;
500 			save_ffr = system_supports_fa64();
501 			vl = last->sme_vl;
502 		}
503 	}
504 
505 	if (IS_ENABLED(CONFIG_ARM64_SVE) && save_sve_regs) {
506 		/* Get the configured VL from RDVL, will account for SM */
507 		if (WARN_ON(sve_get_vl() != vl)) {
508 			/*
509 			 * Can't save the user regs, so current would
510 			 * re-enter user with corrupt state.
511 			 * There's no way to recover, so kill it:
512 			 */
513 			force_signal_inject(SIGKILL, SI_KERNEL, 0, 0);
514 			return;
515 		}
516 
517 		sve_save_state((char *)last->sve_state +
518 					sve_ffr_offset(vl),
519 			       &last->st->fpsr, save_ffr);
520 		*last->fp_type = FP_STATE_SVE;
521 	} else {
522 		fpsimd_save_state(last->st);
523 		*last->fp_type = FP_STATE_FPSIMD;
524 	}
525 }
526 
527 /*
528  * All vector length selection from userspace comes through here.
529  * We're on a slow path, so some sanity-checks are included.
530  * If things go wrong there's a bug somewhere, but try to fall back to a
531  * safe choice.
532  */
find_supported_vector_length(enum vec_type type,unsigned int vl)533 static unsigned int find_supported_vector_length(enum vec_type type,
534 						 unsigned int vl)
535 {
536 	struct vl_info *info = &vl_info[type];
537 	int bit;
538 	int max_vl = info->max_vl;
539 
540 	if (WARN_ON(!sve_vl_valid(vl)))
541 		vl = info->min_vl;
542 
543 	if (WARN_ON(!sve_vl_valid(max_vl)))
544 		max_vl = info->min_vl;
545 
546 	if (vl > max_vl)
547 		vl = max_vl;
548 	if (vl < info->min_vl)
549 		vl = info->min_vl;
550 
551 	bit = find_next_bit(info->vq_map, SVE_VQ_MAX,
552 			    __vq_to_bit(sve_vq_from_vl(vl)));
553 	return sve_vl_from_vq(__bit_to_vq(bit));
554 }
555 
556 #if defined(CONFIG_ARM64_SVE) && defined(CONFIG_SYSCTL)
557 
vec_proc_do_default_vl(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)558 static int vec_proc_do_default_vl(struct ctl_table *table, int write,
559 				  void *buffer, size_t *lenp, loff_t *ppos)
560 {
561 	struct vl_info *info = table->extra1;
562 	enum vec_type type = info->type;
563 	int ret;
564 	int vl = get_default_vl(type);
565 	struct ctl_table tmp_table = {
566 		.data = &vl,
567 		.maxlen = sizeof(vl),
568 	};
569 
570 	ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
571 	if (ret || !write)
572 		return ret;
573 
574 	/* Writing -1 has the special meaning "set to max": */
575 	if (vl == -1)
576 		vl = info->max_vl;
577 
578 	if (!sve_vl_valid(vl))
579 		return -EINVAL;
580 
581 	set_default_vl(type, find_supported_vector_length(type, vl));
582 	return 0;
583 }
584 
585 static struct ctl_table sve_default_vl_table[] = {
586 	{
587 		.procname	= "sve_default_vector_length",
588 		.mode		= 0644,
589 		.proc_handler	= vec_proc_do_default_vl,
590 		.extra1		= &vl_info[ARM64_VEC_SVE],
591 	},
592 	{ }
593 };
594 
sve_sysctl_init(void)595 static int __init sve_sysctl_init(void)
596 {
597 	if (system_supports_sve())
598 		if (!register_sysctl("abi", sve_default_vl_table))
599 			return -EINVAL;
600 
601 	return 0;
602 }
603 
604 #else /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
sve_sysctl_init(void)605 static int __init sve_sysctl_init(void) { return 0; }
606 #endif /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
607 
608 #if defined(CONFIG_ARM64_SME) && defined(CONFIG_SYSCTL)
609 static struct ctl_table sme_default_vl_table[] = {
610 	{
611 		.procname	= "sme_default_vector_length",
612 		.mode		= 0644,
613 		.proc_handler	= vec_proc_do_default_vl,
614 		.extra1		= &vl_info[ARM64_VEC_SME],
615 	},
616 	{ }
617 };
618 
sme_sysctl_init(void)619 static int __init sme_sysctl_init(void)
620 {
621 	if (system_supports_sme())
622 		if (!register_sysctl("abi", sme_default_vl_table))
623 			return -EINVAL;
624 
625 	return 0;
626 }
627 
628 #else /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
sme_sysctl_init(void)629 static int __init sme_sysctl_init(void) { return 0; }
630 #endif /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
631 
632 #define ZREG(sve_state, vq, n) ((char *)(sve_state) +		\
633 	(SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
634 
635 #ifdef CONFIG_CPU_BIG_ENDIAN
arm64_cpu_to_le128(__uint128_t x)636 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
637 {
638 	u64 a = swab64(x);
639 	u64 b = swab64(x >> 64);
640 
641 	return ((__uint128_t)a << 64) | b;
642 }
643 #else
arm64_cpu_to_le128(__uint128_t x)644 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
645 {
646 	return x;
647 }
648 #endif
649 
650 #define arm64_le128_to_cpu(x) arm64_cpu_to_le128(x)
651 
__fpsimd_to_sve(void * sst,struct user_fpsimd_state const * fst,unsigned int vq)652 static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst,
653 			    unsigned int vq)
654 {
655 	unsigned int i;
656 	__uint128_t *p;
657 
658 	for (i = 0; i < SVE_NUM_ZREGS; ++i) {
659 		p = (__uint128_t *)ZREG(sst, vq, i);
660 		*p = arm64_cpu_to_le128(fst->vregs[i]);
661 	}
662 }
663 
664 /*
665  * Transfer the FPSIMD state in task->thread.uw.fpsimd_state to
666  * task->thread.sve_state.
667  *
668  * Task can be a non-runnable task, or current.  In the latter case,
669  * the caller must have ownership of the cpu FPSIMD context before calling
670  * this function.
671  * task->thread.sve_state must point to at least sve_state_size(task)
672  * bytes of allocated kernel memory.
673  * task->thread.uw.fpsimd_state must be up to date before calling this
674  * function.
675  */
fpsimd_to_sve(struct task_struct * task)676 static void fpsimd_to_sve(struct task_struct *task)
677 {
678 	unsigned int vq;
679 	void *sst = task->thread.sve_state;
680 	struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
681 
682 	if (!system_supports_sve() && !system_supports_sme())
683 		return;
684 
685 	vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
686 	__fpsimd_to_sve(sst, fst, vq);
687 }
688 
689 /*
690  * Transfer the SVE state in task->thread.sve_state to
691  * task->thread.uw.fpsimd_state.
692  *
693  * Task can be a non-runnable task, or current.  In the latter case,
694  * the caller must have ownership of the cpu FPSIMD context before calling
695  * this function.
696  * task->thread.sve_state must point to at least sve_state_size(task)
697  * bytes of allocated kernel memory.
698  * task->thread.sve_state must be up to date before calling this function.
699  */
sve_to_fpsimd(struct task_struct * task)700 static void sve_to_fpsimd(struct task_struct *task)
701 {
702 	unsigned int vq, vl;
703 	void const *sst = task->thread.sve_state;
704 	struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state;
705 	unsigned int i;
706 	__uint128_t const *p;
707 
708 	if (!system_supports_sve() && !system_supports_sme())
709 		return;
710 
711 	vl = thread_get_cur_vl(&task->thread);
712 	vq = sve_vq_from_vl(vl);
713 	for (i = 0; i < SVE_NUM_ZREGS; ++i) {
714 		p = (__uint128_t const *)ZREG(sst, vq, i);
715 		fst->vregs[i] = arm64_le128_to_cpu(*p);
716 	}
717 }
718 
719 #ifdef CONFIG_ARM64_SVE
720 /*
721  * Call __sve_free() directly only if you know task can't be scheduled
722  * or preempted.
723  */
__sve_free(struct task_struct * task)724 static void __sve_free(struct task_struct *task)
725 {
726 	kfree(task->thread.sve_state);
727 	task->thread.sve_state = NULL;
728 }
729 
sve_free(struct task_struct * task)730 static void sve_free(struct task_struct *task)
731 {
732 	WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
733 
734 	__sve_free(task);
735 }
736 
737 /*
738  * Return how many bytes of memory are required to store the full SVE
739  * state for task, given task's currently configured vector length.
740  */
sve_state_size(struct task_struct const * task)741 size_t sve_state_size(struct task_struct const *task)
742 {
743 	unsigned int vl = 0;
744 
745 	if (system_supports_sve())
746 		vl = task_get_sve_vl(task);
747 	if (system_supports_sme())
748 		vl = max(vl, task_get_sme_vl(task));
749 
750 	return SVE_SIG_REGS_SIZE(sve_vq_from_vl(vl));
751 }
752 
753 /*
754  * Ensure that task->thread.sve_state is allocated and sufficiently large.
755  *
756  * This function should be used only in preparation for replacing
757  * task->thread.sve_state with new data.  The memory is always zeroed
758  * here to prevent stale data from showing through: this is done in
759  * the interest of testability and predictability: except in the
760  * do_sve_acc() case, there is no ABI requirement to hide stale data
761  * written previously be task.
762  */
sve_alloc(struct task_struct * task,bool flush)763 void sve_alloc(struct task_struct *task, bool flush)
764 {
765 	if (task->thread.sve_state) {
766 		if (flush)
767 			memset(task->thread.sve_state, 0,
768 			       sve_state_size(task));
769 		return;
770 	}
771 
772 	/* This is a small allocation (maximum ~8KB) and Should Not Fail. */
773 	task->thread.sve_state =
774 		kzalloc(sve_state_size(task), GFP_KERNEL);
775 }
776 
777 
778 /*
779  * Force the FPSIMD state shared with SVE to be updated in the SVE state
780  * even if the SVE state is the current active state.
781  *
782  * This should only be called by ptrace.  task must be non-runnable.
783  * task->thread.sve_state must point to at least sve_state_size(task)
784  * bytes of allocated kernel memory.
785  */
fpsimd_force_sync_to_sve(struct task_struct * task)786 void fpsimd_force_sync_to_sve(struct task_struct *task)
787 {
788 	fpsimd_to_sve(task);
789 }
790 
791 /*
792  * Ensure that task->thread.sve_state is up to date with respect to
793  * the user task, irrespective of when SVE is in use or not.
794  *
795  * This should only be called by ptrace.  task must be non-runnable.
796  * task->thread.sve_state must point to at least sve_state_size(task)
797  * bytes of allocated kernel memory.
798  */
fpsimd_sync_to_sve(struct task_struct * task)799 void fpsimd_sync_to_sve(struct task_struct *task)
800 {
801 	if (!test_tsk_thread_flag(task, TIF_SVE) &&
802 	    !thread_sm_enabled(&task->thread))
803 		fpsimd_to_sve(task);
804 }
805 
806 /*
807  * Ensure that task->thread.uw.fpsimd_state is up to date with respect to
808  * the user task, irrespective of whether SVE is in use or not.
809  *
810  * This should only be called by ptrace.  task must be non-runnable.
811  * task->thread.sve_state must point to at least sve_state_size(task)
812  * bytes of allocated kernel memory.
813  */
sve_sync_to_fpsimd(struct task_struct * task)814 void sve_sync_to_fpsimd(struct task_struct *task)
815 {
816 	if (task->thread.fp_type == FP_STATE_SVE)
817 		sve_to_fpsimd(task);
818 }
819 
820 /*
821  * Ensure that task->thread.sve_state is up to date with respect to
822  * the task->thread.uw.fpsimd_state.
823  *
824  * This should only be called by ptrace to merge new FPSIMD register
825  * values into a task for which SVE is currently active.
826  * task must be non-runnable.
827  * task->thread.sve_state must point to at least sve_state_size(task)
828  * bytes of allocated kernel memory.
829  * task->thread.uw.fpsimd_state must already have been initialised with
830  * the new FPSIMD register values to be merged in.
831  */
sve_sync_from_fpsimd_zeropad(struct task_struct * task)832 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
833 {
834 	unsigned int vq;
835 	void *sst = task->thread.sve_state;
836 	struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
837 
838 	if (!test_tsk_thread_flag(task, TIF_SVE) &&
839 	    !thread_sm_enabled(&task->thread))
840 		return;
841 
842 	vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
843 
844 	memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
845 	__fpsimd_to_sve(sst, fst, vq);
846 }
847 
vec_set_vector_length(struct task_struct * task,enum vec_type type,unsigned long vl,unsigned long flags)848 int vec_set_vector_length(struct task_struct *task, enum vec_type type,
849 			  unsigned long vl, unsigned long flags)
850 {
851 	bool free_sme = false;
852 
853 	if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
854 				     PR_SVE_SET_VL_ONEXEC))
855 		return -EINVAL;
856 
857 	if (!sve_vl_valid(vl))
858 		return -EINVAL;
859 
860 	/*
861 	 * Clamp to the maximum vector length that VL-agnostic code
862 	 * can work with.  A flag may be assigned in the future to
863 	 * allow setting of larger vector lengths without confusing
864 	 * older software.
865 	 */
866 	if (vl > VL_ARCH_MAX)
867 		vl = VL_ARCH_MAX;
868 
869 	vl = find_supported_vector_length(type, vl);
870 
871 	if (flags & (PR_SVE_VL_INHERIT |
872 		     PR_SVE_SET_VL_ONEXEC))
873 		task_set_vl_onexec(task, type, vl);
874 	else
875 		/* Reset VL to system default on next exec: */
876 		task_set_vl_onexec(task, type, 0);
877 
878 	/* Only actually set the VL if not deferred: */
879 	if (flags & PR_SVE_SET_VL_ONEXEC)
880 		goto out;
881 
882 	if (vl == task_get_vl(task, type))
883 		goto out;
884 
885 	/*
886 	 * To ensure the FPSIMD bits of the SVE vector registers are preserved,
887 	 * write any live register state back to task_struct, and convert to a
888 	 * regular FPSIMD thread.
889 	 */
890 	if (task == current) {
891 		get_cpu_fpsimd_context();
892 
893 		fpsimd_save();
894 	}
895 
896 	fpsimd_flush_task_state(task);
897 	if (test_and_clear_tsk_thread_flag(task, TIF_SVE) ||
898 	    thread_sm_enabled(&task->thread)) {
899 		sve_to_fpsimd(task);
900 		task->thread.fp_type = FP_STATE_FPSIMD;
901 	}
902 
903 	if (system_supports_sme()) {
904 		if (type == ARM64_VEC_SME ||
905 		    !(task->thread.svcr & (SVCR_SM_MASK | SVCR_ZA_MASK))) {
906 			/*
907 			 * We are changing the SME VL or weren't using
908 			 * SME anyway, discard the state and force a
909 			 * reallocation.
910 			 */
911 			task->thread.svcr &= ~(SVCR_SM_MASK |
912 					       SVCR_ZA_MASK);
913 			clear_tsk_thread_flag(task, TIF_SME);
914 			free_sme = true;
915 		}
916 	}
917 
918 	if (task == current)
919 		put_cpu_fpsimd_context();
920 
921 	task_set_vl(task, type, vl);
922 
923 	/*
924 	 * Free the changed states if they are not in use, SME will be
925 	 * reallocated to the correct size on next use and we just
926 	 * allocate SVE now in case it is needed for use in streaming
927 	 * mode.
928 	 */
929 	if (system_supports_sve()) {
930 		sve_free(task);
931 		sve_alloc(task, true);
932 	}
933 
934 	if (free_sme)
935 		sme_free(task);
936 
937 out:
938 	update_tsk_thread_flag(task, vec_vl_inherit_flag(type),
939 			       flags & PR_SVE_VL_INHERIT);
940 
941 	return 0;
942 }
943 
944 /*
945  * Encode the current vector length and flags for return.
946  * This is only required for prctl(): ptrace has separate fields.
947  * SVE and SME use the same bits for _ONEXEC and _INHERIT.
948  *
949  * flags are as for vec_set_vector_length().
950  */
vec_prctl_status(enum vec_type type,unsigned long flags)951 static int vec_prctl_status(enum vec_type type, unsigned long flags)
952 {
953 	int ret;
954 
955 	if (flags & PR_SVE_SET_VL_ONEXEC)
956 		ret = task_get_vl_onexec(current, type);
957 	else
958 		ret = task_get_vl(current, type);
959 
960 	if (test_thread_flag(vec_vl_inherit_flag(type)))
961 		ret |= PR_SVE_VL_INHERIT;
962 
963 	return ret;
964 }
965 
966 /* PR_SVE_SET_VL */
sve_set_current_vl(unsigned long arg)967 int sve_set_current_vl(unsigned long arg)
968 {
969 	unsigned long vl, flags;
970 	int ret;
971 
972 	vl = arg & PR_SVE_VL_LEN_MASK;
973 	flags = arg & ~vl;
974 
975 	if (!system_supports_sve() || is_compat_task())
976 		return -EINVAL;
977 
978 	ret = vec_set_vector_length(current, ARM64_VEC_SVE, vl, flags);
979 	if (ret)
980 		return ret;
981 
982 	return vec_prctl_status(ARM64_VEC_SVE, flags);
983 }
984 
985 /* PR_SVE_GET_VL */
sve_get_current_vl(void)986 int sve_get_current_vl(void)
987 {
988 	if (!system_supports_sve() || is_compat_task())
989 		return -EINVAL;
990 
991 	return vec_prctl_status(ARM64_VEC_SVE, 0);
992 }
993 
994 #ifdef CONFIG_ARM64_SME
995 /* PR_SME_SET_VL */
sme_set_current_vl(unsigned long arg)996 int sme_set_current_vl(unsigned long arg)
997 {
998 	unsigned long vl, flags;
999 	int ret;
1000 
1001 	vl = arg & PR_SME_VL_LEN_MASK;
1002 	flags = arg & ~vl;
1003 
1004 	if (!system_supports_sme() || is_compat_task())
1005 		return -EINVAL;
1006 
1007 	ret = vec_set_vector_length(current, ARM64_VEC_SME, vl, flags);
1008 	if (ret)
1009 		return ret;
1010 
1011 	return vec_prctl_status(ARM64_VEC_SME, flags);
1012 }
1013 
1014 /* PR_SME_GET_VL */
sme_get_current_vl(void)1015 int sme_get_current_vl(void)
1016 {
1017 	if (!system_supports_sme() || is_compat_task())
1018 		return -EINVAL;
1019 
1020 	return vec_prctl_status(ARM64_VEC_SME, 0);
1021 }
1022 #endif /* CONFIG_ARM64_SME */
1023 
vec_probe_vqs(struct vl_info * info,DECLARE_BITMAP (map,SVE_VQ_MAX))1024 static void vec_probe_vqs(struct vl_info *info,
1025 			  DECLARE_BITMAP(map, SVE_VQ_MAX))
1026 {
1027 	unsigned int vq, vl;
1028 
1029 	bitmap_zero(map, SVE_VQ_MAX);
1030 
1031 	for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
1032 		write_vl(info->type, vq - 1); /* self-syncing */
1033 
1034 		switch (info->type) {
1035 		case ARM64_VEC_SVE:
1036 			vl = sve_get_vl();
1037 			break;
1038 		case ARM64_VEC_SME:
1039 			vl = sme_get_vl();
1040 			break;
1041 		default:
1042 			vl = 0;
1043 			break;
1044 		}
1045 
1046 		/* Minimum VL identified? */
1047 		if (sve_vq_from_vl(vl) > vq)
1048 			break;
1049 
1050 		vq = sve_vq_from_vl(vl); /* skip intervening lengths */
1051 		set_bit(__vq_to_bit(vq), map);
1052 	}
1053 }
1054 
1055 /*
1056  * Initialise the set of known supported VQs for the boot CPU.
1057  * This is called during kernel boot, before secondary CPUs are brought up.
1058  */
vec_init_vq_map(enum vec_type type)1059 void __init vec_init_vq_map(enum vec_type type)
1060 {
1061 	struct vl_info *info = &vl_info[type];
1062 	vec_probe_vqs(info, info->vq_map);
1063 	bitmap_copy(info->vq_partial_map, info->vq_map, SVE_VQ_MAX);
1064 }
1065 
1066 /*
1067  * If we haven't committed to the set of supported VQs yet, filter out
1068  * those not supported by the current CPU.
1069  * This function is called during the bring-up of early secondary CPUs only.
1070  */
vec_update_vq_map(enum vec_type type)1071 void vec_update_vq_map(enum vec_type type)
1072 {
1073 	struct vl_info *info = &vl_info[type];
1074 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1075 
1076 	vec_probe_vqs(info, tmp_map);
1077 	bitmap_and(info->vq_map, info->vq_map, tmp_map, SVE_VQ_MAX);
1078 	bitmap_or(info->vq_partial_map, info->vq_partial_map, tmp_map,
1079 		  SVE_VQ_MAX);
1080 }
1081 
1082 /*
1083  * Check whether the current CPU supports all VQs in the committed set.
1084  * This function is called during the bring-up of late secondary CPUs only.
1085  */
vec_verify_vq_map(enum vec_type type)1086 int vec_verify_vq_map(enum vec_type type)
1087 {
1088 	struct vl_info *info = &vl_info[type];
1089 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1090 	unsigned long b;
1091 
1092 	vec_probe_vqs(info, tmp_map);
1093 
1094 	bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1095 	if (bitmap_intersects(tmp_map, info->vq_map, SVE_VQ_MAX)) {
1096 		pr_warn("%s: cpu%d: Required vector length(s) missing\n",
1097 			info->name, smp_processor_id());
1098 		return -EINVAL;
1099 	}
1100 
1101 	if (!IS_ENABLED(CONFIG_KVM) || !is_hyp_mode_available())
1102 		return 0;
1103 
1104 	/*
1105 	 * For KVM, it is necessary to ensure that this CPU doesn't
1106 	 * support any vector length that guests may have probed as
1107 	 * unsupported.
1108 	 */
1109 
1110 	/* Recover the set of supported VQs: */
1111 	bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1112 	/* Find VQs supported that are not globally supported: */
1113 	bitmap_andnot(tmp_map, tmp_map, info->vq_map, SVE_VQ_MAX);
1114 
1115 	/* Find the lowest such VQ, if any: */
1116 	b = find_last_bit(tmp_map, SVE_VQ_MAX);
1117 	if (b >= SVE_VQ_MAX)
1118 		return 0; /* no mismatches */
1119 
1120 	/*
1121 	 * Mismatches above sve_max_virtualisable_vl are fine, since
1122 	 * no guest is allowed to configure ZCR_EL2.LEN to exceed this:
1123 	 */
1124 	if (sve_vl_from_vq(__bit_to_vq(b)) <= info->max_virtualisable_vl) {
1125 		pr_warn("%s: cpu%d: Unsupported vector length(s) present\n",
1126 			info->name, smp_processor_id());
1127 		return -EINVAL;
1128 	}
1129 
1130 	return 0;
1131 }
1132 
sve_efi_setup(void)1133 static void __init sve_efi_setup(void)
1134 {
1135 	int max_vl = 0;
1136 	int i;
1137 
1138 	if (!IS_ENABLED(CONFIG_EFI))
1139 		return;
1140 
1141 	for (i = 0; i < ARRAY_SIZE(vl_info); i++)
1142 		max_vl = max(vl_info[i].max_vl, max_vl);
1143 
1144 	/*
1145 	 * alloc_percpu() warns and prints a backtrace if this goes wrong.
1146 	 * This is evidence of a crippled system and we are returning void,
1147 	 * so no attempt is made to handle this situation here.
1148 	 */
1149 	if (!sve_vl_valid(max_vl))
1150 		goto fail;
1151 
1152 	efi_sve_state = __alloc_percpu(
1153 		SVE_SIG_REGS_SIZE(sve_vq_from_vl(max_vl)), SVE_VQ_BYTES);
1154 	if (!efi_sve_state)
1155 		goto fail;
1156 
1157 	return;
1158 
1159 fail:
1160 	panic("Cannot allocate percpu memory for EFI SVE save/restore");
1161 }
1162 
1163 /*
1164  * Enable SVE for EL1.
1165  * Intended for use by the cpufeatures code during CPU boot.
1166  */
sve_kernel_enable(const struct arm64_cpu_capabilities * __always_unused p)1167 void sve_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1168 {
1169 	write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
1170 	isb();
1171 }
1172 
1173 /*
1174  * Read the pseudo-ZCR used by cpufeatures to identify the supported SVE
1175  * vector length.
1176  *
1177  * Use only if SVE is present.
1178  * This function clobbers the SVE vector length.
1179  */
read_zcr_features(void)1180 u64 read_zcr_features(void)
1181 {
1182 	/*
1183 	 * Set the maximum possible VL, and write zeroes to all other
1184 	 * bits to see if they stick.
1185 	 */
1186 	sve_kernel_enable(NULL);
1187 	write_sysreg_s(ZCR_ELx_LEN_MASK, SYS_ZCR_EL1);
1188 
1189 	/* Return LEN value that would be written to get the maximum VL */
1190 	return sve_vq_from_vl(sve_get_vl()) - 1;
1191 }
1192 
sve_setup(void)1193 void __init sve_setup(void)
1194 {
1195 	struct vl_info *info = &vl_info[ARM64_VEC_SVE];
1196 	u64 zcr;
1197 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1198 	unsigned long b;
1199 
1200 	if (!system_supports_sve())
1201 		return;
1202 
1203 	/*
1204 	 * The SVE architecture mandates support for 128-bit vectors,
1205 	 * so sve_vq_map must have at least SVE_VQ_MIN set.
1206 	 * If something went wrong, at least try to patch it up:
1207 	 */
1208 	if (WARN_ON(!test_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map)))
1209 		set_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map);
1210 
1211 	zcr = read_sanitised_ftr_reg(SYS_ZCR_EL1);
1212 	info->max_vl = sve_vl_from_vq((zcr & ZCR_ELx_LEN_MASK) + 1);
1213 
1214 	/*
1215 	 * Sanity-check that the max VL we determined through CPU features
1216 	 * corresponds properly to sve_vq_map.  If not, do our best:
1217 	 */
1218 	if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SVE,
1219 								 info->max_vl)))
1220 		info->max_vl = find_supported_vector_length(ARM64_VEC_SVE,
1221 							    info->max_vl);
1222 
1223 	/*
1224 	 * For the default VL, pick the maximum supported value <= 64.
1225 	 * VL == 64 is guaranteed not to grow the signal frame.
1226 	 */
1227 	set_sve_default_vl(find_supported_vector_length(ARM64_VEC_SVE, 64));
1228 
1229 	bitmap_andnot(tmp_map, info->vq_partial_map, info->vq_map,
1230 		      SVE_VQ_MAX);
1231 
1232 	b = find_last_bit(tmp_map, SVE_VQ_MAX);
1233 	if (b >= SVE_VQ_MAX)
1234 		/* No non-virtualisable VLs found */
1235 		info->max_virtualisable_vl = SVE_VQ_MAX;
1236 	else if (WARN_ON(b == SVE_VQ_MAX - 1))
1237 		/* No virtualisable VLs?  This is architecturally forbidden. */
1238 		info->max_virtualisable_vl = SVE_VQ_MIN;
1239 	else /* b + 1 < SVE_VQ_MAX */
1240 		info->max_virtualisable_vl = sve_vl_from_vq(__bit_to_vq(b + 1));
1241 
1242 	if (info->max_virtualisable_vl > info->max_vl)
1243 		info->max_virtualisable_vl = info->max_vl;
1244 
1245 	pr_info("%s: maximum available vector length %u bytes per vector\n",
1246 		info->name, info->max_vl);
1247 	pr_info("%s: default vector length %u bytes per vector\n",
1248 		info->name, get_sve_default_vl());
1249 
1250 	/* KVM decides whether to support mismatched systems. Just warn here: */
1251 	if (sve_max_virtualisable_vl() < sve_max_vl())
1252 		pr_warn("%s: unvirtualisable vector lengths present\n",
1253 			info->name);
1254 
1255 	sve_efi_setup();
1256 }
1257 
1258 /*
1259  * Called from the put_task_struct() path, which cannot get here
1260  * unless dead_task is really dead and not schedulable.
1261  */
fpsimd_release_task(struct task_struct * dead_task)1262 void fpsimd_release_task(struct task_struct *dead_task)
1263 {
1264 	__sve_free(dead_task);
1265 	sme_free(dead_task);
1266 }
1267 
1268 #endif /* CONFIG_ARM64_SVE */
1269 
1270 #ifdef CONFIG_ARM64_SME
1271 
1272 /*
1273  * Ensure that task->thread.sme_state is allocated and sufficiently large.
1274  *
1275  * This function should be used only in preparation for replacing
1276  * task->thread.sme_state with new data.  The memory is always zeroed
1277  * here to prevent stale data from showing through: this is done in
1278  * the interest of testability and predictability, the architecture
1279  * guarantees that when ZA is enabled it will be zeroed.
1280  */
sme_alloc(struct task_struct * task,bool flush)1281 void sme_alloc(struct task_struct *task, bool flush)
1282 {
1283 	if (task->thread.sme_state) {
1284 		if (flush)
1285 			memset(task->thread.sme_state, 0,
1286 			       sme_state_size(task));
1287 		return;
1288 	}
1289 
1290 	/* This could potentially be up to 64K. */
1291 	task->thread.sme_state =
1292 		kzalloc(sme_state_size(task), GFP_KERNEL);
1293 }
1294 
sme_free(struct task_struct * task)1295 static void sme_free(struct task_struct *task)
1296 {
1297 	kfree(task->thread.sme_state);
1298 	task->thread.sme_state = NULL;
1299 }
1300 
sme_kernel_enable(const struct arm64_cpu_capabilities * __always_unused p)1301 void sme_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1302 {
1303 	/* Set priority for all PEs to architecturally defined minimum */
1304 	write_sysreg_s(read_sysreg_s(SYS_SMPRI_EL1) & ~SMPRI_EL1_PRIORITY_MASK,
1305 		       SYS_SMPRI_EL1);
1306 
1307 	/* Allow SME in kernel */
1308 	write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_SMEN_EL1EN, CPACR_EL1);
1309 	isb();
1310 
1311 	/* Allow EL0 to access TPIDR2 */
1312 	write_sysreg(read_sysreg(SCTLR_EL1) | SCTLR_ELx_ENTP2, SCTLR_EL1);
1313 	isb();
1314 }
1315 
1316 /*
1317  * This must be called after sme_kernel_enable(), we rely on the
1318  * feature table being sorted to ensure this.
1319  */
sme2_kernel_enable(const struct arm64_cpu_capabilities * __always_unused p)1320 void sme2_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1321 {
1322 	/* Allow use of ZT0 */
1323 	write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_EZT0_MASK,
1324 		       SYS_SMCR_EL1);
1325 }
1326 
1327 /*
1328  * This must be called after sme_kernel_enable(), we rely on the
1329  * feature table being sorted to ensure this.
1330  */
fa64_kernel_enable(const struct arm64_cpu_capabilities * __always_unused p)1331 void fa64_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1332 {
1333 	/* Allow use of FA64 */
1334 	write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_FA64_MASK,
1335 		       SYS_SMCR_EL1);
1336 }
1337 
1338 /*
1339  * Read the pseudo-SMCR used by cpufeatures to identify the supported
1340  * vector length.
1341  *
1342  * Use only if SME is present.
1343  * This function clobbers the SME vector length.
1344  */
read_smcr_features(void)1345 u64 read_smcr_features(void)
1346 {
1347 	sme_kernel_enable(NULL);
1348 
1349 	/*
1350 	 * Set the maximum possible VL.
1351 	 */
1352 	write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_LEN_MASK,
1353 		       SYS_SMCR_EL1);
1354 
1355 	/* Return LEN value that would be written to get the maximum VL */
1356 	return sve_vq_from_vl(sme_get_vl()) - 1;
1357 }
1358 
sme_setup(void)1359 void __init sme_setup(void)
1360 {
1361 	struct vl_info *info = &vl_info[ARM64_VEC_SME];
1362 	u64 smcr;
1363 	int min_bit;
1364 
1365 	if (!system_supports_sme())
1366 		return;
1367 
1368 	/*
1369 	 * SME doesn't require any particular vector length be
1370 	 * supported but it does require at least one.  We should have
1371 	 * disabled the feature entirely while bringing up CPUs but
1372 	 * let's double check here.
1373 	 */
1374 	WARN_ON(bitmap_empty(info->vq_map, SVE_VQ_MAX));
1375 
1376 	min_bit = find_last_bit(info->vq_map, SVE_VQ_MAX);
1377 	info->min_vl = sve_vl_from_vq(__bit_to_vq(min_bit));
1378 
1379 	smcr = read_sanitised_ftr_reg(SYS_SMCR_EL1);
1380 	info->max_vl = sve_vl_from_vq((smcr & SMCR_ELx_LEN_MASK) + 1);
1381 
1382 	/*
1383 	 * Sanity-check that the max VL we determined through CPU features
1384 	 * corresponds properly to sme_vq_map.  If not, do our best:
1385 	 */
1386 	if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SME,
1387 								 info->max_vl)))
1388 		info->max_vl = find_supported_vector_length(ARM64_VEC_SME,
1389 							    info->max_vl);
1390 
1391 	WARN_ON(info->min_vl > info->max_vl);
1392 
1393 	/*
1394 	 * For the default VL, pick the maximum supported value <= 32
1395 	 * (256 bits) if there is one since this is guaranteed not to
1396 	 * grow the signal frame when in streaming mode, otherwise the
1397 	 * minimum available VL will be used.
1398 	 */
1399 	set_sme_default_vl(find_supported_vector_length(ARM64_VEC_SME, 32));
1400 
1401 	pr_info("SME: minimum available vector length %u bytes per vector\n",
1402 		info->min_vl);
1403 	pr_info("SME: maximum available vector length %u bytes per vector\n",
1404 		info->max_vl);
1405 	pr_info("SME: default vector length %u bytes per vector\n",
1406 		get_sme_default_vl());
1407 }
1408 
sme_suspend_exit(void)1409 void sme_suspend_exit(void)
1410 {
1411 	u64 smcr = 0;
1412 
1413 	if (!system_supports_sme())
1414 		return;
1415 
1416 	if (system_supports_fa64())
1417 		smcr |= SMCR_ELx_FA64;
1418 	if (system_supports_sme2())
1419 		smcr |= SMCR_ELx_EZT0;
1420 
1421 	write_sysreg_s(smcr, SYS_SMCR_EL1);
1422 	write_sysreg_s(0, SYS_SMPRI_EL1);
1423 }
1424 
1425 #endif /* CONFIG_ARM64_SME */
1426 
sve_init_regs(void)1427 static void sve_init_regs(void)
1428 {
1429 	/*
1430 	 * Convert the FPSIMD state to SVE, zeroing all the state that
1431 	 * is not shared with FPSIMD. If (as is likely) the current
1432 	 * state is live in the registers then do this there and
1433 	 * update our metadata for the current task including
1434 	 * disabling the trap, otherwise update our in-memory copy.
1435 	 * We are guaranteed to not be in streaming mode, we can only
1436 	 * take a SVE trap when not in streaming mode and we can't be
1437 	 * in streaming mode when taking a SME trap.
1438 	 */
1439 	if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1440 		unsigned long vq_minus_one =
1441 			sve_vq_from_vl(task_get_sve_vl(current)) - 1;
1442 		sve_set_vq(vq_minus_one);
1443 		sve_flush_live(true, vq_minus_one);
1444 		fpsimd_bind_task_to_cpu();
1445 	} else {
1446 		fpsimd_to_sve(current);
1447 		current->thread.fp_type = FP_STATE_SVE;
1448 		fpsimd_flush_task_state(current);
1449 	}
1450 }
1451 
1452 /*
1453  * Trapped SVE access
1454  *
1455  * Storage is allocated for the full SVE state, the current FPSIMD
1456  * register contents are migrated across, and the access trap is
1457  * disabled.
1458  *
1459  * TIF_SVE should be clear on entry: otherwise, fpsimd_restore_current_state()
1460  * would have disabled the SVE access trap for userspace during
1461  * ret_to_user, making an SVE access trap impossible in that case.
1462  */
do_sve_acc(unsigned long esr,struct pt_regs * regs)1463 void do_sve_acc(unsigned long esr, struct pt_regs *regs)
1464 {
1465 	/* Even if we chose not to use SVE, the hardware could still trap: */
1466 	if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
1467 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1468 		return;
1469 	}
1470 
1471 	sve_alloc(current, true);
1472 	if (!current->thread.sve_state) {
1473 		force_sig(SIGKILL);
1474 		return;
1475 	}
1476 
1477 	get_cpu_fpsimd_context();
1478 
1479 	if (test_and_set_thread_flag(TIF_SVE))
1480 		WARN_ON(1); /* SVE access shouldn't have trapped */
1481 
1482 	/*
1483 	 * Even if the task can have used streaming mode we can only
1484 	 * generate SVE access traps in normal SVE mode and
1485 	 * transitioning out of streaming mode may discard any
1486 	 * streaming mode state.  Always clear the high bits to avoid
1487 	 * any potential errors tracking what is properly initialised.
1488 	 */
1489 	sve_init_regs();
1490 
1491 	put_cpu_fpsimd_context();
1492 }
1493 
1494 /*
1495  * Trapped SME access
1496  *
1497  * Storage is allocated for the full SVE and SME state, the current
1498  * FPSIMD register contents are migrated to SVE if SVE is not already
1499  * active, and the access trap is disabled.
1500  *
1501  * TIF_SME should be clear on entry: otherwise, fpsimd_restore_current_state()
1502  * would have disabled the SME access trap for userspace during
1503  * ret_to_user, making an SME access trap impossible in that case.
1504  */
do_sme_acc(unsigned long esr,struct pt_regs * regs)1505 void do_sme_acc(unsigned long esr, struct pt_regs *regs)
1506 {
1507 	/* Even if we chose not to use SME, the hardware could still trap: */
1508 	if (unlikely(!system_supports_sme()) || WARN_ON(is_compat_task())) {
1509 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1510 		return;
1511 	}
1512 
1513 	/*
1514 	 * If this not a trap due to SME being disabled then something
1515 	 * is being used in the wrong mode, report as SIGILL.
1516 	 */
1517 	if (ESR_ELx_ISS(esr) != ESR_ELx_SME_ISS_SME_DISABLED) {
1518 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1519 		return;
1520 	}
1521 
1522 	sve_alloc(current, false);
1523 	sme_alloc(current, true);
1524 	if (!current->thread.sve_state || !current->thread.sme_state) {
1525 		force_sig(SIGKILL);
1526 		return;
1527 	}
1528 
1529 	get_cpu_fpsimd_context();
1530 
1531 	/* With TIF_SME userspace shouldn't generate any traps */
1532 	if (test_and_set_thread_flag(TIF_SME))
1533 		WARN_ON(1);
1534 
1535 	if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1536 		unsigned long vq_minus_one =
1537 			sve_vq_from_vl(task_get_sme_vl(current)) - 1;
1538 		sme_set_vq(vq_minus_one);
1539 
1540 		fpsimd_bind_task_to_cpu();
1541 	}
1542 
1543 	put_cpu_fpsimd_context();
1544 }
1545 
1546 /*
1547  * Trapped FP/ASIMD access.
1548  */
do_fpsimd_acc(unsigned long esr,struct pt_regs * regs)1549 void do_fpsimd_acc(unsigned long esr, struct pt_regs *regs)
1550 {
1551 	/* TODO: implement lazy context saving/restoring */
1552 	WARN_ON(1);
1553 }
1554 
1555 /*
1556  * Raise a SIGFPE for the current process.
1557  */
do_fpsimd_exc(unsigned long esr,struct pt_regs * regs)1558 void do_fpsimd_exc(unsigned long esr, struct pt_regs *regs)
1559 {
1560 	unsigned int si_code = FPE_FLTUNK;
1561 
1562 	if (esr & ESR_ELx_FP_EXC_TFV) {
1563 		if (esr & FPEXC_IOF)
1564 			si_code = FPE_FLTINV;
1565 		else if (esr & FPEXC_DZF)
1566 			si_code = FPE_FLTDIV;
1567 		else if (esr & FPEXC_OFF)
1568 			si_code = FPE_FLTOVF;
1569 		else if (esr & FPEXC_UFF)
1570 			si_code = FPE_FLTUND;
1571 		else if (esr & FPEXC_IXF)
1572 			si_code = FPE_FLTRES;
1573 	}
1574 
1575 	send_sig_fault(SIGFPE, si_code,
1576 		       (void __user *)instruction_pointer(regs),
1577 		       current);
1578 }
1579 
fpsimd_thread_switch(struct task_struct * next)1580 void fpsimd_thread_switch(struct task_struct *next)
1581 {
1582 	bool wrong_task, wrong_cpu;
1583 
1584 	if (!system_supports_fpsimd())
1585 		return;
1586 
1587 	__get_cpu_fpsimd_context();
1588 
1589 	/* Save unsaved fpsimd state, if any: */
1590 	fpsimd_save();
1591 
1592 	/*
1593 	 * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's
1594 	 * state.  For kernel threads, FPSIMD registers are never loaded
1595 	 * and wrong_task and wrong_cpu will always be true.
1596 	 */
1597 	wrong_task = __this_cpu_read(fpsimd_last_state.st) !=
1598 					&next->thread.uw.fpsimd_state;
1599 	wrong_cpu = next->thread.fpsimd_cpu != smp_processor_id();
1600 
1601 	update_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE,
1602 			       wrong_task || wrong_cpu);
1603 
1604 	__put_cpu_fpsimd_context();
1605 }
1606 
fpsimd_flush_thread_vl(enum vec_type type)1607 static void fpsimd_flush_thread_vl(enum vec_type type)
1608 {
1609 	int vl, supported_vl;
1610 
1611 	/*
1612 	 * Reset the task vector length as required.  This is where we
1613 	 * ensure that all user tasks have a valid vector length
1614 	 * configured: no kernel task can become a user task without
1615 	 * an exec and hence a call to this function.  By the time the
1616 	 * first call to this function is made, all early hardware
1617 	 * probing is complete, so __sve_default_vl should be valid.
1618 	 * If a bug causes this to go wrong, we make some noise and
1619 	 * try to fudge thread.sve_vl to a safe value here.
1620 	 */
1621 	vl = task_get_vl_onexec(current, type);
1622 	if (!vl)
1623 		vl = get_default_vl(type);
1624 
1625 	if (WARN_ON(!sve_vl_valid(vl)))
1626 		vl = vl_info[type].min_vl;
1627 
1628 	supported_vl = find_supported_vector_length(type, vl);
1629 	if (WARN_ON(supported_vl != vl))
1630 		vl = supported_vl;
1631 
1632 	task_set_vl(current, type, vl);
1633 
1634 	/*
1635 	 * If the task is not set to inherit, ensure that the vector
1636 	 * length will be reset by a subsequent exec:
1637 	 */
1638 	if (!test_thread_flag(vec_vl_inherit_flag(type)))
1639 		task_set_vl_onexec(current, type, 0);
1640 }
1641 
fpsimd_flush_thread(void)1642 void fpsimd_flush_thread(void)
1643 {
1644 	void *sve_state = NULL;
1645 	void *sme_state = NULL;
1646 
1647 	if (!system_supports_fpsimd())
1648 		return;
1649 
1650 	get_cpu_fpsimd_context();
1651 
1652 	fpsimd_flush_task_state(current);
1653 	memset(&current->thread.uw.fpsimd_state, 0,
1654 	       sizeof(current->thread.uw.fpsimd_state));
1655 
1656 	if (system_supports_sve()) {
1657 		clear_thread_flag(TIF_SVE);
1658 
1659 		/* Defer kfree() while in atomic context */
1660 		sve_state = current->thread.sve_state;
1661 		current->thread.sve_state = NULL;
1662 
1663 		fpsimd_flush_thread_vl(ARM64_VEC_SVE);
1664 	}
1665 
1666 	if (system_supports_sme()) {
1667 		clear_thread_flag(TIF_SME);
1668 
1669 		/* Defer kfree() while in atomic context */
1670 		sme_state = current->thread.sme_state;
1671 		current->thread.sme_state = NULL;
1672 
1673 		fpsimd_flush_thread_vl(ARM64_VEC_SME);
1674 		current->thread.svcr = 0;
1675 	}
1676 
1677 	current->thread.fp_type = FP_STATE_FPSIMD;
1678 
1679 	put_cpu_fpsimd_context();
1680 	kfree(sve_state);
1681 	kfree(sme_state);
1682 }
1683 
1684 /*
1685  * Save the userland FPSIMD state of 'current' to memory, but only if the state
1686  * currently held in the registers does in fact belong to 'current'
1687  */
fpsimd_preserve_current_state(void)1688 void fpsimd_preserve_current_state(void)
1689 {
1690 	if (!system_supports_fpsimd())
1691 		return;
1692 
1693 	get_cpu_fpsimd_context();
1694 	fpsimd_save();
1695 	put_cpu_fpsimd_context();
1696 }
1697 
1698 /*
1699  * Like fpsimd_preserve_current_state(), but ensure that
1700  * current->thread.uw.fpsimd_state is updated so that it can be copied to
1701  * the signal frame.
1702  */
fpsimd_signal_preserve_current_state(void)1703 void fpsimd_signal_preserve_current_state(void)
1704 {
1705 	fpsimd_preserve_current_state();
1706 	if (current->thread.fp_type == FP_STATE_SVE)
1707 		sve_to_fpsimd(current);
1708 }
1709 
1710 /*
1711  * Called by KVM when entering the guest.
1712  */
fpsimd_kvm_prepare(void)1713 void fpsimd_kvm_prepare(void)
1714 {
1715 	if (!system_supports_sve())
1716 		return;
1717 
1718 	/*
1719 	 * KVM does not save host SVE state since we can only enter
1720 	 * the guest from a syscall so the ABI means that only the
1721 	 * non-saved SVE state needs to be saved.  If we have left
1722 	 * SVE enabled for performance reasons then update the task
1723 	 * state to be FPSIMD only.
1724 	 */
1725 	get_cpu_fpsimd_context();
1726 
1727 	if (test_and_clear_thread_flag(TIF_SVE)) {
1728 		sve_to_fpsimd(current);
1729 		current->thread.fp_type = FP_STATE_FPSIMD;
1730 	}
1731 
1732 	put_cpu_fpsimd_context();
1733 }
1734 
1735 /*
1736  * Associate current's FPSIMD context with this cpu
1737  * The caller must have ownership of the cpu FPSIMD context before calling
1738  * this function.
1739  */
fpsimd_bind_task_to_cpu(void)1740 static void fpsimd_bind_task_to_cpu(void)
1741 {
1742 	struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state);
1743 
1744 	WARN_ON(!system_supports_fpsimd());
1745 	last->st = &current->thread.uw.fpsimd_state;
1746 	last->sve_state = current->thread.sve_state;
1747 	last->sme_state = current->thread.sme_state;
1748 	last->sve_vl = task_get_sve_vl(current);
1749 	last->sme_vl = task_get_sme_vl(current);
1750 	last->svcr = &current->thread.svcr;
1751 	last->fp_type = &current->thread.fp_type;
1752 	last->to_save = FP_STATE_CURRENT;
1753 	current->thread.fpsimd_cpu = smp_processor_id();
1754 
1755 	/*
1756 	 * Toggle SVE and SME trapping for userspace if needed, these
1757 	 * are serialsied by ret_to_user().
1758 	 */
1759 	if (system_supports_sme()) {
1760 		if (test_thread_flag(TIF_SME))
1761 			sme_user_enable();
1762 		else
1763 			sme_user_disable();
1764 	}
1765 
1766 	if (system_supports_sve()) {
1767 		if (test_thread_flag(TIF_SVE))
1768 			sve_user_enable();
1769 		else
1770 			sve_user_disable();
1771 	}
1772 }
1773 
fpsimd_bind_state_to_cpu(struct cpu_fp_state * state)1774 void fpsimd_bind_state_to_cpu(struct cpu_fp_state *state)
1775 {
1776 	struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state);
1777 
1778 	WARN_ON(!system_supports_fpsimd());
1779 	WARN_ON(!in_softirq() && !irqs_disabled());
1780 
1781 	*last = *state;
1782 }
1783 
1784 /*
1785  * Load the userland FPSIMD state of 'current' from memory, but only if the
1786  * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1787  * state of 'current'.  This is called when we are preparing to return to
1788  * userspace to ensure that userspace sees a good register state.
1789  */
fpsimd_restore_current_state(void)1790 void fpsimd_restore_current_state(void)
1791 {
1792 	/*
1793 	 * For the tasks that were created before we detected the absence of
1794 	 * FP/SIMD, the TIF_FOREIGN_FPSTATE could be set via fpsimd_thread_switch(),
1795 	 * e.g, init. This could be then inherited by the children processes.
1796 	 * If we later detect that the system doesn't support FP/SIMD,
1797 	 * we must clear the flag for  all the tasks to indicate that the
1798 	 * FPSTATE is clean (as we can't have one) to avoid looping for ever in
1799 	 * do_notify_resume().
1800 	 */
1801 	if (!system_supports_fpsimd()) {
1802 		clear_thread_flag(TIF_FOREIGN_FPSTATE);
1803 		return;
1804 	}
1805 
1806 	get_cpu_fpsimd_context();
1807 
1808 	if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1809 		task_fpsimd_load();
1810 		fpsimd_bind_task_to_cpu();
1811 	}
1812 
1813 	put_cpu_fpsimd_context();
1814 }
1815 
1816 /*
1817  * Load an updated userland FPSIMD state for 'current' from memory and set the
1818  * flag that indicates that the FPSIMD register contents are the most recent
1819  * FPSIMD state of 'current'. This is used by the signal code to restore the
1820  * register state when returning from a signal handler in FPSIMD only cases,
1821  * any SVE context will be discarded.
1822  */
fpsimd_update_current_state(struct user_fpsimd_state const * state)1823 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1824 {
1825 	if (WARN_ON(!system_supports_fpsimd()))
1826 		return;
1827 
1828 	get_cpu_fpsimd_context();
1829 
1830 	current->thread.uw.fpsimd_state = *state;
1831 	if (test_thread_flag(TIF_SVE))
1832 		fpsimd_to_sve(current);
1833 
1834 	task_fpsimd_load();
1835 	fpsimd_bind_task_to_cpu();
1836 
1837 	clear_thread_flag(TIF_FOREIGN_FPSTATE);
1838 
1839 	put_cpu_fpsimd_context();
1840 }
1841 
1842 /*
1843  * Invalidate live CPU copies of task t's FPSIMD state
1844  *
1845  * This function may be called with preemption enabled.  The barrier()
1846  * ensures that the assignment to fpsimd_cpu is visible to any
1847  * preemption/softirq that could race with set_tsk_thread_flag(), so
1848  * that TIF_FOREIGN_FPSTATE cannot be spuriously re-cleared.
1849  *
1850  * The final barrier ensures that TIF_FOREIGN_FPSTATE is seen set by any
1851  * subsequent code.
1852  */
fpsimd_flush_task_state(struct task_struct * t)1853 void fpsimd_flush_task_state(struct task_struct *t)
1854 {
1855 	t->thread.fpsimd_cpu = NR_CPUS;
1856 	/*
1857 	 * If we don't support fpsimd, bail out after we have
1858 	 * reset the fpsimd_cpu for this task and clear the
1859 	 * FPSTATE.
1860 	 */
1861 	if (!system_supports_fpsimd())
1862 		return;
1863 	barrier();
1864 	set_tsk_thread_flag(t, TIF_FOREIGN_FPSTATE);
1865 
1866 	barrier();
1867 }
1868 
1869 /*
1870  * Invalidate any task's FPSIMD state that is present on this cpu.
1871  * The FPSIMD context should be acquired with get_cpu_fpsimd_context()
1872  * before calling this function.
1873  */
fpsimd_flush_cpu_state(void)1874 static void fpsimd_flush_cpu_state(void)
1875 {
1876 	WARN_ON(!system_supports_fpsimd());
1877 	__this_cpu_write(fpsimd_last_state.st, NULL);
1878 
1879 	/*
1880 	 * Leaving streaming mode enabled will cause issues for any kernel
1881 	 * NEON and leaving streaming mode or ZA enabled may increase power
1882 	 * consumption.
1883 	 */
1884 	if (system_supports_sme())
1885 		sme_smstop();
1886 
1887 	set_thread_flag(TIF_FOREIGN_FPSTATE);
1888 }
1889 
1890 /*
1891  * Save the FPSIMD state to memory and invalidate cpu view.
1892  * This function must be called with preemption disabled.
1893  */
fpsimd_save_and_flush_cpu_state(void)1894 void fpsimd_save_and_flush_cpu_state(void)
1895 {
1896 	if (!system_supports_fpsimd())
1897 		return;
1898 	WARN_ON(preemptible());
1899 	__get_cpu_fpsimd_context();
1900 	fpsimd_save();
1901 	fpsimd_flush_cpu_state();
1902 	__put_cpu_fpsimd_context();
1903 }
1904 
1905 #ifdef CONFIG_KERNEL_MODE_NEON
1906 
1907 /*
1908  * Kernel-side NEON support functions
1909  */
1910 
1911 /*
1912  * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1913  * context
1914  *
1915  * Must not be called unless may_use_simd() returns true.
1916  * Task context in the FPSIMD registers is saved back to memory as necessary.
1917  *
1918  * A matching call to kernel_neon_end() must be made before returning from the
1919  * calling context.
1920  *
1921  * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1922  * called.
1923  */
kernel_neon_begin(void)1924 void kernel_neon_begin(void)
1925 {
1926 	if (WARN_ON(!system_supports_fpsimd()))
1927 		return;
1928 
1929 	BUG_ON(!may_use_simd());
1930 
1931 	get_cpu_fpsimd_context();
1932 
1933 	/* Save unsaved fpsimd state, if any: */
1934 	fpsimd_save();
1935 
1936 	/* Invalidate any task state remaining in the fpsimd regs: */
1937 	fpsimd_flush_cpu_state();
1938 }
1939 EXPORT_SYMBOL_GPL(kernel_neon_begin);
1940 
1941 /*
1942  * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1943  *
1944  * Must be called from a context in which kernel_neon_begin() was previously
1945  * called, with no call to kernel_neon_end() in the meantime.
1946  *
1947  * The caller must not use the FPSIMD registers after this function is called,
1948  * unless kernel_neon_begin() is called again in the meantime.
1949  */
kernel_neon_end(void)1950 void kernel_neon_end(void)
1951 {
1952 	if (!system_supports_fpsimd())
1953 		return;
1954 
1955 	put_cpu_fpsimd_context();
1956 }
1957 EXPORT_SYMBOL_GPL(kernel_neon_end);
1958 
1959 #ifdef CONFIG_EFI
1960 
1961 static DEFINE_PER_CPU(struct user_fpsimd_state, efi_fpsimd_state);
1962 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1963 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1964 static DEFINE_PER_CPU(bool, efi_sm_state);
1965 
1966 /*
1967  * EFI runtime services support functions
1968  *
1969  * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1970  * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1971  * is always used rather than being an optional accelerator.
1972  *
1973  * These functions provide the necessary support for ensuring FPSIMD
1974  * save/restore in the contexts from which EFI is used.
1975  *
1976  * Do not use them for any other purpose -- if tempted to do so, you are
1977  * either doing something wrong or you need to propose some refactoring.
1978  */
1979 
1980 /*
1981  * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1982  */
__efi_fpsimd_begin(void)1983 void __efi_fpsimd_begin(void)
1984 {
1985 	if (!system_supports_fpsimd())
1986 		return;
1987 
1988 	WARN_ON(preemptible());
1989 
1990 	if (may_use_simd()) {
1991 		kernel_neon_begin();
1992 	} else {
1993 		/*
1994 		 * If !efi_sve_state, SVE can't be in use yet and doesn't need
1995 		 * preserving:
1996 		 */
1997 		if (system_supports_sve() && likely(efi_sve_state)) {
1998 			char *sve_state = this_cpu_ptr(efi_sve_state);
1999 			bool ffr = true;
2000 			u64 svcr;
2001 
2002 			__this_cpu_write(efi_sve_state_used, true);
2003 
2004 			if (system_supports_sme()) {
2005 				svcr = read_sysreg_s(SYS_SVCR);
2006 
2007 				__this_cpu_write(efi_sm_state,
2008 						 svcr & SVCR_SM_MASK);
2009 
2010 				/*
2011 				 * Unless we have FA64 FFR does not
2012 				 * exist in streaming mode.
2013 				 */
2014 				if (!system_supports_fa64())
2015 					ffr = !(svcr & SVCR_SM_MASK);
2016 			}
2017 
2018 			sve_save_state(sve_state + sve_ffr_offset(sve_max_vl()),
2019 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
2020 				       ffr);
2021 
2022 			if (system_supports_sme())
2023 				sysreg_clear_set_s(SYS_SVCR,
2024 						   SVCR_SM_MASK, 0);
2025 
2026 		} else {
2027 			fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
2028 		}
2029 
2030 		__this_cpu_write(efi_fpsimd_state_used, true);
2031 	}
2032 }
2033 
2034 /*
2035  * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
2036  */
__efi_fpsimd_end(void)2037 void __efi_fpsimd_end(void)
2038 {
2039 	if (!system_supports_fpsimd())
2040 		return;
2041 
2042 	if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
2043 		kernel_neon_end();
2044 	} else {
2045 		if (system_supports_sve() &&
2046 		    likely(__this_cpu_read(efi_sve_state_used))) {
2047 			char const *sve_state = this_cpu_ptr(efi_sve_state);
2048 			bool ffr = true;
2049 
2050 			/*
2051 			 * Restore streaming mode; EFI calls are
2052 			 * normal function calls so should not return in
2053 			 * streaming mode.
2054 			 */
2055 			if (system_supports_sme()) {
2056 				if (__this_cpu_read(efi_sm_state)) {
2057 					sysreg_clear_set_s(SYS_SVCR,
2058 							   0,
2059 							   SVCR_SM_MASK);
2060 
2061 					/*
2062 					 * Unless we have FA64 FFR does not
2063 					 * exist in streaming mode.
2064 					 */
2065 					if (!system_supports_fa64())
2066 						ffr = false;
2067 				}
2068 			}
2069 
2070 			sve_load_state(sve_state + sve_ffr_offset(sve_max_vl()),
2071 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
2072 				       ffr);
2073 
2074 			__this_cpu_write(efi_sve_state_used, false);
2075 		} else {
2076 			fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
2077 		}
2078 	}
2079 }
2080 
2081 #endif /* CONFIG_EFI */
2082 
2083 #endif /* CONFIG_KERNEL_MODE_NEON */
2084 
2085 #ifdef CONFIG_CPU_PM
fpsimd_cpu_pm_notifier(struct notifier_block * self,unsigned long cmd,void * v)2086 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
2087 				  unsigned long cmd, void *v)
2088 {
2089 	switch (cmd) {
2090 	case CPU_PM_ENTER:
2091 		fpsimd_save_and_flush_cpu_state();
2092 		break;
2093 	case CPU_PM_EXIT:
2094 		break;
2095 	case CPU_PM_ENTER_FAILED:
2096 	default:
2097 		return NOTIFY_DONE;
2098 	}
2099 	return NOTIFY_OK;
2100 }
2101 
2102 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
2103 	.notifier_call = fpsimd_cpu_pm_notifier,
2104 };
2105 
fpsimd_pm_init(void)2106 static void __init fpsimd_pm_init(void)
2107 {
2108 	cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
2109 }
2110 
2111 #else
fpsimd_pm_init(void)2112 static inline void fpsimd_pm_init(void) { }
2113 #endif /* CONFIG_CPU_PM */
2114 
2115 #ifdef CONFIG_HOTPLUG_CPU
fpsimd_cpu_dead(unsigned int cpu)2116 static int fpsimd_cpu_dead(unsigned int cpu)
2117 {
2118 	per_cpu(fpsimd_last_state.st, cpu) = NULL;
2119 	return 0;
2120 }
2121 
fpsimd_hotplug_init(void)2122 static inline void fpsimd_hotplug_init(void)
2123 {
2124 	cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
2125 				  NULL, fpsimd_cpu_dead);
2126 }
2127 
2128 #else
fpsimd_hotplug_init(void)2129 static inline void fpsimd_hotplug_init(void) { }
2130 #endif
2131 
2132 /*
2133  * FP/SIMD support code initialisation.
2134  */
fpsimd_init(void)2135 static int __init fpsimd_init(void)
2136 {
2137 	if (cpu_have_named_feature(FP)) {
2138 		fpsimd_pm_init();
2139 		fpsimd_hotplug_init();
2140 	} else {
2141 		pr_notice("Floating-point is not implemented\n");
2142 	}
2143 
2144 	if (!cpu_have_named_feature(ASIMD))
2145 		pr_notice("Advanced SIMD is not implemented\n");
2146 
2147 
2148 	sve_sysctl_init();
2149 	sme_sysctl_init();
2150 
2151 	return 0;
2152 }
2153 core_initcall(fpsimd_init);
2154