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