xref: /openbmc/linux/arch/arm64/kernel/fpsimd.c (revision 0a94608f)
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 struct fpsimd_last_state_struct {
122 	struct user_fpsimd_state *st;
123 	void *sve_state;
124 	unsigned int sve_vl;
125 };
126 
127 static DEFINE_PER_CPU(struct fpsimd_last_state_struct, fpsimd_last_state);
128 
129 __ro_after_init struct vl_info vl_info[ARM64_VEC_MAX] = {
130 #ifdef CONFIG_ARM64_SVE
131 	[ARM64_VEC_SVE] = {
132 		.type			= ARM64_VEC_SVE,
133 		.name			= "SVE",
134 		.min_vl			= SVE_VL_MIN,
135 		.max_vl			= SVE_VL_MIN,
136 		.max_virtualisable_vl	= SVE_VL_MIN,
137 	},
138 #endif
139 };
140 
141 static unsigned int vec_vl_inherit_flag(enum vec_type type)
142 {
143 	switch (type) {
144 	case ARM64_VEC_SVE:
145 		return TIF_SVE_VL_INHERIT;
146 	default:
147 		WARN_ON_ONCE(1);
148 		return 0;
149 	}
150 }
151 
152 struct vl_config {
153 	int __default_vl;		/* Default VL for tasks */
154 };
155 
156 static struct vl_config vl_config[ARM64_VEC_MAX];
157 
158 static inline int get_default_vl(enum vec_type type)
159 {
160 	return READ_ONCE(vl_config[type].__default_vl);
161 }
162 
163 #ifdef CONFIG_ARM64_SVE
164 
165 static inline int get_sve_default_vl(void)
166 {
167 	return get_default_vl(ARM64_VEC_SVE);
168 }
169 
170 static inline void set_default_vl(enum vec_type type, int val)
171 {
172 	WRITE_ONCE(vl_config[type].__default_vl, val);
173 }
174 
175 static inline void set_sve_default_vl(int val)
176 {
177 	set_default_vl(ARM64_VEC_SVE, val);
178 }
179 
180 static void __percpu *efi_sve_state;
181 
182 #else /* ! CONFIG_ARM64_SVE */
183 
184 /* Dummy declaration for code that will be optimised out: */
185 extern void __percpu *efi_sve_state;
186 
187 #endif /* ! CONFIG_ARM64_SVE */
188 
189 DEFINE_PER_CPU(bool, fpsimd_context_busy);
190 EXPORT_PER_CPU_SYMBOL(fpsimd_context_busy);
191 
192 static void fpsimd_bind_task_to_cpu(void);
193 
194 static void __get_cpu_fpsimd_context(void)
195 {
196 	bool busy = __this_cpu_xchg(fpsimd_context_busy, true);
197 
198 	WARN_ON(busy);
199 }
200 
201 /*
202  * Claim ownership of the CPU FPSIMD context for use by the calling context.
203  *
204  * The caller may freely manipulate the FPSIMD context metadata until
205  * put_cpu_fpsimd_context() is called.
206  *
207  * The double-underscore version must only be called if you know the task
208  * can't be preempted.
209  */
210 static void get_cpu_fpsimd_context(void)
211 {
212 	local_bh_disable();
213 	__get_cpu_fpsimd_context();
214 }
215 
216 static void __put_cpu_fpsimd_context(void)
217 {
218 	bool busy = __this_cpu_xchg(fpsimd_context_busy, false);
219 
220 	WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */
221 }
222 
223 /*
224  * Release the CPU FPSIMD context.
225  *
226  * Must be called from a context in which get_cpu_fpsimd_context() was
227  * previously called, with no call to put_cpu_fpsimd_context() in the
228  * meantime.
229  */
230 static void put_cpu_fpsimd_context(void)
231 {
232 	__put_cpu_fpsimd_context();
233 	local_bh_enable();
234 }
235 
236 static bool have_cpu_fpsimd_context(void)
237 {
238 	return !preemptible() && __this_cpu_read(fpsimd_context_busy);
239 }
240 
241 /*
242  * Call __sve_free() directly only if you know task can't be scheduled
243  * or preempted.
244  */
245 static void __sve_free(struct task_struct *task)
246 {
247 	kfree(task->thread.sve_state);
248 	task->thread.sve_state = NULL;
249 }
250 
251 static void sve_free(struct task_struct *task)
252 {
253 	WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
254 
255 	__sve_free(task);
256 }
257 
258 unsigned int task_get_vl(const struct task_struct *task, enum vec_type type)
259 {
260 	return task->thread.vl[type];
261 }
262 
263 void task_set_vl(struct task_struct *task, enum vec_type type,
264 		 unsigned long vl)
265 {
266 	task->thread.vl[type] = vl;
267 }
268 
269 unsigned int task_get_vl_onexec(const struct task_struct *task,
270 				enum vec_type type)
271 {
272 	return task->thread.vl_onexec[type];
273 }
274 
275 void task_set_vl_onexec(struct task_struct *task, enum vec_type type,
276 			unsigned long vl)
277 {
278 	task->thread.vl_onexec[type] = vl;
279 }
280 
281 /*
282  * TIF_SVE controls whether a task can use SVE without trapping while
283  * in userspace, and also the way a task's FPSIMD/SVE state is stored
284  * in thread_struct.
285  *
286  * The kernel uses this flag to track whether a user task is actively
287  * using SVE, and therefore whether full SVE register state needs to
288  * be tracked.  If not, the cheaper FPSIMD context handling code can
289  * be used instead of the more costly SVE equivalents.
290  *
291  *  * TIF_SVE set:
292  *
293  *    The task can execute SVE instructions while in userspace without
294  *    trapping to the kernel.
295  *
296  *    When stored, Z0-Z31 (incorporating Vn in bits[127:0] or the
297  *    corresponding Zn), P0-P15 and FFR are encoded in in
298  *    task->thread.sve_state, formatted appropriately for vector
299  *    length task->thread.sve_vl.
300  *
301  *    task->thread.sve_state must point to a valid buffer at least
302  *    sve_state_size(task) bytes in size.
303  *
304  *    During any syscall, the kernel may optionally clear TIF_SVE and
305  *    discard the vector state except for the FPSIMD subset.
306  *
307  *  * TIF_SVE clear:
308  *
309  *    An attempt by the user task to execute an SVE instruction causes
310  *    do_sve_acc() to be called, which does some preparation and then
311  *    sets TIF_SVE.
312  *
313  *    When stored, FPSIMD registers V0-V31 are encoded in
314  *    task->thread.uw.fpsimd_state; bits [max : 128] for each of Z0-Z31 are
315  *    logically zero but not stored anywhere; P0-P15 and FFR are not
316  *    stored and have unspecified values from userspace's point of
317  *    view.  For hygiene purposes, the kernel zeroes them on next use,
318  *    but userspace is discouraged from relying on this.
319  *
320  *    task->thread.sve_state does not need to be non-NULL, valid or any
321  *    particular size: it must not be dereferenced.
322  *
323  *  * FPSR and FPCR are always stored in task->thread.uw.fpsimd_state
324  *    irrespective of whether TIF_SVE is clear or set, since these are
325  *    not vector length dependent.
326  */
327 
328 /*
329  * Update current's FPSIMD/SVE registers from thread_struct.
330  *
331  * This function should be called only when the FPSIMD/SVE state in
332  * thread_struct is known to be up to date, when preparing to enter
333  * userspace.
334  */
335 static void task_fpsimd_load(void)
336 {
337 	WARN_ON(!system_supports_fpsimd());
338 	WARN_ON(!have_cpu_fpsimd_context());
339 
340 	if (IS_ENABLED(CONFIG_ARM64_SVE) && test_thread_flag(TIF_SVE)) {
341 		sve_set_vq(sve_vq_from_vl(task_get_sve_vl(current)) - 1);
342 		sve_load_state(sve_pffr(&current->thread),
343 			       &current->thread.uw.fpsimd_state.fpsr, true);
344 	} else {
345 		fpsimd_load_state(&current->thread.uw.fpsimd_state);
346 	}
347 }
348 
349 /*
350  * Ensure FPSIMD/SVE storage in memory for the loaded context is up to
351  * date with respect to the CPU registers. Note carefully that the
352  * current context is the context last bound to the CPU stored in
353  * last, if KVM is involved this may be the guest VM context rather
354  * than the host thread for the VM pointed to by current. This means
355  * that we must always reference the state storage via last rather
356  * than via current, other than the TIF_ flags which KVM will
357  * carefully maintain for us.
358  */
359 static void fpsimd_save(void)
360 {
361 	struct fpsimd_last_state_struct const *last =
362 		this_cpu_ptr(&fpsimd_last_state);
363 	/* set by fpsimd_bind_task_to_cpu() or fpsimd_bind_state_to_cpu() */
364 
365 	WARN_ON(!system_supports_fpsimd());
366 	WARN_ON(!have_cpu_fpsimd_context());
367 
368 	if (test_thread_flag(TIF_FOREIGN_FPSTATE))
369 		return;
370 
371 	if (IS_ENABLED(CONFIG_ARM64_SVE) &&
372 	    test_thread_flag(TIF_SVE)) {
373 		if (WARN_ON(sve_get_vl() != last->sve_vl)) {
374 			/*
375 			 * Can't save the user regs, so current would
376 			 * re-enter user with corrupt state.
377 			 * There's no way to recover, so kill it:
378 			 */
379 			force_signal_inject(SIGKILL, SI_KERNEL, 0, 0);
380 			return;
381 		}
382 
383 		sve_save_state((char *)last->sve_state +
384 					sve_ffr_offset(last->sve_vl),
385 			       &last->st->fpsr, true);
386 	} else {
387 		fpsimd_save_state(last->st);
388 	}
389 }
390 
391 /*
392  * All vector length selection from userspace comes through here.
393  * We're on a slow path, so some sanity-checks are included.
394  * If things go wrong there's a bug somewhere, but try to fall back to a
395  * safe choice.
396  */
397 static unsigned int find_supported_vector_length(enum vec_type type,
398 						 unsigned int vl)
399 {
400 	struct vl_info *info = &vl_info[type];
401 	int bit;
402 	int max_vl = info->max_vl;
403 
404 	if (WARN_ON(!sve_vl_valid(vl)))
405 		vl = info->min_vl;
406 
407 	if (WARN_ON(!sve_vl_valid(max_vl)))
408 		max_vl = info->min_vl;
409 
410 	if (vl > max_vl)
411 		vl = max_vl;
412 
413 	bit = find_next_bit(info->vq_map, SVE_VQ_MAX,
414 			    __vq_to_bit(sve_vq_from_vl(vl)));
415 	return sve_vl_from_vq(__bit_to_vq(bit));
416 }
417 
418 #if defined(CONFIG_ARM64_SVE) && defined(CONFIG_SYSCTL)
419 
420 static int vec_proc_do_default_vl(struct ctl_table *table, int write,
421 				  void *buffer, size_t *lenp, loff_t *ppos)
422 {
423 	struct vl_info *info = table->extra1;
424 	enum vec_type type = info->type;
425 	int ret;
426 	int vl = get_default_vl(type);
427 	struct ctl_table tmp_table = {
428 		.data = &vl,
429 		.maxlen = sizeof(vl),
430 	};
431 
432 	ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
433 	if (ret || !write)
434 		return ret;
435 
436 	/* Writing -1 has the special meaning "set to max": */
437 	if (vl == -1)
438 		vl = info->max_vl;
439 
440 	if (!sve_vl_valid(vl))
441 		return -EINVAL;
442 
443 	set_default_vl(type, find_supported_vector_length(type, vl));
444 	return 0;
445 }
446 
447 static struct ctl_table sve_default_vl_table[] = {
448 	{
449 		.procname	= "sve_default_vector_length",
450 		.mode		= 0644,
451 		.proc_handler	= vec_proc_do_default_vl,
452 		.extra1		= &vl_info[ARM64_VEC_SVE],
453 	},
454 	{ }
455 };
456 
457 static int __init sve_sysctl_init(void)
458 {
459 	if (system_supports_sve())
460 		if (!register_sysctl("abi", sve_default_vl_table))
461 			return -EINVAL;
462 
463 	return 0;
464 }
465 
466 #else /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
467 static int __init sve_sysctl_init(void) { return 0; }
468 #endif /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
469 
470 #define ZREG(sve_state, vq, n) ((char *)(sve_state) +		\
471 	(SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
472 
473 #ifdef CONFIG_CPU_BIG_ENDIAN
474 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
475 {
476 	u64 a = swab64(x);
477 	u64 b = swab64(x >> 64);
478 
479 	return ((__uint128_t)a << 64) | b;
480 }
481 #else
482 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
483 {
484 	return x;
485 }
486 #endif
487 
488 #define arm64_le128_to_cpu(x) arm64_cpu_to_le128(x)
489 
490 static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst,
491 			    unsigned int vq)
492 {
493 	unsigned int i;
494 	__uint128_t *p;
495 
496 	for (i = 0; i < SVE_NUM_ZREGS; ++i) {
497 		p = (__uint128_t *)ZREG(sst, vq, i);
498 		*p = arm64_cpu_to_le128(fst->vregs[i]);
499 	}
500 }
501 
502 /*
503  * Transfer the FPSIMD state in task->thread.uw.fpsimd_state to
504  * task->thread.sve_state.
505  *
506  * Task can be a non-runnable task, or current.  In the latter case,
507  * the caller must have ownership of the cpu FPSIMD context before calling
508  * this function.
509  * task->thread.sve_state must point to at least sve_state_size(task)
510  * bytes of allocated kernel memory.
511  * task->thread.uw.fpsimd_state must be up to date before calling this
512  * function.
513  */
514 static void fpsimd_to_sve(struct task_struct *task)
515 {
516 	unsigned int vq;
517 	void *sst = task->thread.sve_state;
518 	struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
519 
520 	if (!system_supports_sve())
521 		return;
522 
523 	vq = sve_vq_from_vl(task_get_sve_vl(task));
524 	__fpsimd_to_sve(sst, fst, vq);
525 }
526 
527 /*
528  * Transfer the SVE state in task->thread.sve_state to
529  * task->thread.uw.fpsimd_state.
530  *
531  * Task can be a non-runnable task, or current.  In the latter case,
532  * the caller must have ownership of the cpu FPSIMD context before calling
533  * this function.
534  * task->thread.sve_state must point to at least sve_state_size(task)
535  * bytes of allocated kernel memory.
536  * task->thread.sve_state must be up to date before calling this function.
537  */
538 static void sve_to_fpsimd(struct task_struct *task)
539 {
540 	unsigned int vq;
541 	void const *sst = task->thread.sve_state;
542 	struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state;
543 	unsigned int i;
544 	__uint128_t const *p;
545 
546 	if (!system_supports_sve())
547 		return;
548 
549 	vq = sve_vq_from_vl(task_get_sve_vl(task));
550 	for (i = 0; i < SVE_NUM_ZREGS; ++i) {
551 		p = (__uint128_t const *)ZREG(sst, vq, i);
552 		fst->vregs[i] = arm64_le128_to_cpu(*p);
553 	}
554 }
555 
556 #ifdef CONFIG_ARM64_SVE
557 
558 /*
559  * Return how many bytes of memory are required to store the full SVE
560  * state for task, given task's currently configured vector length.
561  */
562 static size_t sve_state_size(struct task_struct const *task)
563 {
564 	return SVE_SIG_REGS_SIZE(sve_vq_from_vl(task_get_sve_vl(task)));
565 }
566 
567 /*
568  * Ensure that task->thread.sve_state is allocated and sufficiently large.
569  *
570  * This function should be used only in preparation for replacing
571  * task->thread.sve_state with new data.  The memory is always zeroed
572  * here to prevent stale data from showing through: this is done in
573  * the interest of testability and predictability: except in the
574  * do_sve_acc() case, there is no ABI requirement to hide stale data
575  * written previously be task.
576  */
577 void sve_alloc(struct task_struct *task)
578 {
579 	if (task->thread.sve_state) {
580 		memset(task->thread.sve_state, 0, sve_state_size(task));
581 		return;
582 	}
583 
584 	/* This is a small allocation (maximum ~8KB) and Should Not Fail. */
585 	task->thread.sve_state =
586 		kzalloc(sve_state_size(task), GFP_KERNEL);
587 }
588 
589 
590 /*
591  * Ensure that task->thread.sve_state is up to date with respect to
592  * the user task, irrespective of when SVE is in use or not.
593  *
594  * This should only be called by ptrace.  task must be non-runnable.
595  * task->thread.sve_state must point to at least sve_state_size(task)
596  * bytes of allocated kernel memory.
597  */
598 void fpsimd_sync_to_sve(struct task_struct *task)
599 {
600 	if (!test_tsk_thread_flag(task, TIF_SVE))
601 		fpsimd_to_sve(task);
602 }
603 
604 /*
605  * Ensure that task->thread.uw.fpsimd_state is up to date with respect to
606  * the user task, irrespective of whether SVE is in use or not.
607  *
608  * This should only be called by ptrace.  task must be non-runnable.
609  * task->thread.sve_state must point to at least sve_state_size(task)
610  * bytes of allocated kernel memory.
611  */
612 void sve_sync_to_fpsimd(struct task_struct *task)
613 {
614 	if (test_tsk_thread_flag(task, TIF_SVE))
615 		sve_to_fpsimd(task);
616 }
617 
618 /*
619  * Ensure that task->thread.sve_state is up to date with respect to
620  * the task->thread.uw.fpsimd_state.
621  *
622  * This should only be called by ptrace to merge new FPSIMD register
623  * values into a task for which SVE is currently active.
624  * task must be non-runnable.
625  * task->thread.sve_state must point to at least sve_state_size(task)
626  * bytes of allocated kernel memory.
627  * task->thread.uw.fpsimd_state must already have been initialised with
628  * the new FPSIMD register values to be merged in.
629  */
630 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
631 {
632 	unsigned int vq;
633 	void *sst = task->thread.sve_state;
634 	struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
635 
636 	if (!test_tsk_thread_flag(task, TIF_SVE))
637 		return;
638 
639 	vq = sve_vq_from_vl(task_get_sve_vl(task));
640 
641 	memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
642 	__fpsimd_to_sve(sst, fst, vq);
643 }
644 
645 int vec_set_vector_length(struct task_struct *task, enum vec_type type,
646 			  unsigned long vl, unsigned long flags)
647 {
648 	if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
649 				     PR_SVE_SET_VL_ONEXEC))
650 		return -EINVAL;
651 
652 	if (!sve_vl_valid(vl))
653 		return -EINVAL;
654 
655 	/*
656 	 * Clamp to the maximum vector length that VL-agnostic code
657 	 * can work with.  A flag may be assigned in the future to
658 	 * allow setting of larger vector lengths without confusing
659 	 * older software.
660 	 */
661 	if (vl > VL_ARCH_MAX)
662 		vl = VL_ARCH_MAX;
663 
664 	vl = find_supported_vector_length(type, vl);
665 
666 	if (flags & (PR_SVE_VL_INHERIT |
667 		     PR_SVE_SET_VL_ONEXEC))
668 		task_set_vl_onexec(task, type, vl);
669 	else
670 		/* Reset VL to system default on next exec: */
671 		task_set_vl_onexec(task, type, 0);
672 
673 	/* Only actually set the VL if not deferred: */
674 	if (flags & PR_SVE_SET_VL_ONEXEC)
675 		goto out;
676 
677 	if (vl == task_get_vl(task, type))
678 		goto out;
679 
680 	/*
681 	 * To ensure the FPSIMD bits of the SVE vector registers are preserved,
682 	 * write any live register state back to task_struct, and convert to a
683 	 * regular FPSIMD thread.  Since the vector length can only be changed
684 	 * with a syscall we can't be in streaming mode while reconfiguring.
685 	 */
686 	if (task == current) {
687 		get_cpu_fpsimd_context();
688 
689 		fpsimd_save();
690 	}
691 
692 	fpsimd_flush_task_state(task);
693 	if (test_and_clear_tsk_thread_flag(task, TIF_SVE))
694 		sve_to_fpsimd(task);
695 
696 	if (task == current)
697 		put_cpu_fpsimd_context();
698 
699 	/*
700 	 * Force reallocation of task SVE state to the correct size
701 	 * on next use:
702 	 */
703 	sve_free(task);
704 
705 	task_set_vl(task, type, vl);
706 
707 out:
708 	update_tsk_thread_flag(task, vec_vl_inherit_flag(type),
709 			       flags & PR_SVE_VL_INHERIT);
710 
711 	return 0;
712 }
713 
714 /*
715  * Encode the current vector length and flags for return.
716  * This is only required for prctl(): ptrace has separate fields.
717  * SVE and SME use the same bits for _ONEXEC and _INHERIT.
718  *
719  * flags are as for vec_set_vector_length().
720  */
721 static int vec_prctl_status(enum vec_type type, unsigned long flags)
722 {
723 	int ret;
724 
725 	if (flags & PR_SVE_SET_VL_ONEXEC)
726 		ret = task_get_vl_onexec(current, type);
727 	else
728 		ret = task_get_vl(current, type);
729 
730 	if (test_thread_flag(vec_vl_inherit_flag(type)))
731 		ret |= PR_SVE_VL_INHERIT;
732 
733 	return ret;
734 }
735 
736 /* PR_SVE_SET_VL */
737 int sve_set_current_vl(unsigned long arg)
738 {
739 	unsigned long vl, flags;
740 	int ret;
741 
742 	vl = arg & PR_SVE_VL_LEN_MASK;
743 	flags = arg & ~vl;
744 
745 	if (!system_supports_sve() || is_compat_task())
746 		return -EINVAL;
747 
748 	ret = vec_set_vector_length(current, ARM64_VEC_SVE, vl, flags);
749 	if (ret)
750 		return ret;
751 
752 	return vec_prctl_status(ARM64_VEC_SVE, flags);
753 }
754 
755 /* PR_SVE_GET_VL */
756 int sve_get_current_vl(void)
757 {
758 	if (!system_supports_sve() || is_compat_task())
759 		return -EINVAL;
760 
761 	return vec_prctl_status(ARM64_VEC_SVE, 0);
762 }
763 
764 static void vec_probe_vqs(struct vl_info *info,
765 			  DECLARE_BITMAP(map, SVE_VQ_MAX))
766 {
767 	unsigned int vq, vl;
768 
769 	bitmap_zero(map, SVE_VQ_MAX);
770 
771 	for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
772 		write_vl(info->type, vq - 1); /* self-syncing */
773 		vl = sve_get_vl();
774 		vq = sve_vq_from_vl(vl); /* skip intervening lengths */
775 		set_bit(__vq_to_bit(vq), map);
776 	}
777 }
778 
779 /*
780  * Initialise the set of known supported VQs for the boot CPU.
781  * This is called during kernel boot, before secondary CPUs are brought up.
782  */
783 void __init vec_init_vq_map(enum vec_type type)
784 {
785 	struct vl_info *info = &vl_info[type];
786 	vec_probe_vqs(info, info->vq_map);
787 	bitmap_copy(info->vq_partial_map, info->vq_map, SVE_VQ_MAX);
788 }
789 
790 /*
791  * If we haven't committed to the set of supported VQs yet, filter out
792  * those not supported by the current CPU.
793  * This function is called during the bring-up of early secondary CPUs only.
794  */
795 void vec_update_vq_map(enum vec_type type)
796 {
797 	struct vl_info *info = &vl_info[type];
798 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
799 
800 	vec_probe_vqs(info, tmp_map);
801 	bitmap_and(info->vq_map, info->vq_map, tmp_map, SVE_VQ_MAX);
802 	bitmap_or(info->vq_partial_map, info->vq_partial_map, tmp_map,
803 		  SVE_VQ_MAX);
804 }
805 
806 /*
807  * Check whether the current CPU supports all VQs in the committed set.
808  * This function is called during the bring-up of late secondary CPUs only.
809  */
810 int vec_verify_vq_map(enum vec_type type)
811 {
812 	struct vl_info *info = &vl_info[type];
813 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
814 	unsigned long b;
815 
816 	vec_probe_vqs(info, tmp_map);
817 
818 	bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
819 	if (bitmap_intersects(tmp_map, info->vq_map, SVE_VQ_MAX)) {
820 		pr_warn("%s: cpu%d: Required vector length(s) missing\n",
821 			info->name, smp_processor_id());
822 		return -EINVAL;
823 	}
824 
825 	if (!IS_ENABLED(CONFIG_KVM) || !is_hyp_mode_available())
826 		return 0;
827 
828 	/*
829 	 * For KVM, it is necessary to ensure that this CPU doesn't
830 	 * support any vector length that guests may have probed as
831 	 * unsupported.
832 	 */
833 
834 	/* Recover the set of supported VQs: */
835 	bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
836 	/* Find VQs supported that are not globally supported: */
837 	bitmap_andnot(tmp_map, tmp_map, info->vq_map, SVE_VQ_MAX);
838 
839 	/* Find the lowest such VQ, if any: */
840 	b = find_last_bit(tmp_map, SVE_VQ_MAX);
841 	if (b >= SVE_VQ_MAX)
842 		return 0; /* no mismatches */
843 
844 	/*
845 	 * Mismatches above sve_max_virtualisable_vl are fine, since
846 	 * no guest is allowed to configure ZCR_EL2.LEN to exceed this:
847 	 */
848 	if (sve_vl_from_vq(__bit_to_vq(b)) <= info->max_virtualisable_vl) {
849 		pr_warn("%s: cpu%d: Unsupported vector length(s) present\n",
850 			info->name, smp_processor_id());
851 		return -EINVAL;
852 	}
853 
854 	return 0;
855 }
856 
857 static void __init sve_efi_setup(void)
858 {
859 	struct vl_info *info = &vl_info[ARM64_VEC_SVE];
860 
861 	if (!IS_ENABLED(CONFIG_EFI))
862 		return;
863 
864 	/*
865 	 * alloc_percpu() warns and prints a backtrace if this goes wrong.
866 	 * This is evidence of a crippled system and we are returning void,
867 	 * so no attempt is made to handle this situation here.
868 	 */
869 	if (!sve_vl_valid(info->max_vl))
870 		goto fail;
871 
872 	efi_sve_state = __alloc_percpu(
873 		SVE_SIG_REGS_SIZE(sve_vq_from_vl(info->max_vl)), SVE_VQ_BYTES);
874 	if (!efi_sve_state)
875 		goto fail;
876 
877 	return;
878 
879 fail:
880 	panic("Cannot allocate percpu memory for EFI SVE save/restore");
881 }
882 
883 /*
884  * Enable SVE for EL1.
885  * Intended for use by the cpufeatures code during CPU boot.
886  */
887 void sve_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
888 {
889 	write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
890 	isb();
891 }
892 
893 /*
894  * Read the pseudo-ZCR used by cpufeatures to identify the supported SVE
895  * vector length.
896  *
897  * Use only if SVE is present.
898  * This function clobbers the SVE vector length.
899  */
900 u64 read_zcr_features(void)
901 {
902 	u64 zcr;
903 	unsigned int vq_max;
904 
905 	/*
906 	 * Set the maximum possible VL, and write zeroes to all other
907 	 * bits to see if they stick.
908 	 */
909 	sve_kernel_enable(NULL);
910 	write_sysreg_s(ZCR_ELx_LEN_MASK, SYS_ZCR_EL1);
911 
912 	zcr = read_sysreg_s(SYS_ZCR_EL1);
913 	zcr &= ~(u64)ZCR_ELx_LEN_MASK; /* find sticky 1s outside LEN field */
914 	vq_max = sve_vq_from_vl(sve_get_vl());
915 	zcr |= vq_max - 1; /* set LEN field to maximum effective value */
916 
917 	return zcr;
918 }
919 
920 void __init sve_setup(void)
921 {
922 	struct vl_info *info = &vl_info[ARM64_VEC_SVE];
923 	u64 zcr;
924 	DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
925 	unsigned long b;
926 
927 	if (!system_supports_sve())
928 		return;
929 
930 	/*
931 	 * The SVE architecture mandates support for 128-bit vectors,
932 	 * so sve_vq_map must have at least SVE_VQ_MIN set.
933 	 * If something went wrong, at least try to patch it up:
934 	 */
935 	if (WARN_ON(!test_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map)))
936 		set_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map);
937 
938 	zcr = read_sanitised_ftr_reg(SYS_ZCR_EL1);
939 	info->max_vl = sve_vl_from_vq((zcr & ZCR_ELx_LEN_MASK) + 1);
940 
941 	/*
942 	 * Sanity-check that the max VL we determined through CPU features
943 	 * corresponds properly to sve_vq_map.  If not, do our best:
944 	 */
945 	if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SVE,
946 								 info->max_vl)))
947 		info->max_vl = find_supported_vector_length(ARM64_VEC_SVE,
948 							    info->max_vl);
949 
950 	/*
951 	 * For the default VL, pick the maximum supported value <= 64.
952 	 * VL == 64 is guaranteed not to grow the signal frame.
953 	 */
954 	set_sve_default_vl(find_supported_vector_length(ARM64_VEC_SVE, 64));
955 
956 	bitmap_andnot(tmp_map, info->vq_partial_map, info->vq_map,
957 		      SVE_VQ_MAX);
958 
959 	b = find_last_bit(tmp_map, SVE_VQ_MAX);
960 	if (b >= SVE_VQ_MAX)
961 		/* No non-virtualisable VLs found */
962 		info->max_virtualisable_vl = SVE_VQ_MAX;
963 	else if (WARN_ON(b == SVE_VQ_MAX - 1))
964 		/* No virtualisable VLs?  This is architecturally forbidden. */
965 		info->max_virtualisable_vl = SVE_VQ_MIN;
966 	else /* b + 1 < SVE_VQ_MAX */
967 		info->max_virtualisable_vl = sve_vl_from_vq(__bit_to_vq(b + 1));
968 
969 	if (info->max_virtualisable_vl > info->max_vl)
970 		info->max_virtualisable_vl = info->max_vl;
971 
972 	pr_info("%s: maximum available vector length %u bytes per vector\n",
973 		info->name, info->max_vl);
974 	pr_info("%s: default vector length %u bytes per vector\n",
975 		info->name, get_sve_default_vl());
976 
977 	/* KVM decides whether to support mismatched systems. Just warn here: */
978 	if (sve_max_virtualisable_vl() < sve_max_vl())
979 		pr_warn("%s: unvirtualisable vector lengths present\n",
980 			info->name);
981 
982 	sve_efi_setup();
983 }
984 
985 /*
986  * Called from the put_task_struct() path, which cannot get here
987  * unless dead_task is really dead and not schedulable.
988  */
989 void fpsimd_release_task(struct task_struct *dead_task)
990 {
991 	__sve_free(dead_task);
992 }
993 
994 #endif /* CONFIG_ARM64_SVE */
995 
996 /*
997  * Trapped SVE access
998  *
999  * Storage is allocated for the full SVE state, the current FPSIMD
1000  * register contents are migrated across, and the access trap is
1001  * disabled.
1002  *
1003  * TIF_SVE should be clear on entry: otherwise, fpsimd_restore_current_state()
1004  * would have disabled the SVE access trap for userspace during
1005  * ret_to_user, making an SVE access trap impossible in that case.
1006  */
1007 void do_sve_acc(unsigned int esr, struct pt_regs *regs)
1008 {
1009 	/* Even if we chose not to use SVE, the hardware could still trap: */
1010 	if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
1011 		force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1012 		return;
1013 	}
1014 
1015 	sve_alloc(current);
1016 	if (!current->thread.sve_state) {
1017 		force_sig(SIGKILL);
1018 		return;
1019 	}
1020 
1021 	get_cpu_fpsimd_context();
1022 
1023 	if (test_and_set_thread_flag(TIF_SVE))
1024 		WARN_ON(1); /* SVE access shouldn't have trapped */
1025 
1026 	/*
1027 	 * Convert the FPSIMD state to SVE, zeroing all the state that
1028 	 * is not shared with FPSIMD. If (as is likely) the current
1029 	 * state is live in the registers then do this there and
1030 	 * update our metadata for the current task including
1031 	 * disabling the trap, otherwise update our in-memory copy.
1032 	 */
1033 	if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1034 		unsigned long vq_minus_one =
1035 			sve_vq_from_vl(task_get_sve_vl(current)) - 1;
1036 		sve_set_vq(vq_minus_one);
1037 		sve_flush_live(true, vq_minus_one);
1038 		fpsimd_bind_task_to_cpu();
1039 	} else {
1040 		fpsimd_to_sve(current);
1041 	}
1042 
1043 	put_cpu_fpsimd_context();
1044 }
1045 
1046 /*
1047  * Trapped FP/ASIMD access.
1048  */
1049 void do_fpsimd_acc(unsigned int esr, struct pt_regs *regs)
1050 {
1051 	/* TODO: implement lazy context saving/restoring */
1052 	WARN_ON(1);
1053 }
1054 
1055 /*
1056  * Raise a SIGFPE for the current process.
1057  */
1058 void do_fpsimd_exc(unsigned int esr, struct pt_regs *regs)
1059 {
1060 	unsigned int si_code = FPE_FLTUNK;
1061 
1062 	if (esr & ESR_ELx_FP_EXC_TFV) {
1063 		if (esr & FPEXC_IOF)
1064 			si_code = FPE_FLTINV;
1065 		else if (esr & FPEXC_DZF)
1066 			si_code = FPE_FLTDIV;
1067 		else if (esr & FPEXC_OFF)
1068 			si_code = FPE_FLTOVF;
1069 		else if (esr & FPEXC_UFF)
1070 			si_code = FPE_FLTUND;
1071 		else if (esr & FPEXC_IXF)
1072 			si_code = FPE_FLTRES;
1073 	}
1074 
1075 	send_sig_fault(SIGFPE, si_code,
1076 		       (void __user *)instruction_pointer(regs),
1077 		       current);
1078 }
1079 
1080 void fpsimd_thread_switch(struct task_struct *next)
1081 {
1082 	bool wrong_task, wrong_cpu;
1083 
1084 	if (!system_supports_fpsimd())
1085 		return;
1086 
1087 	__get_cpu_fpsimd_context();
1088 
1089 	/* Save unsaved fpsimd state, if any: */
1090 	fpsimd_save();
1091 
1092 	/*
1093 	 * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's
1094 	 * state.  For kernel threads, FPSIMD registers are never loaded
1095 	 * and wrong_task and wrong_cpu will always be true.
1096 	 */
1097 	wrong_task = __this_cpu_read(fpsimd_last_state.st) !=
1098 					&next->thread.uw.fpsimd_state;
1099 	wrong_cpu = next->thread.fpsimd_cpu != smp_processor_id();
1100 
1101 	update_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE,
1102 			       wrong_task || wrong_cpu);
1103 
1104 	__put_cpu_fpsimd_context();
1105 }
1106 
1107 static void fpsimd_flush_thread_vl(enum vec_type type)
1108 {
1109 	int vl, supported_vl;
1110 
1111 	/*
1112 	 * Reset the task vector length as required.  This is where we
1113 	 * ensure that all user tasks have a valid vector length
1114 	 * configured: no kernel task can become a user task without
1115 	 * an exec and hence a call to this function.  By the time the
1116 	 * first call to this function is made, all early hardware
1117 	 * probing is complete, so __sve_default_vl should be valid.
1118 	 * If a bug causes this to go wrong, we make some noise and
1119 	 * try to fudge thread.sve_vl to a safe value here.
1120 	 */
1121 	vl = task_get_vl_onexec(current, type);
1122 	if (!vl)
1123 		vl = get_default_vl(type);
1124 
1125 	if (WARN_ON(!sve_vl_valid(vl)))
1126 		vl = vl_info[type].min_vl;
1127 
1128 	supported_vl = find_supported_vector_length(type, vl);
1129 	if (WARN_ON(supported_vl != vl))
1130 		vl = supported_vl;
1131 
1132 	task_set_vl(current, type, vl);
1133 
1134 	/*
1135 	 * If the task is not set to inherit, ensure that the vector
1136 	 * length will be reset by a subsequent exec:
1137 	 */
1138 	if (!test_thread_flag(vec_vl_inherit_flag(type)))
1139 		task_set_vl_onexec(current, type, 0);
1140 }
1141 
1142 void fpsimd_flush_thread(void)
1143 {
1144 	if (!system_supports_fpsimd())
1145 		return;
1146 
1147 	get_cpu_fpsimd_context();
1148 
1149 	fpsimd_flush_task_state(current);
1150 	memset(&current->thread.uw.fpsimd_state, 0,
1151 	       sizeof(current->thread.uw.fpsimd_state));
1152 
1153 	if (system_supports_sve()) {
1154 		clear_thread_flag(TIF_SVE);
1155 		sve_free(current);
1156 		fpsimd_flush_thread_vl(ARM64_VEC_SVE);
1157 	}
1158 
1159 	put_cpu_fpsimd_context();
1160 }
1161 
1162 /*
1163  * Save the userland FPSIMD state of 'current' to memory, but only if the state
1164  * currently held in the registers does in fact belong to 'current'
1165  */
1166 void fpsimd_preserve_current_state(void)
1167 {
1168 	if (!system_supports_fpsimd())
1169 		return;
1170 
1171 	get_cpu_fpsimd_context();
1172 	fpsimd_save();
1173 	put_cpu_fpsimd_context();
1174 }
1175 
1176 /*
1177  * Like fpsimd_preserve_current_state(), but ensure that
1178  * current->thread.uw.fpsimd_state is updated so that it can be copied to
1179  * the signal frame.
1180  */
1181 void fpsimd_signal_preserve_current_state(void)
1182 {
1183 	fpsimd_preserve_current_state();
1184 	if (test_thread_flag(TIF_SVE))
1185 		sve_to_fpsimd(current);
1186 }
1187 
1188 /*
1189  * Associate current's FPSIMD context with this cpu
1190  * The caller must have ownership of the cpu FPSIMD context before calling
1191  * this function.
1192  */
1193 static void fpsimd_bind_task_to_cpu(void)
1194 {
1195 	struct fpsimd_last_state_struct *last =
1196 		this_cpu_ptr(&fpsimd_last_state);
1197 
1198 	WARN_ON(!system_supports_fpsimd());
1199 	last->st = &current->thread.uw.fpsimd_state;
1200 	last->sve_state = current->thread.sve_state;
1201 	last->sve_vl = task_get_sve_vl(current);
1202 	current->thread.fpsimd_cpu = smp_processor_id();
1203 
1204 	if (system_supports_sve()) {
1205 		/* Toggle SVE trapping for userspace if needed */
1206 		if (test_thread_flag(TIF_SVE))
1207 			sve_user_enable();
1208 		else
1209 			sve_user_disable();
1210 
1211 		/* Serialised by exception return to user */
1212 	}
1213 }
1214 
1215 void fpsimd_bind_state_to_cpu(struct user_fpsimd_state *st, void *sve_state,
1216 			      unsigned int sve_vl)
1217 {
1218 	struct fpsimd_last_state_struct *last =
1219 		this_cpu_ptr(&fpsimd_last_state);
1220 
1221 	WARN_ON(!system_supports_fpsimd());
1222 	WARN_ON(!in_softirq() && !irqs_disabled());
1223 
1224 	last->st = st;
1225 	last->sve_state = sve_state;
1226 	last->sve_vl = sve_vl;
1227 }
1228 
1229 /*
1230  * Load the userland FPSIMD state of 'current' from memory, but only if the
1231  * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1232  * state of 'current'.  This is called when we are preparing to return to
1233  * userspace to ensure that userspace sees a good register state.
1234  */
1235 void fpsimd_restore_current_state(void)
1236 {
1237 	/*
1238 	 * For the tasks that were created before we detected the absence of
1239 	 * FP/SIMD, the TIF_FOREIGN_FPSTATE could be set via fpsimd_thread_switch(),
1240 	 * e.g, init. This could be then inherited by the children processes.
1241 	 * If we later detect that the system doesn't support FP/SIMD,
1242 	 * we must clear the flag for  all the tasks to indicate that the
1243 	 * FPSTATE is clean (as we can't have one) to avoid looping for ever in
1244 	 * do_notify_resume().
1245 	 */
1246 	if (!system_supports_fpsimd()) {
1247 		clear_thread_flag(TIF_FOREIGN_FPSTATE);
1248 		return;
1249 	}
1250 
1251 	get_cpu_fpsimd_context();
1252 
1253 	if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1254 		task_fpsimd_load();
1255 		fpsimd_bind_task_to_cpu();
1256 	}
1257 
1258 	put_cpu_fpsimd_context();
1259 }
1260 
1261 /*
1262  * Load an updated userland FPSIMD state for 'current' from memory and set the
1263  * flag that indicates that the FPSIMD register contents are the most recent
1264  * FPSIMD state of 'current'. This is used by the signal code to restore the
1265  * register state when returning from a signal handler in FPSIMD only cases,
1266  * any SVE context will be discarded.
1267  */
1268 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1269 {
1270 	if (WARN_ON(!system_supports_fpsimd()))
1271 		return;
1272 
1273 	get_cpu_fpsimd_context();
1274 
1275 	current->thread.uw.fpsimd_state = *state;
1276 	if (test_thread_flag(TIF_SVE))
1277 		fpsimd_to_sve(current);
1278 
1279 	task_fpsimd_load();
1280 	fpsimd_bind_task_to_cpu();
1281 
1282 	clear_thread_flag(TIF_FOREIGN_FPSTATE);
1283 
1284 	put_cpu_fpsimd_context();
1285 }
1286 
1287 /*
1288  * Invalidate live CPU copies of task t's FPSIMD state
1289  *
1290  * This function may be called with preemption enabled.  The barrier()
1291  * ensures that the assignment to fpsimd_cpu is visible to any
1292  * preemption/softirq that could race with set_tsk_thread_flag(), so
1293  * that TIF_FOREIGN_FPSTATE cannot be spuriously re-cleared.
1294  *
1295  * The final barrier ensures that TIF_FOREIGN_FPSTATE is seen set by any
1296  * subsequent code.
1297  */
1298 void fpsimd_flush_task_state(struct task_struct *t)
1299 {
1300 	t->thread.fpsimd_cpu = NR_CPUS;
1301 	/*
1302 	 * If we don't support fpsimd, bail out after we have
1303 	 * reset the fpsimd_cpu for this task and clear the
1304 	 * FPSTATE.
1305 	 */
1306 	if (!system_supports_fpsimd())
1307 		return;
1308 	barrier();
1309 	set_tsk_thread_flag(t, TIF_FOREIGN_FPSTATE);
1310 
1311 	barrier();
1312 }
1313 
1314 /*
1315  * Invalidate any task's FPSIMD state that is present on this cpu.
1316  * The FPSIMD context should be acquired with get_cpu_fpsimd_context()
1317  * before calling this function.
1318  */
1319 static void fpsimd_flush_cpu_state(void)
1320 {
1321 	WARN_ON(!system_supports_fpsimd());
1322 	__this_cpu_write(fpsimd_last_state.st, NULL);
1323 	set_thread_flag(TIF_FOREIGN_FPSTATE);
1324 }
1325 
1326 /*
1327  * Save the FPSIMD state to memory and invalidate cpu view.
1328  * This function must be called with preemption disabled.
1329  */
1330 void fpsimd_save_and_flush_cpu_state(void)
1331 {
1332 	if (!system_supports_fpsimd())
1333 		return;
1334 	WARN_ON(preemptible());
1335 	__get_cpu_fpsimd_context();
1336 	fpsimd_save();
1337 	fpsimd_flush_cpu_state();
1338 	__put_cpu_fpsimd_context();
1339 }
1340 
1341 #ifdef CONFIG_KERNEL_MODE_NEON
1342 
1343 /*
1344  * Kernel-side NEON support functions
1345  */
1346 
1347 /*
1348  * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1349  * context
1350  *
1351  * Must not be called unless may_use_simd() returns true.
1352  * Task context in the FPSIMD registers is saved back to memory as necessary.
1353  *
1354  * A matching call to kernel_neon_end() must be made before returning from the
1355  * calling context.
1356  *
1357  * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1358  * called.
1359  */
1360 void kernel_neon_begin(void)
1361 {
1362 	if (WARN_ON(!system_supports_fpsimd()))
1363 		return;
1364 
1365 	BUG_ON(!may_use_simd());
1366 
1367 	get_cpu_fpsimd_context();
1368 
1369 	/* Save unsaved fpsimd state, if any: */
1370 	fpsimd_save();
1371 
1372 	/* Invalidate any task state remaining in the fpsimd regs: */
1373 	fpsimd_flush_cpu_state();
1374 }
1375 EXPORT_SYMBOL(kernel_neon_begin);
1376 
1377 /*
1378  * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1379  *
1380  * Must be called from a context in which kernel_neon_begin() was previously
1381  * called, with no call to kernel_neon_end() in the meantime.
1382  *
1383  * The caller must not use the FPSIMD registers after this function is called,
1384  * unless kernel_neon_begin() is called again in the meantime.
1385  */
1386 void kernel_neon_end(void)
1387 {
1388 	if (!system_supports_fpsimd())
1389 		return;
1390 
1391 	put_cpu_fpsimd_context();
1392 }
1393 EXPORT_SYMBOL(kernel_neon_end);
1394 
1395 #ifdef CONFIG_EFI
1396 
1397 static DEFINE_PER_CPU(struct user_fpsimd_state, efi_fpsimd_state);
1398 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1399 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1400 
1401 /*
1402  * EFI runtime services support functions
1403  *
1404  * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1405  * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1406  * is always used rather than being an optional accelerator.
1407  *
1408  * These functions provide the necessary support for ensuring FPSIMD
1409  * save/restore in the contexts from which EFI is used.
1410  *
1411  * Do not use them for any other purpose -- if tempted to do so, you are
1412  * either doing something wrong or you need to propose some refactoring.
1413  */
1414 
1415 /*
1416  * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1417  */
1418 void __efi_fpsimd_begin(void)
1419 {
1420 	if (!system_supports_fpsimd())
1421 		return;
1422 
1423 	WARN_ON(preemptible());
1424 
1425 	if (may_use_simd()) {
1426 		kernel_neon_begin();
1427 	} else {
1428 		/*
1429 		 * If !efi_sve_state, SVE can't be in use yet and doesn't need
1430 		 * preserving:
1431 		 */
1432 		if (system_supports_sve() && likely(efi_sve_state)) {
1433 			char *sve_state = this_cpu_ptr(efi_sve_state);
1434 
1435 			__this_cpu_write(efi_sve_state_used, true);
1436 
1437 			sve_save_state(sve_state + sve_ffr_offset(sve_max_vl()),
1438 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
1439 				       true);
1440 		} else {
1441 			fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
1442 		}
1443 
1444 		__this_cpu_write(efi_fpsimd_state_used, true);
1445 	}
1446 }
1447 
1448 /*
1449  * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
1450  */
1451 void __efi_fpsimd_end(void)
1452 {
1453 	if (!system_supports_fpsimd())
1454 		return;
1455 
1456 	if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
1457 		kernel_neon_end();
1458 	} else {
1459 		if (system_supports_sve() &&
1460 		    likely(__this_cpu_read(efi_sve_state_used))) {
1461 			char const *sve_state = this_cpu_ptr(efi_sve_state);
1462 
1463 			sve_set_vq(sve_vq_from_vl(sve_get_vl()) - 1);
1464 			sve_load_state(sve_state + sve_ffr_offset(sve_max_vl()),
1465 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
1466 				       true);
1467 
1468 			__this_cpu_write(efi_sve_state_used, false);
1469 		} else {
1470 			fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
1471 		}
1472 	}
1473 }
1474 
1475 #endif /* CONFIG_EFI */
1476 
1477 #endif /* CONFIG_KERNEL_MODE_NEON */
1478 
1479 #ifdef CONFIG_CPU_PM
1480 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
1481 				  unsigned long cmd, void *v)
1482 {
1483 	switch (cmd) {
1484 	case CPU_PM_ENTER:
1485 		fpsimd_save_and_flush_cpu_state();
1486 		break;
1487 	case CPU_PM_EXIT:
1488 		break;
1489 	case CPU_PM_ENTER_FAILED:
1490 	default:
1491 		return NOTIFY_DONE;
1492 	}
1493 	return NOTIFY_OK;
1494 }
1495 
1496 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
1497 	.notifier_call = fpsimd_cpu_pm_notifier,
1498 };
1499 
1500 static void __init fpsimd_pm_init(void)
1501 {
1502 	cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
1503 }
1504 
1505 #else
1506 static inline void fpsimd_pm_init(void) { }
1507 #endif /* CONFIG_CPU_PM */
1508 
1509 #ifdef CONFIG_HOTPLUG_CPU
1510 static int fpsimd_cpu_dead(unsigned int cpu)
1511 {
1512 	per_cpu(fpsimd_last_state.st, cpu) = NULL;
1513 	return 0;
1514 }
1515 
1516 static inline void fpsimd_hotplug_init(void)
1517 {
1518 	cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
1519 				  NULL, fpsimd_cpu_dead);
1520 }
1521 
1522 #else
1523 static inline void fpsimd_hotplug_init(void) { }
1524 #endif
1525 
1526 /*
1527  * FP/SIMD support code initialisation.
1528  */
1529 static int __init fpsimd_init(void)
1530 {
1531 	if (cpu_have_named_feature(FP)) {
1532 		fpsimd_pm_init();
1533 		fpsimd_hotplug_init();
1534 	} else {
1535 		pr_notice("Floating-point is not implemented\n");
1536 	}
1537 
1538 	if (!cpu_have_named_feature(ASIMD))
1539 		pr_notice("Advanced SIMD is not implemented\n");
1540 
1541 	return sve_sysctl_init();
1542 }
1543 core_initcall(fpsimd_init);
1544