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