xref: /linux/arch/arm64/kernel/fpsimd.c (revision 16e5ac127d8d18adf85fe5ba847d77b58d1ed418)
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 
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 
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 
168 static inline int get_sve_default_vl(void)
169 {
170 	return get_default_vl(ARM64_VEC_SVE);
171 }
172 
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 
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 
194 static int get_sme_default_vl(void)
195 {
196 	return get_default_vl(ARM64_VEC_SME);
197 }
198 
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 
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 
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  */
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 
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  */
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 
271 static bool have_cpu_fpsimd_context(void)
272 {
273 	return !preemptible() && __this_cpu_read(fpsimd_context_busy);
274 }
275 
276 unsigned int task_get_vl(const struct task_struct *task, enum vec_type type)
277 {
278 	return task->thread.vl[type];
279 }
280 
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 
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 
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  */
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  */
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  */
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 
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 static int __init sve_sysctl_init(void)
595 {
596 	if (system_supports_sve())
597 		if (!register_sysctl("abi", sve_default_vl_table))
598 			return -EINVAL;
599 
600 	return 0;
601 }
602 
603 #else /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
604 static int __init sve_sysctl_init(void) { return 0; }
605 #endif /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
606 
607 #if defined(CONFIG_ARM64_SME) && defined(CONFIG_SYSCTL)
608 static struct ctl_table sme_default_vl_table[] = {
609 	{
610 		.procname	= "sme_default_vector_length",
611 		.mode		= 0644,
612 		.proc_handler	= vec_proc_do_default_vl,
613 		.extra1		= &vl_info[ARM64_VEC_SME],
614 	},
615 };
616 
617 static int __init sme_sysctl_init(void)
618 {
619 	if (system_supports_sme())
620 		if (!register_sysctl("abi", sme_default_vl_table))
621 			return -EINVAL;
622 
623 	return 0;
624 }
625 
626 #else /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
627 static int __init sme_sysctl_init(void) { return 0; }
628 #endif /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
629 
630 #define ZREG(sve_state, vq, n) ((char *)(sve_state) +		\
631 	(SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
632 
633 #ifdef CONFIG_CPU_BIG_ENDIAN
634 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
635 {
636 	u64 a = swab64(x);
637 	u64 b = swab64(x >> 64);
638 
639 	return ((__uint128_t)a << 64) | b;
640 }
641 #else
642 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
643 {
644 	return x;
645 }
646 #endif
647 
648 #define arm64_le128_to_cpu(x) arm64_cpu_to_le128(x)
649 
650 static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst,
651 			    unsigned int vq)
652 {
653 	unsigned int i;
654 	__uint128_t *p;
655 
656 	for (i = 0; i < SVE_NUM_ZREGS; ++i) {
657 		p = (__uint128_t *)ZREG(sst, vq, i);
658 		*p = arm64_cpu_to_le128(fst->vregs[i]);
659 	}
660 }
661 
662 /*
663  * Transfer the FPSIMD state in task->thread.uw.fpsimd_state to
664  * task->thread.sve_state.
665  *
666  * Task can be a non-runnable task, or current.  In the latter case,
667  * the caller must have ownership of the cpu FPSIMD context before calling
668  * this function.
669  * task->thread.sve_state must point to at least sve_state_size(task)
670  * bytes of allocated kernel memory.
671  * task->thread.uw.fpsimd_state must be up to date before calling this
672  * function.
673  */
674 static void fpsimd_to_sve(struct task_struct *task)
675 {
676 	unsigned int vq;
677 	void *sst = task->thread.sve_state;
678 	struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
679 
680 	if (!system_supports_sve() && !system_supports_sme())
681 		return;
682 
683 	vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
684 	__fpsimd_to_sve(sst, fst, vq);
685 }
686 
687 /*
688  * Transfer the SVE state in task->thread.sve_state to
689  * task->thread.uw.fpsimd_state.
690  *
691  * Task can be a non-runnable task, or current.  In the latter case,
692  * the caller must have ownership of the cpu FPSIMD context before calling
693  * this function.
694  * task->thread.sve_state must point to at least sve_state_size(task)
695  * bytes of allocated kernel memory.
696  * task->thread.sve_state must be up to date before calling this function.
697  */
698 static void sve_to_fpsimd(struct task_struct *task)
699 {
700 	unsigned int vq, vl;
701 	void const *sst = task->thread.sve_state;
702 	struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state;
703 	unsigned int i;
704 	__uint128_t const *p;
705 
706 	if (!system_supports_sve() && !system_supports_sme())
707 		return;
708 
709 	vl = thread_get_cur_vl(&task->thread);
710 	vq = sve_vq_from_vl(vl);
711 	for (i = 0; i < SVE_NUM_ZREGS; ++i) {
712 		p = (__uint128_t const *)ZREG(sst, vq, i);
713 		fst->vregs[i] = arm64_le128_to_cpu(*p);
714 	}
715 }
716 
717 #ifdef CONFIG_ARM64_SVE
718 /*
719  * Call __sve_free() directly only if you know task can't be scheduled
720  * or preempted.
721  */
722 static void __sve_free(struct task_struct *task)
723 {
724 	kfree(task->thread.sve_state);
725 	task->thread.sve_state = NULL;
726 }
727 
728 static void sve_free(struct task_struct *task)
729 {
730 	WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
731 
732 	__sve_free(task);
733 }
734 
735 /*
736  * Return how many bytes of memory are required to store the full SVE
737  * state for task, given task's currently configured vector length.
738  */
739 size_t sve_state_size(struct task_struct const *task)
740 {
741 	unsigned int vl = 0;
742 
743 	if (system_supports_sve())
744 		vl = task_get_sve_vl(task);
745 	if (system_supports_sme())
746 		vl = max(vl, task_get_sme_vl(task));
747 
748 	return SVE_SIG_REGS_SIZE(sve_vq_from_vl(vl));
749 }
750 
751 /*
752  * Ensure that task->thread.sve_state is allocated and sufficiently large.
753  *
754  * This function should be used only in preparation for replacing
755  * task->thread.sve_state with new data.  The memory is always zeroed
756  * here to prevent stale data from showing through: this is done in
757  * the interest of testability and predictability: except in the
758  * do_sve_acc() case, there is no ABI requirement to hide stale data
759  * written previously be task.
760  */
761 void sve_alloc(struct task_struct *task, bool flush)
762 {
763 	if (task->thread.sve_state) {
764 		if (flush)
765 			memset(task->thread.sve_state, 0,
766 			       sve_state_size(task));
767 		return;
768 	}
769 
770 	/* This is a small allocation (maximum ~8KB) and Should Not Fail. */
771 	task->thread.sve_state =
772 		kzalloc(sve_state_size(task), GFP_KERNEL);
773 }
774 
775 
776 /*
777  * Force the FPSIMD state shared with SVE to be updated in the SVE state
778  * even if the SVE state is the current active state.
779  *
780  * This should only be called by ptrace.  task must be non-runnable.
781  * task->thread.sve_state must point to at least sve_state_size(task)
782  * bytes of allocated kernel memory.
783  */
784 void fpsimd_force_sync_to_sve(struct task_struct *task)
785 {
786 	fpsimd_to_sve(task);
787 }
788 
789 /*
790  * Ensure that task->thread.sve_state is up to date with respect to
791  * the user task, irrespective of when SVE is in use or not.
792  *
793  * This should only be called by ptrace.  task must be non-runnable.
794  * task->thread.sve_state must point to at least sve_state_size(task)
795  * bytes of allocated kernel memory.
796  */
797 void fpsimd_sync_to_sve(struct task_struct *task)
798 {
799 	if (!test_tsk_thread_flag(task, TIF_SVE) &&
800 	    !thread_sm_enabled(&task->thread))
801 		fpsimd_to_sve(task);
802 }
803 
804 /*
805  * Ensure that task->thread.uw.fpsimd_state is up to date with respect to
806  * the user task, irrespective of whether SVE is in use or not.
807  *
808  * This should only be called by ptrace.  task must be non-runnable.
809  * task->thread.sve_state must point to at least sve_state_size(task)
810  * bytes of allocated kernel memory.
811  */
812 void sve_sync_to_fpsimd(struct task_struct *task)
813 {
814 	if (task->thread.fp_type == FP_STATE_SVE)
815 		sve_to_fpsimd(task);
816 }
817 
818 /*
819  * Ensure that task->thread.sve_state is up to date with respect to
820  * the task->thread.uw.fpsimd_state.
821  *
822  * This should only be called by ptrace to merge new FPSIMD register
823  * values into a task for which SVE is currently active.
824  * task must be non-runnable.
825  * task->thread.sve_state must point to at least sve_state_size(task)
826  * bytes of allocated kernel memory.
827  * task->thread.uw.fpsimd_state must already have been initialised with
828  * the new FPSIMD register values to be merged in.
829  */
830 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
831 {
832 	unsigned int vq;
833 	void *sst = task->thread.sve_state;
834 	struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
835 
836 	if (!test_tsk_thread_flag(task, TIF_SVE) &&
837 	    !thread_sm_enabled(&task->thread))
838 		return;
839 
840 	vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
841 
842 	memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
843 	__fpsimd_to_sve(sst, fst, vq);
844 }
845 
846 int vec_set_vector_length(struct task_struct *task, enum vec_type type,
847 			  unsigned long vl, unsigned long flags)
848 {
849 	bool free_sme = false;
850 
851 	if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
852 				     PR_SVE_SET_VL_ONEXEC))
853 		return -EINVAL;
854 
855 	if (!sve_vl_valid(vl))
856 		return -EINVAL;
857 
858 	/*
859 	 * Clamp to the maximum vector length that VL-agnostic code
860 	 * can work with.  A flag may be assigned in the future to
861 	 * allow setting of larger vector lengths without confusing
862 	 * older software.
863 	 */
864 	if (vl > VL_ARCH_MAX)
865 		vl = VL_ARCH_MAX;
866 
867 	vl = find_supported_vector_length(type, vl);
868 
869 	if (flags & (PR_SVE_VL_INHERIT |
870 		     PR_SVE_SET_VL_ONEXEC))
871 		task_set_vl_onexec(task, type, vl);
872 	else
873 		/* Reset VL to system default on next exec: */
874 		task_set_vl_onexec(task, type, 0);
875 
876 	/* Only actually set the VL if not deferred: */
877 	if (flags & PR_SVE_SET_VL_ONEXEC)
878 		goto out;
879 
880 	if (vl == task_get_vl(task, type))
881 		goto out;
882 
883 	/*
884 	 * To ensure the FPSIMD bits of the SVE vector registers are preserved,
885 	 * write any live register state back to task_struct, and convert to a
886 	 * regular FPSIMD thread.
887 	 */
888 	if (task == current) {
889 		get_cpu_fpsimd_context();
890 
891 		fpsimd_save();
892 	}
893 
894 	fpsimd_flush_task_state(task);
895 	if (test_and_clear_tsk_thread_flag(task, TIF_SVE) ||
896 	    thread_sm_enabled(&task->thread)) {
897 		sve_to_fpsimd(task);
898 		task->thread.fp_type = FP_STATE_FPSIMD;
899 	}
900 
901 	if (system_supports_sme()) {
902 		if (type == ARM64_VEC_SME ||
903 		    !(task->thread.svcr & (SVCR_SM_MASK | SVCR_ZA_MASK))) {
904 			/*
905 			 * We are changing the SME VL or weren't using
906 			 * SME anyway, discard the state and force a
907 			 * reallocation.
908 			 */
909 			task->thread.svcr &= ~(SVCR_SM_MASK |
910 					       SVCR_ZA_MASK);
911 			clear_tsk_thread_flag(task, TIF_SME);
912 			free_sme = true;
913 		}
914 	}
915 
916 	if (task == current)
917 		put_cpu_fpsimd_context();
918 
919 	task_set_vl(task, type, vl);
920 
921 	/*
922 	 * Free the changed states if they are not in use, SME will be
923 	 * reallocated to the correct size on next use and we just
924 	 * allocate SVE now in case it is needed for use in streaming
925 	 * mode.
926 	 */
927 	if (system_supports_sve()) {
928 		sve_free(task);
929 		sve_alloc(task, true);
930 	}
931 
932 	if (free_sme)
933 		sme_free(task);
934 
935 out:
936 	update_tsk_thread_flag(task, vec_vl_inherit_flag(type),
937 			       flags & PR_SVE_VL_INHERIT);
938 
939 	return 0;
940 }
941 
942 /*
943  * Encode the current vector length and flags for return.
944  * This is only required for prctl(): ptrace has separate fields.
945  * SVE and SME use the same bits for _ONEXEC and _INHERIT.
946  *
947  * flags are as for vec_set_vector_length().
948  */
949 static int vec_prctl_status(enum vec_type type, unsigned long flags)
950 {
951 	int ret;
952 
953 	if (flags & PR_SVE_SET_VL_ONEXEC)
954 		ret = task_get_vl_onexec(current, type);
955 	else
956 		ret = task_get_vl(current, type);
957 
958 	if (test_thread_flag(vec_vl_inherit_flag(type)))
959 		ret |= PR_SVE_VL_INHERIT;
960 
961 	return ret;
962 }
963 
964 /* PR_SVE_SET_VL */
965 int sve_set_current_vl(unsigned long arg)
966 {
967 	unsigned long vl, flags;
968 	int ret;
969 
970 	vl = arg & PR_SVE_VL_LEN_MASK;
971 	flags = arg & ~vl;
972 
973 	if (!system_supports_sve() || is_compat_task())
974 		return -EINVAL;
975 
976 	ret = vec_set_vector_length(current, ARM64_VEC_SVE, vl, flags);
977 	if (ret)
978 		return ret;
979 
980 	return vec_prctl_status(ARM64_VEC_SVE, flags);
981 }
982 
983 /* PR_SVE_GET_VL */
984 int sve_get_current_vl(void)
985 {
986 	if (!system_supports_sve() || is_compat_task())
987 		return -EINVAL;
988 
989 	return vec_prctl_status(ARM64_VEC_SVE, 0);
990 }
991 
992 #ifdef CONFIG_ARM64_SME
993 /* PR_SME_SET_VL */
994 int sme_set_current_vl(unsigned long arg)
995 {
996 	unsigned long vl, flags;
997 	int ret;
998 
999 	vl = arg & PR_SME_VL_LEN_MASK;
1000 	flags = arg & ~vl;
1001 
1002 	if (!system_supports_sme() || is_compat_task())
1003 		return -EINVAL;
1004 
1005 	ret = vec_set_vector_length(current, ARM64_VEC_SME, vl, flags);
1006 	if (ret)
1007 		return ret;
1008 
1009 	return vec_prctl_status(ARM64_VEC_SME, flags);
1010 }
1011 
1012 /* PR_SME_GET_VL */
1013 int sme_get_current_vl(void)
1014 {
1015 	if (!system_supports_sme() || is_compat_task())
1016 		return -EINVAL;
1017 
1018 	return vec_prctl_status(ARM64_VEC_SME, 0);
1019 }
1020 #endif /* CONFIG_ARM64_SME */
1021 
1022 static void vec_probe_vqs(struct vl_info *info,
1023 			  DECLARE_BITMAP(map, SVE_VQ_MAX))
1024 {
1025 	unsigned int vq, vl;
1026 
1027 	bitmap_zero(map, SVE_VQ_MAX);
1028 
1029 	for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
1030 		write_vl(info->type, vq - 1); /* self-syncing */
1031 
1032 		switch (info->type) {
1033 		case ARM64_VEC_SVE:
1034 			vl = sve_get_vl();
1035 			break;
1036 		case ARM64_VEC_SME:
1037 			vl = sme_get_vl();
1038 			break;
1039 		default:
1040 			vl = 0;
1041 			break;
1042 		}
1043 
1044 		/* Minimum VL identified? */
1045 		if (sve_vq_from_vl(vl) > vq)
1046 			break;
1047 
1048 		vq = sve_vq_from_vl(vl); /* skip intervening lengths */
1049 		set_bit(__vq_to_bit(vq), map);
1050 	}
1051 }
1052 
1053 /*
1054  * Initialise the set of known supported VQs for the boot CPU.
1055  * This is called during kernel boot, before secondary CPUs are brought up.
1056  */
1057 void __init vec_init_vq_map(enum vec_type type)
1058 {
1059 	struct vl_info *info = &vl_info[type];
1060 	vec_probe_vqs(info, info->vq_map);
1061 	bitmap_copy(info->vq_partial_map, info->vq_map, SVE_VQ_MAX);
1062 }
1063 
1064 /*
1065  * If we haven't committed to the set of supported VQs yet, filter out
1066  * those not supported by the current CPU.
1067  * This function is called during the bring-up of early secondary CPUs only.
1068  */
1069 void vec_update_vq_map(enum vec_type type)
1070 {
1071 	struct vl_info *info = &vl_info[type];
1072 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1073 
1074 	vec_probe_vqs(info, tmp_map);
1075 	bitmap_and(info->vq_map, info->vq_map, tmp_map, SVE_VQ_MAX);
1076 	bitmap_or(info->vq_partial_map, info->vq_partial_map, tmp_map,
1077 		  SVE_VQ_MAX);
1078 }
1079 
1080 /*
1081  * Check whether the current CPU supports all VQs in the committed set.
1082  * This function is called during the bring-up of late secondary CPUs only.
1083  */
1084 int vec_verify_vq_map(enum vec_type type)
1085 {
1086 	struct vl_info *info = &vl_info[type];
1087 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1088 	unsigned long b;
1089 
1090 	vec_probe_vqs(info, tmp_map);
1091 
1092 	bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1093 	if (bitmap_intersects(tmp_map, info->vq_map, SVE_VQ_MAX)) {
1094 		pr_warn("%s: cpu%d: Required vector length(s) missing\n",
1095 			info->name, smp_processor_id());
1096 		return -EINVAL;
1097 	}
1098 
1099 	if (!IS_ENABLED(CONFIG_KVM) || !is_hyp_mode_available())
1100 		return 0;
1101 
1102 	/*
1103 	 * For KVM, it is necessary to ensure that this CPU doesn't
1104 	 * support any vector length that guests may have probed as
1105 	 * unsupported.
1106 	 */
1107 
1108 	/* Recover the set of supported VQs: */
1109 	bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1110 	/* Find VQs supported that are not globally supported: */
1111 	bitmap_andnot(tmp_map, tmp_map, info->vq_map, SVE_VQ_MAX);
1112 
1113 	/* Find the lowest such VQ, if any: */
1114 	b = find_last_bit(tmp_map, SVE_VQ_MAX);
1115 	if (b >= SVE_VQ_MAX)
1116 		return 0; /* no mismatches */
1117 
1118 	/*
1119 	 * Mismatches above sve_max_virtualisable_vl are fine, since
1120 	 * no guest is allowed to configure ZCR_EL2.LEN to exceed this:
1121 	 */
1122 	if (sve_vl_from_vq(__bit_to_vq(b)) <= info->max_virtualisable_vl) {
1123 		pr_warn("%s: cpu%d: Unsupported vector length(s) present\n",
1124 			info->name, smp_processor_id());
1125 		return -EINVAL;
1126 	}
1127 
1128 	return 0;
1129 }
1130 
1131 static void __init sve_efi_setup(void)
1132 {
1133 	int max_vl = 0;
1134 	int i;
1135 
1136 	if (!IS_ENABLED(CONFIG_EFI))
1137 		return;
1138 
1139 	for (i = 0; i < ARRAY_SIZE(vl_info); i++)
1140 		max_vl = max(vl_info[i].max_vl, max_vl);
1141 
1142 	/*
1143 	 * alloc_percpu() warns and prints a backtrace if this goes wrong.
1144 	 * This is evidence of a crippled system and we are returning void,
1145 	 * so no attempt is made to handle this situation here.
1146 	 */
1147 	if (!sve_vl_valid(max_vl))
1148 		goto fail;
1149 
1150 	efi_sve_state = __alloc_percpu(
1151 		SVE_SIG_REGS_SIZE(sve_vq_from_vl(max_vl)), SVE_VQ_BYTES);
1152 	if (!efi_sve_state)
1153 		goto fail;
1154 
1155 	return;
1156 
1157 fail:
1158 	panic("Cannot allocate percpu memory for EFI SVE save/restore");
1159 }
1160 
1161 void cpu_enable_sve(const struct arm64_cpu_capabilities *__always_unused p)
1162 {
1163 	write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
1164 	isb();
1165 }
1166 
1167 void __init sve_setup(void)
1168 {
1169 	struct vl_info *info = &vl_info[ARM64_VEC_SVE];
1170 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1171 	unsigned long b;
1172 	int max_bit;
1173 
1174 	if (!cpus_have_cap(ARM64_SVE))
1175 		return;
1176 
1177 	/*
1178 	 * The SVE architecture mandates support for 128-bit vectors,
1179 	 * so sve_vq_map must have at least SVE_VQ_MIN set.
1180 	 * If something went wrong, at least try to patch it up:
1181 	 */
1182 	if (WARN_ON(!test_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map)))
1183 		set_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map);
1184 
1185 	max_bit = find_first_bit(info->vq_map, SVE_VQ_MAX);
1186 	info->max_vl = sve_vl_from_vq(__bit_to_vq(max_bit));
1187 
1188 	/*
1189 	 * For the default VL, pick the maximum supported value <= 64.
1190 	 * VL == 64 is guaranteed not to grow the signal frame.
1191 	 */
1192 	set_sve_default_vl(find_supported_vector_length(ARM64_VEC_SVE, 64));
1193 
1194 	bitmap_andnot(tmp_map, info->vq_partial_map, info->vq_map,
1195 		      SVE_VQ_MAX);
1196 
1197 	b = find_last_bit(tmp_map, SVE_VQ_MAX);
1198 	if (b >= SVE_VQ_MAX)
1199 		/* No non-virtualisable VLs found */
1200 		info->max_virtualisable_vl = SVE_VQ_MAX;
1201 	else if (WARN_ON(b == SVE_VQ_MAX - 1))
1202 		/* No virtualisable VLs?  This is architecturally forbidden. */
1203 		info->max_virtualisable_vl = SVE_VQ_MIN;
1204 	else /* b + 1 < SVE_VQ_MAX */
1205 		info->max_virtualisable_vl = sve_vl_from_vq(__bit_to_vq(b + 1));
1206 
1207 	if (info->max_virtualisable_vl > info->max_vl)
1208 		info->max_virtualisable_vl = info->max_vl;
1209 
1210 	pr_info("%s: maximum available vector length %u bytes per vector\n",
1211 		info->name, info->max_vl);
1212 	pr_info("%s: default vector length %u bytes per vector\n",
1213 		info->name, get_sve_default_vl());
1214 
1215 	/* KVM decides whether to support mismatched systems. Just warn here: */
1216 	if (sve_max_virtualisable_vl() < sve_max_vl())
1217 		pr_warn("%s: unvirtualisable vector lengths present\n",
1218 			info->name);
1219 
1220 	sve_efi_setup();
1221 }
1222 
1223 /*
1224  * Called from the put_task_struct() path, which cannot get here
1225  * unless dead_task is really dead and not schedulable.
1226  */
1227 void fpsimd_release_task(struct task_struct *dead_task)
1228 {
1229 	__sve_free(dead_task);
1230 	sme_free(dead_task);
1231 }
1232 
1233 #endif /* CONFIG_ARM64_SVE */
1234 
1235 #ifdef CONFIG_ARM64_SME
1236 
1237 /*
1238  * Ensure that task->thread.sme_state is allocated and sufficiently large.
1239  *
1240  * This function should be used only in preparation for replacing
1241  * task->thread.sme_state with new data.  The memory is always zeroed
1242  * here to prevent stale data from showing through: this is done in
1243  * the interest of testability and predictability, the architecture
1244  * guarantees that when ZA is enabled it will be zeroed.
1245  */
1246 void sme_alloc(struct task_struct *task, bool flush)
1247 {
1248 	if (task->thread.sme_state && flush) {
1249 		memset(task->thread.sme_state, 0, sme_state_size(task));
1250 		return;
1251 	}
1252 
1253 	/* This could potentially be up to 64K. */
1254 	task->thread.sme_state =
1255 		kzalloc(sme_state_size(task), GFP_KERNEL);
1256 }
1257 
1258 static void sme_free(struct task_struct *task)
1259 {
1260 	kfree(task->thread.sme_state);
1261 	task->thread.sme_state = NULL;
1262 }
1263 
1264 void cpu_enable_sme(const struct arm64_cpu_capabilities *__always_unused p)
1265 {
1266 	/* Set priority for all PEs to architecturally defined minimum */
1267 	write_sysreg_s(read_sysreg_s(SYS_SMPRI_EL1) & ~SMPRI_EL1_PRIORITY_MASK,
1268 		       SYS_SMPRI_EL1);
1269 
1270 	/* Allow SME in kernel */
1271 	write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_SMEN_EL1EN, CPACR_EL1);
1272 	isb();
1273 
1274 	/* Allow EL0 to access TPIDR2 */
1275 	write_sysreg(read_sysreg(SCTLR_EL1) | SCTLR_ELx_ENTP2, SCTLR_EL1);
1276 	isb();
1277 }
1278 
1279 void cpu_enable_sme2(const struct arm64_cpu_capabilities *__always_unused p)
1280 {
1281 	/* This must be enabled after SME */
1282 	BUILD_BUG_ON(ARM64_SME2 <= ARM64_SME);
1283 
1284 	/* Allow use of ZT0 */
1285 	write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_EZT0_MASK,
1286 		       SYS_SMCR_EL1);
1287 }
1288 
1289 void cpu_enable_fa64(const struct arm64_cpu_capabilities *__always_unused p)
1290 {
1291 	/* This must be enabled after SME */
1292 	BUILD_BUG_ON(ARM64_SME_FA64 <= ARM64_SME);
1293 
1294 	/* Allow use of FA64 */
1295 	write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_FA64_MASK,
1296 		       SYS_SMCR_EL1);
1297 }
1298 
1299 void __init sme_setup(void)
1300 {
1301 	struct vl_info *info = &vl_info[ARM64_VEC_SME];
1302 	int min_bit, max_bit;
1303 
1304 	if (!cpus_have_cap(ARM64_SME))
1305 		return;
1306 
1307 	/*
1308 	 * SME doesn't require any particular vector length be
1309 	 * supported but it does require at least one.  We should have
1310 	 * disabled the feature entirely while bringing up CPUs but
1311 	 * let's double check here.  The bitmap is SVE_VQ_MAP sized for
1312 	 * sharing with SVE.
1313 	 */
1314 	WARN_ON(bitmap_empty(info->vq_map, SVE_VQ_MAX));
1315 
1316 	min_bit = find_last_bit(info->vq_map, SVE_VQ_MAX);
1317 	info->min_vl = sve_vl_from_vq(__bit_to_vq(min_bit));
1318 
1319 	max_bit = find_first_bit(info->vq_map, SVE_VQ_MAX);
1320 	info->max_vl = sve_vl_from_vq(__bit_to_vq(max_bit));
1321 
1322 	WARN_ON(info->min_vl > info->max_vl);
1323 
1324 	/*
1325 	 * For the default VL, pick the maximum supported value <= 32
1326 	 * (256 bits) if there is one since this is guaranteed not to
1327 	 * grow the signal frame when in streaming mode, otherwise the
1328 	 * minimum available VL will be used.
1329 	 */
1330 	set_sme_default_vl(find_supported_vector_length(ARM64_VEC_SME, 32));
1331 
1332 	pr_info("SME: minimum available vector length %u bytes per vector\n",
1333 		info->min_vl);
1334 	pr_info("SME: maximum available vector length %u bytes per vector\n",
1335 		info->max_vl);
1336 	pr_info("SME: default vector length %u bytes per vector\n",
1337 		get_sme_default_vl());
1338 }
1339 
1340 #endif /* CONFIG_ARM64_SME */
1341 
1342 static void sve_init_regs(void)
1343 {
1344 	/*
1345 	 * Convert the FPSIMD state to SVE, zeroing all the state that
1346 	 * is not shared with FPSIMD. If (as is likely) the current
1347 	 * state is live in the registers then do this there and
1348 	 * update our metadata for the current task including
1349 	 * disabling the trap, otherwise update our in-memory copy.
1350 	 * We are guaranteed to not be in streaming mode, we can only
1351 	 * take a SVE trap when not in streaming mode and we can't be
1352 	 * in streaming mode when taking a SME trap.
1353 	 */
1354 	if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1355 		unsigned long vq_minus_one =
1356 			sve_vq_from_vl(task_get_sve_vl(current)) - 1;
1357 		sve_set_vq(vq_minus_one);
1358 		sve_flush_live(true, vq_minus_one);
1359 		fpsimd_bind_task_to_cpu();
1360 	} else {
1361 		fpsimd_to_sve(current);
1362 		current->thread.fp_type = FP_STATE_SVE;
1363 	}
1364 }
1365 
1366 /*
1367  * Trapped SVE access
1368  *
1369  * Storage is allocated for the full SVE state, the current FPSIMD
1370  * register contents are migrated across, and the access trap is
1371  * disabled.
1372  *
1373  * TIF_SVE should be clear on entry: otherwise, fpsimd_restore_current_state()
1374  * would have disabled the SVE access trap for userspace during
1375  * ret_to_user, making an SVE access trap impossible in that case.
1376  */
1377 void do_sve_acc(unsigned long esr, struct pt_regs *regs)
1378 {
1379 	/* Even if we chose not to use SVE, the hardware could still trap: */
1380 	if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
1381 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1382 		return;
1383 	}
1384 
1385 	sve_alloc(current, true);
1386 	if (!current->thread.sve_state) {
1387 		force_sig(SIGKILL);
1388 		return;
1389 	}
1390 
1391 	get_cpu_fpsimd_context();
1392 
1393 	if (test_and_set_thread_flag(TIF_SVE))
1394 		WARN_ON(1); /* SVE access shouldn't have trapped */
1395 
1396 	/*
1397 	 * Even if the task can have used streaming mode we can only
1398 	 * generate SVE access traps in normal SVE mode and
1399 	 * transitioning out of streaming mode may discard any
1400 	 * streaming mode state.  Always clear the high bits to avoid
1401 	 * any potential errors tracking what is properly initialised.
1402 	 */
1403 	sve_init_regs();
1404 
1405 	put_cpu_fpsimd_context();
1406 }
1407 
1408 /*
1409  * Trapped SME access
1410  *
1411  * Storage is allocated for the full SVE and SME state, the current
1412  * FPSIMD register contents are migrated to SVE if SVE is not already
1413  * active, and the access trap is disabled.
1414  *
1415  * TIF_SME should be clear on entry: otherwise, fpsimd_restore_current_state()
1416  * would have disabled the SME access trap for userspace during
1417  * ret_to_user, making an SME access trap impossible in that case.
1418  */
1419 void do_sme_acc(unsigned long esr, struct pt_regs *regs)
1420 {
1421 	/* Even if we chose not to use SME, the hardware could still trap: */
1422 	if (unlikely(!system_supports_sme()) || WARN_ON(is_compat_task())) {
1423 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1424 		return;
1425 	}
1426 
1427 	/*
1428 	 * If this not a trap due to SME being disabled then something
1429 	 * is being used in the wrong mode, report as SIGILL.
1430 	 */
1431 	if (ESR_ELx_ISS(esr) != ESR_ELx_SME_ISS_SME_DISABLED) {
1432 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1433 		return;
1434 	}
1435 
1436 	sve_alloc(current, false);
1437 	sme_alloc(current, true);
1438 	if (!current->thread.sve_state || !current->thread.sme_state) {
1439 		force_sig(SIGKILL);
1440 		return;
1441 	}
1442 
1443 	get_cpu_fpsimd_context();
1444 
1445 	/* With TIF_SME userspace shouldn't generate any traps */
1446 	if (test_and_set_thread_flag(TIF_SME))
1447 		WARN_ON(1);
1448 
1449 	if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1450 		unsigned long vq_minus_one =
1451 			sve_vq_from_vl(task_get_sme_vl(current)) - 1;
1452 		sme_set_vq(vq_minus_one);
1453 
1454 		fpsimd_bind_task_to_cpu();
1455 	}
1456 
1457 	put_cpu_fpsimd_context();
1458 }
1459 
1460 /*
1461  * Trapped FP/ASIMD access.
1462  */
1463 void do_fpsimd_acc(unsigned long esr, struct pt_regs *regs)
1464 {
1465 	/* Even if we chose not to use FPSIMD, the hardware could still trap: */
1466 	if (!system_supports_fpsimd()) {
1467 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1468 		return;
1469 	}
1470 
1471 	/*
1472 	 * When FPSIMD is enabled, we should never take a trap unless something
1473 	 * has gone very wrong.
1474 	 */
1475 	BUG();
1476 }
1477 
1478 /*
1479  * Raise a SIGFPE for the current process.
1480  */
1481 void do_fpsimd_exc(unsigned long esr, struct pt_regs *regs)
1482 {
1483 	unsigned int si_code = FPE_FLTUNK;
1484 
1485 	if (esr & ESR_ELx_FP_EXC_TFV) {
1486 		if (esr & FPEXC_IOF)
1487 			si_code = FPE_FLTINV;
1488 		else if (esr & FPEXC_DZF)
1489 			si_code = FPE_FLTDIV;
1490 		else if (esr & FPEXC_OFF)
1491 			si_code = FPE_FLTOVF;
1492 		else if (esr & FPEXC_UFF)
1493 			si_code = FPE_FLTUND;
1494 		else if (esr & FPEXC_IXF)
1495 			si_code = FPE_FLTRES;
1496 	}
1497 
1498 	send_sig_fault(SIGFPE, si_code,
1499 		       (void __user *)instruction_pointer(regs),
1500 		       current);
1501 }
1502 
1503 void fpsimd_thread_switch(struct task_struct *next)
1504 {
1505 	bool wrong_task, wrong_cpu;
1506 
1507 	if (!system_supports_fpsimd())
1508 		return;
1509 
1510 	__get_cpu_fpsimd_context();
1511 
1512 	/* Save unsaved fpsimd state, if any: */
1513 	fpsimd_save();
1514 
1515 	/*
1516 	 * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's
1517 	 * state.  For kernel threads, FPSIMD registers are never loaded
1518 	 * and wrong_task and wrong_cpu will always be true.
1519 	 */
1520 	wrong_task = __this_cpu_read(fpsimd_last_state.st) !=
1521 					&next->thread.uw.fpsimd_state;
1522 	wrong_cpu = next->thread.fpsimd_cpu != smp_processor_id();
1523 
1524 	update_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE,
1525 			       wrong_task || wrong_cpu);
1526 
1527 	__put_cpu_fpsimd_context();
1528 }
1529 
1530 static void fpsimd_flush_thread_vl(enum vec_type type)
1531 {
1532 	int vl, supported_vl;
1533 
1534 	/*
1535 	 * Reset the task vector length as required.  This is where we
1536 	 * ensure that all user tasks have a valid vector length
1537 	 * configured: no kernel task can become a user task without
1538 	 * an exec and hence a call to this function.  By the time the
1539 	 * first call to this function is made, all early hardware
1540 	 * probing is complete, so __sve_default_vl should be valid.
1541 	 * If a bug causes this to go wrong, we make some noise and
1542 	 * try to fudge thread.sve_vl to a safe value here.
1543 	 */
1544 	vl = task_get_vl_onexec(current, type);
1545 	if (!vl)
1546 		vl = get_default_vl(type);
1547 
1548 	if (WARN_ON(!sve_vl_valid(vl)))
1549 		vl = vl_info[type].min_vl;
1550 
1551 	supported_vl = find_supported_vector_length(type, vl);
1552 	if (WARN_ON(supported_vl != vl))
1553 		vl = supported_vl;
1554 
1555 	task_set_vl(current, type, vl);
1556 
1557 	/*
1558 	 * If the task is not set to inherit, ensure that the vector
1559 	 * length will be reset by a subsequent exec:
1560 	 */
1561 	if (!test_thread_flag(vec_vl_inherit_flag(type)))
1562 		task_set_vl_onexec(current, type, 0);
1563 }
1564 
1565 void fpsimd_flush_thread(void)
1566 {
1567 	void *sve_state = NULL;
1568 	void *sme_state = NULL;
1569 
1570 	if (!system_supports_fpsimd())
1571 		return;
1572 
1573 	get_cpu_fpsimd_context();
1574 
1575 	fpsimd_flush_task_state(current);
1576 	memset(&current->thread.uw.fpsimd_state, 0,
1577 	       sizeof(current->thread.uw.fpsimd_state));
1578 
1579 	if (system_supports_sve()) {
1580 		clear_thread_flag(TIF_SVE);
1581 
1582 		/* Defer kfree() while in atomic context */
1583 		sve_state = current->thread.sve_state;
1584 		current->thread.sve_state = NULL;
1585 
1586 		fpsimd_flush_thread_vl(ARM64_VEC_SVE);
1587 	}
1588 
1589 	if (system_supports_sme()) {
1590 		clear_thread_flag(TIF_SME);
1591 
1592 		/* Defer kfree() while in atomic context */
1593 		sme_state = current->thread.sme_state;
1594 		current->thread.sme_state = NULL;
1595 
1596 		fpsimd_flush_thread_vl(ARM64_VEC_SME);
1597 		current->thread.svcr = 0;
1598 	}
1599 
1600 	current->thread.fp_type = FP_STATE_FPSIMD;
1601 
1602 	put_cpu_fpsimd_context();
1603 	kfree(sve_state);
1604 	kfree(sme_state);
1605 }
1606 
1607 /*
1608  * Save the userland FPSIMD state of 'current' to memory, but only if the state
1609  * currently held in the registers does in fact belong to 'current'
1610  */
1611 void fpsimd_preserve_current_state(void)
1612 {
1613 	if (!system_supports_fpsimd())
1614 		return;
1615 
1616 	get_cpu_fpsimd_context();
1617 	fpsimd_save();
1618 	put_cpu_fpsimd_context();
1619 }
1620 
1621 /*
1622  * Like fpsimd_preserve_current_state(), but ensure that
1623  * current->thread.uw.fpsimd_state is updated so that it can be copied to
1624  * the signal frame.
1625  */
1626 void fpsimd_signal_preserve_current_state(void)
1627 {
1628 	fpsimd_preserve_current_state();
1629 	if (test_thread_flag(TIF_SVE))
1630 		sve_to_fpsimd(current);
1631 }
1632 
1633 /*
1634  * Called by KVM when entering the guest.
1635  */
1636 void fpsimd_kvm_prepare(void)
1637 {
1638 	if (!system_supports_sve())
1639 		return;
1640 
1641 	/*
1642 	 * KVM does not save host SVE state since we can only enter
1643 	 * the guest from a syscall so the ABI means that only the
1644 	 * non-saved SVE state needs to be saved.  If we have left
1645 	 * SVE enabled for performance reasons then update the task
1646 	 * state to be FPSIMD only.
1647 	 */
1648 	get_cpu_fpsimd_context();
1649 
1650 	if (test_and_clear_thread_flag(TIF_SVE)) {
1651 		sve_to_fpsimd(current);
1652 		current->thread.fp_type = FP_STATE_FPSIMD;
1653 	}
1654 
1655 	put_cpu_fpsimd_context();
1656 }
1657 
1658 /*
1659  * Associate current's FPSIMD context with this cpu
1660  * The caller must have ownership of the cpu FPSIMD context before calling
1661  * this function.
1662  */
1663 static void fpsimd_bind_task_to_cpu(void)
1664 {
1665 	struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state);
1666 
1667 	WARN_ON(!system_supports_fpsimd());
1668 	last->st = &current->thread.uw.fpsimd_state;
1669 	last->sve_state = current->thread.sve_state;
1670 	last->sme_state = current->thread.sme_state;
1671 	last->sve_vl = task_get_sve_vl(current);
1672 	last->sme_vl = task_get_sme_vl(current);
1673 	last->svcr = &current->thread.svcr;
1674 	last->fp_type = &current->thread.fp_type;
1675 	last->to_save = FP_STATE_CURRENT;
1676 	current->thread.fpsimd_cpu = smp_processor_id();
1677 
1678 	/*
1679 	 * Toggle SVE and SME trapping for userspace if needed, these
1680 	 * are serialsied by ret_to_user().
1681 	 */
1682 	if (system_supports_sme()) {
1683 		if (test_thread_flag(TIF_SME))
1684 			sme_user_enable();
1685 		else
1686 			sme_user_disable();
1687 	}
1688 
1689 	if (system_supports_sve()) {
1690 		if (test_thread_flag(TIF_SVE))
1691 			sve_user_enable();
1692 		else
1693 			sve_user_disable();
1694 	}
1695 }
1696 
1697 void fpsimd_bind_state_to_cpu(struct cpu_fp_state *state)
1698 {
1699 	struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state);
1700 
1701 	WARN_ON(!system_supports_fpsimd());
1702 	WARN_ON(!in_softirq() && !irqs_disabled());
1703 
1704 	*last = *state;
1705 }
1706 
1707 /*
1708  * Load the userland FPSIMD state of 'current' from memory, but only if the
1709  * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1710  * state of 'current'.  This is called when we are preparing to return to
1711  * userspace to ensure that userspace sees a good register state.
1712  */
1713 void fpsimd_restore_current_state(void)
1714 {
1715 	/*
1716 	 * TIF_FOREIGN_FPSTATE is set on the init task and copied by
1717 	 * arch_dup_task_struct() regardless of whether FP/SIMD is detected.
1718 	 * Thus user threads can have this set even when FP/SIMD hasn't been
1719 	 * detected.
1720 	 *
1721 	 * When FP/SIMD is detected, begin_new_exec() will set
1722 	 * TIF_FOREIGN_FPSTATE via flush_thread() -> fpsimd_flush_thread(),
1723 	 * and fpsimd_thread_switch() will set TIF_FOREIGN_FPSTATE when
1724 	 * switching tasks. We detect FP/SIMD before we exec the first user
1725 	 * process, ensuring this has TIF_FOREIGN_FPSTATE set and
1726 	 * do_notify_resume() will call fpsimd_restore_current_state() to
1727 	 * install the user FP/SIMD context.
1728 	 *
1729 	 * When FP/SIMD is not detected, nothing else will clear or set
1730 	 * TIF_FOREIGN_FPSTATE prior to the first return to userspace, and
1731 	 * we must clear TIF_FOREIGN_FPSTATE to avoid do_notify_resume()
1732 	 * looping forever calling fpsimd_restore_current_state().
1733 	 */
1734 	if (!system_supports_fpsimd()) {
1735 		clear_thread_flag(TIF_FOREIGN_FPSTATE);
1736 		return;
1737 	}
1738 
1739 	get_cpu_fpsimd_context();
1740 
1741 	if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1742 		task_fpsimd_load();
1743 		fpsimd_bind_task_to_cpu();
1744 	}
1745 
1746 	put_cpu_fpsimd_context();
1747 }
1748 
1749 /*
1750  * Load an updated userland FPSIMD state for 'current' from memory and set the
1751  * flag that indicates that the FPSIMD register contents are the most recent
1752  * FPSIMD state of 'current'. This is used by the signal code to restore the
1753  * register state when returning from a signal handler in FPSIMD only cases,
1754  * any SVE context will be discarded.
1755  */
1756 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1757 {
1758 	if (WARN_ON(!system_supports_fpsimd()))
1759 		return;
1760 
1761 	get_cpu_fpsimd_context();
1762 
1763 	current->thread.uw.fpsimd_state = *state;
1764 	if (test_thread_flag(TIF_SVE))
1765 		fpsimd_to_sve(current);
1766 
1767 	task_fpsimd_load();
1768 	fpsimd_bind_task_to_cpu();
1769 
1770 	clear_thread_flag(TIF_FOREIGN_FPSTATE);
1771 
1772 	put_cpu_fpsimd_context();
1773 }
1774 
1775 /*
1776  * Invalidate live CPU copies of task t's FPSIMD state
1777  *
1778  * This function may be called with preemption enabled.  The barrier()
1779  * ensures that the assignment to fpsimd_cpu is visible to any
1780  * preemption/softirq that could race with set_tsk_thread_flag(), so
1781  * that TIF_FOREIGN_FPSTATE cannot be spuriously re-cleared.
1782  *
1783  * The final barrier ensures that TIF_FOREIGN_FPSTATE is seen set by any
1784  * subsequent code.
1785  */
1786 void fpsimd_flush_task_state(struct task_struct *t)
1787 {
1788 	t->thread.fpsimd_cpu = NR_CPUS;
1789 	/*
1790 	 * If we don't support fpsimd, bail out after we have
1791 	 * reset the fpsimd_cpu for this task and clear the
1792 	 * FPSTATE.
1793 	 */
1794 	if (!system_supports_fpsimd())
1795 		return;
1796 	barrier();
1797 	set_tsk_thread_flag(t, TIF_FOREIGN_FPSTATE);
1798 
1799 	barrier();
1800 }
1801 
1802 /*
1803  * Invalidate any task's FPSIMD state that is present on this cpu.
1804  * The FPSIMD context should be acquired with get_cpu_fpsimd_context()
1805  * before calling this function.
1806  */
1807 static void fpsimd_flush_cpu_state(void)
1808 {
1809 	WARN_ON(!system_supports_fpsimd());
1810 	__this_cpu_write(fpsimd_last_state.st, NULL);
1811 
1812 	/*
1813 	 * Leaving streaming mode enabled will cause issues for any kernel
1814 	 * NEON and leaving streaming mode or ZA enabled may increase power
1815 	 * consumption.
1816 	 */
1817 	if (system_supports_sme())
1818 		sme_smstop();
1819 
1820 	set_thread_flag(TIF_FOREIGN_FPSTATE);
1821 }
1822 
1823 /*
1824  * Save the FPSIMD state to memory and invalidate cpu view.
1825  * This function must be called with preemption disabled.
1826  */
1827 void fpsimd_save_and_flush_cpu_state(void)
1828 {
1829 	if (!system_supports_fpsimd())
1830 		return;
1831 	WARN_ON(preemptible());
1832 	__get_cpu_fpsimd_context();
1833 	fpsimd_save();
1834 	fpsimd_flush_cpu_state();
1835 	__put_cpu_fpsimd_context();
1836 }
1837 
1838 #ifdef CONFIG_KERNEL_MODE_NEON
1839 
1840 /*
1841  * Kernel-side NEON support functions
1842  */
1843 
1844 /*
1845  * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1846  * context
1847  *
1848  * Must not be called unless may_use_simd() returns true.
1849  * Task context in the FPSIMD registers is saved back to memory as necessary.
1850  *
1851  * A matching call to kernel_neon_end() must be made before returning from the
1852  * calling context.
1853  *
1854  * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1855  * called.
1856  */
1857 void kernel_neon_begin(void)
1858 {
1859 	if (WARN_ON(!system_supports_fpsimd()))
1860 		return;
1861 
1862 	BUG_ON(!may_use_simd());
1863 
1864 	get_cpu_fpsimd_context();
1865 
1866 	/* Save unsaved fpsimd state, if any: */
1867 	fpsimd_save();
1868 
1869 	/* Invalidate any task state remaining in the fpsimd regs: */
1870 	fpsimd_flush_cpu_state();
1871 }
1872 EXPORT_SYMBOL_GPL(kernel_neon_begin);
1873 
1874 /*
1875  * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1876  *
1877  * Must be called from a context in which kernel_neon_begin() was previously
1878  * called, with no call to kernel_neon_end() in the meantime.
1879  *
1880  * The caller must not use the FPSIMD registers after this function is called,
1881  * unless kernel_neon_begin() is called again in the meantime.
1882  */
1883 void kernel_neon_end(void)
1884 {
1885 	if (!system_supports_fpsimd())
1886 		return;
1887 
1888 	put_cpu_fpsimd_context();
1889 }
1890 EXPORT_SYMBOL_GPL(kernel_neon_end);
1891 
1892 #ifdef CONFIG_EFI
1893 
1894 static DEFINE_PER_CPU(struct user_fpsimd_state, efi_fpsimd_state);
1895 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1896 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1897 static DEFINE_PER_CPU(bool, efi_sm_state);
1898 
1899 /*
1900  * EFI runtime services support functions
1901  *
1902  * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1903  * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1904  * is always used rather than being an optional accelerator.
1905  *
1906  * These functions provide the necessary support for ensuring FPSIMD
1907  * save/restore in the contexts from which EFI is used.
1908  *
1909  * Do not use them for any other purpose -- if tempted to do so, you are
1910  * either doing something wrong or you need to propose some refactoring.
1911  */
1912 
1913 /*
1914  * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1915  */
1916 void __efi_fpsimd_begin(void)
1917 {
1918 	if (!system_supports_fpsimd())
1919 		return;
1920 
1921 	WARN_ON(preemptible());
1922 
1923 	if (may_use_simd()) {
1924 		kernel_neon_begin();
1925 	} else {
1926 		/*
1927 		 * If !efi_sve_state, SVE can't be in use yet and doesn't need
1928 		 * preserving:
1929 		 */
1930 		if (system_supports_sve() && likely(efi_sve_state)) {
1931 			char *sve_state = this_cpu_ptr(efi_sve_state);
1932 			bool ffr = true;
1933 			u64 svcr;
1934 
1935 			__this_cpu_write(efi_sve_state_used, true);
1936 
1937 			if (system_supports_sme()) {
1938 				svcr = read_sysreg_s(SYS_SVCR);
1939 
1940 				__this_cpu_write(efi_sm_state,
1941 						 svcr & SVCR_SM_MASK);
1942 
1943 				/*
1944 				 * Unless we have FA64 FFR does not
1945 				 * exist in streaming mode.
1946 				 */
1947 				if (!system_supports_fa64())
1948 					ffr = !(svcr & SVCR_SM_MASK);
1949 			}
1950 
1951 			sve_save_state(sve_state + sve_ffr_offset(sve_max_vl()),
1952 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
1953 				       ffr);
1954 
1955 			if (system_supports_sme())
1956 				sysreg_clear_set_s(SYS_SVCR,
1957 						   SVCR_SM_MASK, 0);
1958 
1959 		} else {
1960 			fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
1961 		}
1962 
1963 		__this_cpu_write(efi_fpsimd_state_used, true);
1964 	}
1965 }
1966 
1967 /*
1968  * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
1969  */
1970 void __efi_fpsimd_end(void)
1971 {
1972 	if (!system_supports_fpsimd())
1973 		return;
1974 
1975 	if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
1976 		kernel_neon_end();
1977 	} else {
1978 		if (system_supports_sve() &&
1979 		    likely(__this_cpu_read(efi_sve_state_used))) {
1980 			char const *sve_state = this_cpu_ptr(efi_sve_state);
1981 			bool ffr = true;
1982 
1983 			/*
1984 			 * Restore streaming mode; EFI calls are
1985 			 * normal function calls so should not return in
1986 			 * streaming mode.
1987 			 */
1988 			if (system_supports_sme()) {
1989 				if (__this_cpu_read(efi_sm_state)) {
1990 					sysreg_clear_set_s(SYS_SVCR,
1991 							   0,
1992 							   SVCR_SM_MASK);
1993 
1994 					/*
1995 					 * Unless we have FA64 FFR does not
1996 					 * exist in streaming mode.
1997 					 */
1998 					if (!system_supports_fa64())
1999 						ffr = false;
2000 				}
2001 			}
2002 
2003 			sve_load_state(sve_state + sve_ffr_offset(sve_max_vl()),
2004 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
2005 				       ffr);
2006 
2007 			__this_cpu_write(efi_sve_state_used, false);
2008 		} else {
2009 			fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
2010 		}
2011 	}
2012 }
2013 
2014 #endif /* CONFIG_EFI */
2015 
2016 #endif /* CONFIG_KERNEL_MODE_NEON */
2017 
2018 #ifdef CONFIG_CPU_PM
2019 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
2020 				  unsigned long cmd, void *v)
2021 {
2022 	switch (cmd) {
2023 	case CPU_PM_ENTER:
2024 		fpsimd_save_and_flush_cpu_state();
2025 		break;
2026 	case CPU_PM_EXIT:
2027 		break;
2028 	case CPU_PM_ENTER_FAILED:
2029 	default:
2030 		return NOTIFY_DONE;
2031 	}
2032 	return NOTIFY_OK;
2033 }
2034 
2035 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
2036 	.notifier_call = fpsimd_cpu_pm_notifier,
2037 };
2038 
2039 static void __init fpsimd_pm_init(void)
2040 {
2041 	cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
2042 }
2043 
2044 #else
2045 static inline void fpsimd_pm_init(void) { }
2046 #endif /* CONFIG_CPU_PM */
2047 
2048 #ifdef CONFIG_HOTPLUG_CPU
2049 static int fpsimd_cpu_dead(unsigned int cpu)
2050 {
2051 	per_cpu(fpsimd_last_state.st, cpu) = NULL;
2052 	return 0;
2053 }
2054 
2055 static inline void fpsimd_hotplug_init(void)
2056 {
2057 	cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
2058 				  NULL, fpsimd_cpu_dead);
2059 }
2060 
2061 #else
2062 static inline void fpsimd_hotplug_init(void) { }
2063 #endif
2064 
2065 void cpu_enable_fpsimd(const struct arm64_cpu_capabilities *__always_unused p)
2066 {
2067 	unsigned long enable = CPACR_EL1_FPEN_EL1EN | CPACR_EL1_FPEN_EL0EN;
2068 	write_sysreg(read_sysreg(CPACR_EL1) | enable, CPACR_EL1);
2069 	isb();
2070 }
2071 
2072 /*
2073  * FP/SIMD support code initialisation.
2074  */
2075 static int __init fpsimd_init(void)
2076 {
2077 	if (cpu_have_named_feature(FP)) {
2078 		fpsimd_pm_init();
2079 		fpsimd_hotplug_init();
2080 	} else {
2081 		pr_notice("Floating-point is not implemented\n");
2082 	}
2083 
2084 	if (!cpu_have_named_feature(ASIMD))
2085 		pr_notice("Advanced SIMD is not implemented\n");
2086 
2087 
2088 	sve_sysctl_init();
2089 	sme_sysctl_init();
2090 
2091 	return 0;
2092 }
2093 core_initcall(fpsimd_init);
2094