xref: /openbmc/linux/arch/arm64/kernel/fpsimd.c (revision bc05aa6e)
1 /*
2  * FP/SIMD context switching and fault handling
3  *
4  * Copyright (C) 2012 ARM Ltd.
5  * Author: Catalin Marinas <catalin.marinas@arm.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include <linux/bitmap.h>
21 #include <linux/bottom_half.h>
22 #include <linux/bug.h>
23 #include <linux/cache.h>
24 #include <linux/compat.h>
25 #include <linux/cpu.h>
26 #include <linux/cpu_pm.h>
27 #include <linux/kernel.h>
28 #include <linux/linkage.h>
29 #include <linux/irqflags.h>
30 #include <linux/init.h>
31 #include <linux/percpu.h>
32 #include <linux/prctl.h>
33 #include <linux/preempt.h>
34 #include <linux/prctl.h>
35 #include <linux/ptrace.h>
36 #include <linux/sched/signal.h>
37 #include <linux/sched/task_stack.h>
38 #include <linux/signal.h>
39 #include <linux/slab.h>
40 #include <linux/sysctl.h>
41 
42 #include <asm/fpsimd.h>
43 #include <asm/cputype.h>
44 #include <asm/simd.h>
45 #include <asm/sigcontext.h>
46 #include <asm/sysreg.h>
47 #include <asm/traps.h>
48 
49 #define FPEXC_IOF	(1 << 0)
50 #define FPEXC_DZF	(1 << 1)
51 #define FPEXC_OFF	(1 << 2)
52 #define FPEXC_UFF	(1 << 3)
53 #define FPEXC_IXF	(1 << 4)
54 #define FPEXC_IDF	(1 << 7)
55 
56 /*
57  * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
58  *
59  * In order to reduce the number of times the FPSIMD state is needlessly saved
60  * and restored, we need to keep track of two things:
61  * (a) for each task, we need to remember which CPU was the last one to have
62  *     the task's FPSIMD state loaded into its FPSIMD registers;
63  * (b) for each CPU, we need to remember which task's userland FPSIMD state has
64  *     been loaded into its FPSIMD registers most recently, or whether it has
65  *     been used to perform kernel mode NEON in the meantime.
66  *
67  * For (a), we add a 'cpu' field to struct fpsimd_state, which gets updated to
68  * the id of the current CPU every time the state is loaded onto a CPU. For (b),
69  * we add the per-cpu variable 'fpsimd_last_state' (below), which contains the
70  * address of the userland FPSIMD state of the task that was loaded onto the CPU
71  * the most recently, or NULL if kernel mode NEON has been performed after that.
72  *
73  * With this in place, we no longer have to restore the next FPSIMD state right
74  * when switching between tasks. Instead, we can defer this check to userland
75  * resume, at which time we verify whether the CPU's fpsimd_last_state and the
76  * task's fpsimd_state.cpu are still mutually in sync. If this is the case, we
77  * can omit the FPSIMD restore.
78  *
79  * As an optimization, we use the thread_info flag TIF_FOREIGN_FPSTATE to
80  * indicate whether or not the userland FPSIMD state of the current task is
81  * present in the registers. The flag is set unless the FPSIMD registers of this
82  * CPU currently contain the most recent userland FPSIMD state of the current
83  * task.
84  *
85  * In order to allow softirq handlers to use FPSIMD, kernel_neon_begin() may
86  * save the task's FPSIMD context back to task_struct from softirq context.
87  * To prevent this from racing with the manipulation of the task's FPSIMD state
88  * from task context and thereby corrupting the state, it is necessary to
89  * protect any manipulation of a task's fpsimd_state or TIF_FOREIGN_FPSTATE
90  * flag with local_bh_disable() unless softirqs are already masked.
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_state.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_state.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 fpsimd_state *st;
119 	bool sve_in_use;
120 };
121 
122 static DEFINE_PER_CPU(struct fpsimd_last_state_struct, fpsimd_last_state);
123 
124 /* Default VL for tasks that don't set it explicitly: */
125 static int sve_default_vl = -1;
126 
127 #ifdef CONFIG_ARM64_SVE
128 
129 /* Maximum supported vector length across all CPUs (initially poisoned) */
130 int __ro_after_init sve_max_vl = -1;
131 /* Set of available vector lengths, as vq_to_bit(vq): */
132 static __ro_after_init DECLARE_BITMAP(sve_vq_map, SVE_VQ_MAX);
133 static void __percpu *efi_sve_state;
134 
135 #else /* ! CONFIG_ARM64_SVE */
136 
137 /* Dummy declaration for code that will be optimised out: */
138 extern __ro_after_init DECLARE_BITMAP(sve_vq_map, SVE_VQ_MAX);
139 extern void __percpu *efi_sve_state;
140 
141 #endif /* ! CONFIG_ARM64_SVE */
142 
143 /*
144  * Call __sve_free() directly only if you know task can't be scheduled
145  * or preempted.
146  */
147 static void __sve_free(struct task_struct *task)
148 {
149 	kfree(task->thread.sve_state);
150 	task->thread.sve_state = NULL;
151 }
152 
153 static void sve_free(struct task_struct *task)
154 {
155 	WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
156 
157 	__sve_free(task);
158 }
159 
160 
161 /* Offset of FFR in the SVE register dump */
162 static size_t sve_ffr_offset(int vl)
163 {
164 	return SVE_SIG_FFR_OFFSET(sve_vq_from_vl(vl)) - SVE_SIG_REGS_OFFSET;
165 }
166 
167 static void *sve_pffr(struct task_struct *task)
168 {
169 	return (char *)task->thread.sve_state +
170 		sve_ffr_offset(task->thread.sve_vl);
171 }
172 
173 static void change_cpacr(u64 val, u64 mask)
174 {
175 	u64 cpacr = read_sysreg(CPACR_EL1);
176 	u64 new = (cpacr & ~mask) | val;
177 
178 	if (new != cpacr)
179 		write_sysreg(new, CPACR_EL1);
180 }
181 
182 static void sve_user_disable(void)
183 {
184 	change_cpacr(0, CPACR_EL1_ZEN_EL0EN);
185 }
186 
187 static void sve_user_enable(void)
188 {
189 	change_cpacr(CPACR_EL1_ZEN_EL0EN, CPACR_EL1_ZEN_EL0EN);
190 }
191 
192 /*
193  * TIF_SVE controls whether a task can use SVE without trapping while
194  * in userspace, and also the way a task's FPSIMD/SVE state is stored
195  * in thread_struct.
196  *
197  * The kernel uses this flag to track whether a user task is actively
198  * using SVE, and therefore whether full SVE register state needs to
199  * be tracked.  If not, the cheaper FPSIMD context handling code can
200  * be used instead of the more costly SVE equivalents.
201  *
202  *  * TIF_SVE set:
203  *
204  *    The task can execute SVE instructions while in userspace without
205  *    trapping to the kernel.
206  *
207  *    When stored, Z0-Z31 (incorporating Vn in bits[127:0] or the
208  *    corresponding Zn), P0-P15 and FFR are encoded in in
209  *    task->thread.sve_state, formatted appropriately for vector
210  *    length task->thread.sve_vl.
211  *
212  *    task->thread.sve_state must point to a valid buffer at least
213  *    sve_state_size(task) bytes in size.
214  *
215  *    During any syscall, the kernel may optionally clear TIF_SVE and
216  *    discard the vector state except for the FPSIMD subset.
217  *
218  *  * TIF_SVE clear:
219  *
220  *    An attempt by the user task to execute an SVE instruction causes
221  *    do_sve_acc() to be called, which does some preparation and then
222  *    sets TIF_SVE.
223  *
224  *    When stored, FPSIMD registers V0-V31 are encoded in
225  *    task->fpsimd_state; bits [max : 128] for each of Z0-Z31 are
226  *    logically zero but not stored anywhere; P0-P15 and FFR are not
227  *    stored and have unspecified values from userspace's point of
228  *    view.  For hygiene purposes, the kernel zeroes them on next use,
229  *    but userspace is discouraged from relying on this.
230  *
231  *    task->thread.sve_state does not need to be non-NULL, valid or any
232  *    particular size: it must not be dereferenced.
233  *
234  *  * FPSR and FPCR are always stored in task->fpsimd_state irrespctive of
235  *    whether TIF_SVE is clear or set, since these are not vector length
236  *    dependent.
237  */
238 
239 /*
240  * Update current's FPSIMD/SVE registers from thread_struct.
241  *
242  * This function should be called only when the FPSIMD/SVE state in
243  * thread_struct is known to be up to date, when preparing to enter
244  * userspace.
245  *
246  * Softirqs (and preemption) must be disabled.
247  */
248 static void task_fpsimd_load(void)
249 {
250 	WARN_ON(!in_softirq() && !irqs_disabled());
251 
252 	if (system_supports_sve() && test_thread_flag(TIF_SVE))
253 		sve_load_state(sve_pffr(current),
254 			       &current->thread.fpsimd_state.fpsr,
255 			       sve_vq_from_vl(current->thread.sve_vl) - 1);
256 	else
257 		fpsimd_load_state(&current->thread.fpsimd_state);
258 
259 	if (system_supports_sve()) {
260 		/* Toggle SVE trapping for userspace if needed */
261 		if (test_thread_flag(TIF_SVE))
262 			sve_user_enable();
263 		else
264 			sve_user_disable();
265 
266 		/* Serialised by exception return to user */
267 	}
268 }
269 
270 /*
271  * Ensure current's FPSIMD/SVE storage in thread_struct is up to date
272  * with respect to the CPU registers.
273  *
274  * Softirqs (and preemption) must be disabled.
275  */
276 static void task_fpsimd_save(void)
277 {
278 	WARN_ON(!in_softirq() && !irqs_disabled());
279 
280 	if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
281 		if (system_supports_sve() && test_thread_flag(TIF_SVE)) {
282 			if (WARN_ON(sve_get_vl() != current->thread.sve_vl)) {
283 				/*
284 				 * Can't save the user regs, so current would
285 				 * re-enter user with corrupt state.
286 				 * There's no way to recover, so kill it:
287 				 */
288 				force_signal_inject(
289 					SIGKILL, 0, current_pt_regs(), 0);
290 				return;
291 			}
292 
293 			sve_save_state(sve_pffr(current),
294 				       &current->thread.fpsimd_state.fpsr);
295 		} else
296 			fpsimd_save_state(&current->thread.fpsimd_state);
297 	}
298 }
299 
300 /*
301  * Helpers to translate bit indices in sve_vq_map to VQ values (and
302  * vice versa).  This allows find_next_bit() to be used to find the
303  * _maximum_ VQ not exceeding a certain value.
304  */
305 
306 static unsigned int vq_to_bit(unsigned int vq)
307 {
308 	return SVE_VQ_MAX - vq;
309 }
310 
311 static unsigned int bit_to_vq(unsigned int bit)
312 {
313 	if (WARN_ON(bit >= SVE_VQ_MAX))
314 		bit = SVE_VQ_MAX - 1;
315 
316 	return SVE_VQ_MAX - bit;
317 }
318 
319 /*
320  * All vector length selection from userspace comes through here.
321  * We're on a slow path, so some sanity-checks are included.
322  * If things go wrong there's a bug somewhere, but try to fall back to a
323  * safe choice.
324  */
325 static unsigned int find_supported_vector_length(unsigned int vl)
326 {
327 	int bit;
328 	int max_vl = sve_max_vl;
329 
330 	if (WARN_ON(!sve_vl_valid(vl)))
331 		vl = SVE_VL_MIN;
332 
333 	if (WARN_ON(!sve_vl_valid(max_vl)))
334 		max_vl = SVE_VL_MIN;
335 
336 	if (vl > max_vl)
337 		vl = max_vl;
338 
339 	bit = find_next_bit(sve_vq_map, SVE_VQ_MAX,
340 			    vq_to_bit(sve_vq_from_vl(vl)));
341 	return sve_vl_from_vq(bit_to_vq(bit));
342 }
343 
344 #ifdef CONFIG_SYSCTL
345 
346 static int sve_proc_do_default_vl(struct ctl_table *table, int write,
347 				  void __user *buffer, size_t *lenp,
348 				  loff_t *ppos)
349 {
350 	int ret;
351 	int vl = sve_default_vl;
352 	struct ctl_table tmp_table = {
353 		.data = &vl,
354 		.maxlen = sizeof(vl),
355 	};
356 
357 	ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
358 	if (ret || !write)
359 		return ret;
360 
361 	/* Writing -1 has the special meaning "set to max": */
362 	if (vl == -1) {
363 		/* Fail safe if sve_max_vl wasn't initialised */
364 		if (WARN_ON(!sve_vl_valid(sve_max_vl)))
365 			vl = SVE_VL_MIN;
366 		else
367 			vl = sve_max_vl;
368 
369 		goto chosen;
370 	}
371 
372 	if (!sve_vl_valid(vl))
373 		return -EINVAL;
374 
375 	vl = find_supported_vector_length(vl);
376 chosen:
377 	sve_default_vl = vl;
378 	return 0;
379 }
380 
381 static struct ctl_table sve_default_vl_table[] = {
382 	{
383 		.procname	= "sve_default_vector_length",
384 		.mode		= 0644,
385 		.proc_handler	= sve_proc_do_default_vl,
386 	},
387 	{ }
388 };
389 
390 static int __init sve_sysctl_init(void)
391 {
392 	if (system_supports_sve())
393 		if (!register_sysctl("abi", sve_default_vl_table))
394 			return -EINVAL;
395 
396 	return 0;
397 }
398 
399 #else /* ! CONFIG_SYSCTL */
400 static int __init sve_sysctl_init(void) { return 0; }
401 #endif /* ! CONFIG_SYSCTL */
402 
403 #define ZREG(sve_state, vq, n) ((char *)(sve_state) +		\
404 	(SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
405 
406 /*
407  * Transfer the FPSIMD state in task->thread.fpsimd_state to
408  * task->thread.sve_state.
409  *
410  * Task can be a non-runnable task, or current.  In the latter case,
411  * softirqs (and preemption) must be disabled.
412  * task->thread.sve_state must point to at least sve_state_size(task)
413  * bytes of allocated kernel memory.
414  * task->thread.fpsimd_state must be up to date before calling this function.
415  */
416 static void fpsimd_to_sve(struct task_struct *task)
417 {
418 	unsigned int vq;
419 	void *sst = task->thread.sve_state;
420 	struct fpsimd_state const *fst = &task->thread.fpsimd_state;
421 	unsigned int i;
422 
423 	if (!system_supports_sve())
424 		return;
425 
426 	vq = sve_vq_from_vl(task->thread.sve_vl);
427 	for (i = 0; i < 32; ++i)
428 		memcpy(ZREG(sst, vq, i), &fst->vregs[i],
429 		       sizeof(fst->vregs[i]));
430 }
431 
432 /*
433  * Transfer the SVE state in task->thread.sve_state to
434  * task->thread.fpsimd_state.
435  *
436  * Task can be a non-runnable task, or current.  In the latter case,
437  * softirqs (and preemption) must be disabled.
438  * task->thread.sve_state must point to at least sve_state_size(task)
439  * bytes of allocated kernel memory.
440  * task->thread.sve_state must be up to date before calling this function.
441  */
442 static void sve_to_fpsimd(struct task_struct *task)
443 {
444 	unsigned int vq;
445 	void const *sst = task->thread.sve_state;
446 	struct fpsimd_state *fst = &task->thread.fpsimd_state;
447 	unsigned int i;
448 
449 	if (!system_supports_sve())
450 		return;
451 
452 	vq = sve_vq_from_vl(task->thread.sve_vl);
453 	for (i = 0; i < 32; ++i)
454 		memcpy(&fst->vregs[i], ZREG(sst, vq, i),
455 		       sizeof(fst->vregs[i]));
456 }
457 
458 #ifdef CONFIG_ARM64_SVE
459 
460 /*
461  * Return how many bytes of memory are required to store the full SVE
462  * state for task, given task's currently configured vector length.
463  */
464 size_t sve_state_size(struct task_struct const *task)
465 {
466 	return SVE_SIG_REGS_SIZE(sve_vq_from_vl(task->thread.sve_vl));
467 }
468 
469 /*
470  * Ensure that task->thread.sve_state is allocated and sufficiently large.
471  *
472  * This function should be used only in preparation for replacing
473  * task->thread.sve_state with new data.  The memory is always zeroed
474  * here to prevent stale data from showing through: this is done in
475  * the interest of testability and predictability: except in the
476  * do_sve_acc() case, there is no ABI requirement to hide stale data
477  * written previously be task.
478  */
479 void sve_alloc(struct task_struct *task)
480 {
481 	if (task->thread.sve_state) {
482 		memset(task->thread.sve_state, 0, sve_state_size(current));
483 		return;
484 	}
485 
486 	/* This is a small allocation (maximum ~8KB) and Should Not Fail. */
487 	task->thread.sve_state =
488 		kzalloc(sve_state_size(task), GFP_KERNEL);
489 
490 	/*
491 	 * If future SVE revisions can have larger vectors though,
492 	 * this may cease to be true:
493 	 */
494 	BUG_ON(!task->thread.sve_state);
495 }
496 
497 
498 /*
499  * Ensure that task->thread.sve_state is up to date with respect to
500  * the user task, irrespective of when SVE is in use or not.
501  *
502  * This should only be called by ptrace.  task must be non-runnable.
503  * task->thread.sve_state must point to at least sve_state_size(task)
504  * bytes of allocated kernel memory.
505  */
506 void fpsimd_sync_to_sve(struct task_struct *task)
507 {
508 	if (!test_tsk_thread_flag(task, TIF_SVE))
509 		fpsimd_to_sve(task);
510 }
511 
512 /*
513  * Ensure that task->thread.fpsimd_state is up to date with respect to
514  * the user task, irrespective of whether SVE is in use or not.
515  *
516  * This should only be called by ptrace.  task must be non-runnable.
517  * task->thread.sve_state must point to at least sve_state_size(task)
518  * bytes of allocated kernel memory.
519  */
520 void sve_sync_to_fpsimd(struct task_struct *task)
521 {
522 	if (test_tsk_thread_flag(task, TIF_SVE))
523 		sve_to_fpsimd(task);
524 }
525 
526 /*
527  * Ensure that task->thread.sve_state is up to date with respect to
528  * the task->thread.fpsimd_state.
529  *
530  * This should only be called by ptrace to merge new FPSIMD register
531  * values into a task for which SVE is currently active.
532  * task must be non-runnable.
533  * task->thread.sve_state must point to at least sve_state_size(task)
534  * bytes of allocated kernel memory.
535  * task->thread.fpsimd_state must already have been initialised with
536  * the new FPSIMD register values to be merged in.
537  */
538 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
539 {
540 	unsigned int vq;
541 	void *sst = task->thread.sve_state;
542 	struct fpsimd_state const *fst = &task->thread.fpsimd_state;
543 	unsigned int i;
544 
545 	if (!test_tsk_thread_flag(task, TIF_SVE))
546 		return;
547 
548 	vq = sve_vq_from_vl(task->thread.sve_vl);
549 
550 	memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
551 
552 	for (i = 0; i < 32; ++i)
553 		memcpy(ZREG(sst, vq, i), &fst->vregs[i],
554 		       sizeof(fst->vregs[i]));
555 }
556 
557 int sve_set_vector_length(struct task_struct *task,
558 			  unsigned long vl, unsigned long flags)
559 {
560 	if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
561 				     PR_SVE_SET_VL_ONEXEC))
562 		return -EINVAL;
563 
564 	if (!sve_vl_valid(vl))
565 		return -EINVAL;
566 
567 	/*
568 	 * Clamp to the maximum vector length that VL-agnostic SVE code can
569 	 * work with.  A flag may be assigned in the future to allow setting
570 	 * of larger vector lengths without confusing older software.
571 	 */
572 	if (vl > SVE_VL_ARCH_MAX)
573 		vl = SVE_VL_ARCH_MAX;
574 
575 	vl = find_supported_vector_length(vl);
576 
577 	if (flags & (PR_SVE_VL_INHERIT |
578 		     PR_SVE_SET_VL_ONEXEC))
579 		task->thread.sve_vl_onexec = vl;
580 	else
581 		/* Reset VL to system default on next exec: */
582 		task->thread.sve_vl_onexec = 0;
583 
584 	/* Only actually set the VL if not deferred: */
585 	if (flags & PR_SVE_SET_VL_ONEXEC)
586 		goto out;
587 
588 	if (vl == task->thread.sve_vl)
589 		goto out;
590 
591 	/*
592 	 * To ensure the FPSIMD bits of the SVE vector registers are preserved,
593 	 * write any live register state back to task_struct, and convert to a
594 	 * non-SVE thread.
595 	 */
596 	if (task == current) {
597 		local_bh_disable();
598 
599 		task_fpsimd_save();
600 		set_thread_flag(TIF_FOREIGN_FPSTATE);
601 	}
602 
603 	fpsimd_flush_task_state(task);
604 	if (test_and_clear_tsk_thread_flag(task, TIF_SVE))
605 		sve_to_fpsimd(task);
606 
607 	if (task == current)
608 		local_bh_enable();
609 
610 	/*
611 	 * Force reallocation of task SVE state to the correct size
612 	 * on next use:
613 	 */
614 	sve_free(task);
615 
616 	task->thread.sve_vl = vl;
617 
618 out:
619 	if (flags & PR_SVE_VL_INHERIT)
620 		set_tsk_thread_flag(task, TIF_SVE_VL_INHERIT);
621 	else
622 		clear_tsk_thread_flag(task, TIF_SVE_VL_INHERIT);
623 
624 	return 0;
625 }
626 
627 /*
628  * Encode the current vector length and flags for return.
629  * This is only required for prctl(): ptrace has separate fields
630  *
631  * flags are as for sve_set_vector_length().
632  */
633 static int sve_prctl_status(unsigned long flags)
634 {
635 	int ret;
636 
637 	if (flags & PR_SVE_SET_VL_ONEXEC)
638 		ret = current->thread.sve_vl_onexec;
639 	else
640 		ret = current->thread.sve_vl;
641 
642 	if (test_thread_flag(TIF_SVE_VL_INHERIT))
643 		ret |= PR_SVE_VL_INHERIT;
644 
645 	return ret;
646 }
647 
648 /* PR_SVE_SET_VL */
649 int sve_set_current_vl(unsigned long arg)
650 {
651 	unsigned long vl, flags;
652 	int ret;
653 
654 	vl = arg & PR_SVE_VL_LEN_MASK;
655 	flags = arg & ~vl;
656 
657 	if (!system_supports_sve())
658 		return -EINVAL;
659 
660 	ret = sve_set_vector_length(current, vl, flags);
661 	if (ret)
662 		return ret;
663 
664 	return sve_prctl_status(flags);
665 }
666 
667 /* PR_SVE_GET_VL */
668 int sve_get_current_vl(void)
669 {
670 	if (!system_supports_sve())
671 		return -EINVAL;
672 
673 	return sve_prctl_status(0);
674 }
675 
676 /*
677  * Bitmap for temporary storage of the per-CPU set of supported vector lengths
678  * during secondary boot.
679  */
680 static DECLARE_BITMAP(sve_secondary_vq_map, SVE_VQ_MAX);
681 
682 static void sve_probe_vqs(DECLARE_BITMAP(map, SVE_VQ_MAX))
683 {
684 	unsigned int vq, vl;
685 	unsigned long zcr;
686 
687 	bitmap_zero(map, SVE_VQ_MAX);
688 
689 	zcr = ZCR_ELx_LEN_MASK;
690 	zcr = read_sysreg_s(SYS_ZCR_EL1) & ~zcr;
691 
692 	for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
693 		write_sysreg_s(zcr | (vq - 1), SYS_ZCR_EL1); /* self-syncing */
694 		vl = sve_get_vl();
695 		vq = sve_vq_from_vl(vl); /* skip intervening lengths */
696 		set_bit(vq_to_bit(vq), map);
697 	}
698 }
699 
700 void __init sve_init_vq_map(void)
701 {
702 	sve_probe_vqs(sve_vq_map);
703 }
704 
705 /*
706  * If we haven't committed to the set of supported VQs yet, filter out
707  * those not supported by the current CPU.
708  */
709 void sve_update_vq_map(void)
710 {
711 	sve_probe_vqs(sve_secondary_vq_map);
712 	bitmap_and(sve_vq_map, sve_vq_map, sve_secondary_vq_map, SVE_VQ_MAX);
713 }
714 
715 /* Check whether the current CPU supports all VQs in the committed set */
716 int sve_verify_vq_map(void)
717 {
718 	int ret = 0;
719 
720 	sve_probe_vqs(sve_secondary_vq_map);
721 	bitmap_andnot(sve_secondary_vq_map, sve_vq_map, sve_secondary_vq_map,
722 		      SVE_VQ_MAX);
723 	if (!bitmap_empty(sve_secondary_vq_map, SVE_VQ_MAX)) {
724 		pr_warn("SVE: cpu%d: Required vector length(s) missing\n",
725 			smp_processor_id());
726 		ret = -EINVAL;
727 	}
728 
729 	return ret;
730 }
731 
732 static void __init sve_efi_setup(void)
733 {
734 	if (!IS_ENABLED(CONFIG_EFI))
735 		return;
736 
737 	/*
738 	 * alloc_percpu() warns and prints a backtrace if this goes wrong.
739 	 * This is evidence of a crippled system and we are returning void,
740 	 * so no attempt is made to handle this situation here.
741 	 */
742 	if (!sve_vl_valid(sve_max_vl))
743 		goto fail;
744 
745 	efi_sve_state = __alloc_percpu(
746 		SVE_SIG_REGS_SIZE(sve_vq_from_vl(sve_max_vl)), SVE_VQ_BYTES);
747 	if (!efi_sve_state)
748 		goto fail;
749 
750 	return;
751 
752 fail:
753 	panic("Cannot allocate percpu memory for EFI SVE save/restore");
754 }
755 
756 /*
757  * Enable SVE for EL1.
758  * Intended for use by the cpufeatures code during CPU boot.
759  */
760 int sve_kernel_enable(void *__always_unused p)
761 {
762 	write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
763 	isb();
764 
765 	return 0;
766 }
767 
768 void __init sve_setup(void)
769 {
770 	u64 zcr;
771 
772 	if (!system_supports_sve())
773 		return;
774 
775 	/*
776 	 * The SVE architecture mandates support for 128-bit vectors,
777 	 * so sve_vq_map must have at least SVE_VQ_MIN set.
778 	 * If something went wrong, at least try to patch it up:
779 	 */
780 	if (WARN_ON(!test_bit(vq_to_bit(SVE_VQ_MIN), sve_vq_map)))
781 		set_bit(vq_to_bit(SVE_VQ_MIN), sve_vq_map);
782 
783 	zcr = read_sanitised_ftr_reg(SYS_ZCR_EL1);
784 	sve_max_vl = sve_vl_from_vq((zcr & ZCR_ELx_LEN_MASK) + 1);
785 
786 	/*
787 	 * Sanity-check that the max VL we determined through CPU features
788 	 * corresponds properly to sve_vq_map.  If not, do our best:
789 	 */
790 	if (WARN_ON(sve_max_vl != find_supported_vector_length(sve_max_vl)))
791 		sve_max_vl = find_supported_vector_length(sve_max_vl);
792 
793 	/*
794 	 * For the default VL, pick the maximum supported value <= 64.
795 	 * VL == 64 is guaranteed not to grow the signal frame.
796 	 */
797 	sve_default_vl = find_supported_vector_length(64);
798 
799 	pr_info("SVE: maximum available vector length %u bytes per vector\n",
800 		sve_max_vl);
801 	pr_info("SVE: default vector length %u bytes per vector\n",
802 		sve_default_vl);
803 
804 	sve_efi_setup();
805 }
806 
807 /*
808  * Called from the put_task_struct() path, which cannot get here
809  * unless dead_task is really dead and not schedulable.
810  */
811 void fpsimd_release_task(struct task_struct *dead_task)
812 {
813 	__sve_free(dead_task);
814 }
815 
816 #endif /* CONFIG_ARM64_SVE */
817 
818 /*
819  * Trapped SVE access
820  *
821  * Storage is allocated for the full SVE state, the current FPSIMD
822  * register contents are migrated across, and TIF_SVE is set so that
823  * the SVE access trap will be disabled the next time this task
824  * reaches ret_to_user.
825  *
826  * TIF_SVE should be clear on entry: otherwise, task_fpsimd_load()
827  * would have disabled the SVE access trap for userspace during
828  * ret_to_user, making an SVE access trap impossible in that case.
829  */
830 asmlinkage void do_sve_acc(unsigned int esr, struct pt_regs *regs)
831 {
832 	/* Even if we chose not to use SVE, the hardware could still trap: */
833 	if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
834 		force_signal_inject(SIGILL, ILL_ILLOPC, regs, 0);
835 		return;
836 	}
837 
838 	sve_alloc(current);
839 
840 	local_bh_disable();
841 
842 	task_fpsimd_save();
843 	fpsimd_to_sve(current);
844 
845 	/* Force ret_to_user to reload the registers: */
846 	fpsimd_flush_task_state(current);
847 	set_thread_flag(TIF_FOREIGN_FPSTATE);
848 
849 	if (test_and_set_thread_flag(TIF_SVE))
850 		WARN_ON(1); /* SVE access shouldn't have trapped */
851 
852 	local_bh_enable();
853 }
854 
855 /*
856  * Trapped FP/ASIMD access.
857  */
858 asmlinkage void do_fpsimd_acc(unsigned int esr, struct pt_regs *regs)
859 {
860 	/* TODO: implement lazy context saving/restoring */
861 	WARN_ON(1);
862 }
863 
864 /*
865  * Raise a SIGFPE for the current process.
866  */
867 asmlinkage void do_fpsimd_exc(unsigned int esr, struct pt_regs *regs)
868 {
869 	siginfo_t info;
870 	unsigned int si_code = FPE_FIXME;
871 
872 	if (esr & FPEXC_IOF)
873 		si_code = FPE_FLTINV;
874 	else if (esr & FPEXC_DZF)
875 		si_code = FPE_FLTDIV;
876 	else if (esr & FPEXC_OFF)
877 		si_code = FPE_FLTOVF;
878 	else if (esr & FPEXC_UFF)
879 		si_code = FPE_FLTUND;
880 	else if (esr & FPEXC_IXF)
881 		si_code = FPE_FLTRES;
882 
883 	memset(&info, 0, sizeof(info));
884 	info.si_signo = SIGFPE;
885 	info.si_code = si_code;
886 	info.si_addr = (void __user *)instruction_pointer(regs);
887 
888 	send_sig_info(SIGFPE, &info, current);
889 }
890 
891 void fpsimd_thread_switch(struct task_struct *next)
892 {
893 	if (!system_supports_fpsimd())
894 		return;
895 	/*
896 	 * Save the current FPSIMD state to memory, but only if whatever is in
897 	 * the registers is in fact the most recent userland FPSIMD state of
898 	 * 'current'.
899 	 */
900 	if (current->mm)
901 		task_fpsimd_save();
902 
903 	if (next->mm) {
904 		/*
905 		 * If we are switching to a task whose most recent userland
906 		 * FPSIMD state is already in the registers of *this* cpu,
907 		 * we can skip loading the state from memory. Otherwise, set
908 		 * the TIF_FOREIGN_FPSTATE flag so the state will be loaded
909 		 * upon the next return to userland.
910 		 */
911 		struct fpsimd_state *st = &next->thread.fpsimd_state;
912 
913 		if (__this_cpu_read(fpsimd_last_state.st) == st
914 		    && st->cpu == smp_processor_id())
915 			clear_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE);
916 		else
917 			set_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE);
918 	}
919 }
920 
921 void fpsimd_flush_thread(void)
922 {
923 	int vl, supported_vl;
924 
925 	if (!system_supports_fpsimd())
926 		return;
927 
928 	local_bh_disable();
929 
930 	memset(&current->thread.fpsimd_state, 0, sizeof(struct fpsimd_state));
931 	fpsimd_flush_task_state(current);
932 
933 	if (system_supports_sve()) {
934 		clear_thread_flag(TIF_SVE);
935 		sve_free(current);
936 
937 		/*
938 		 * Reset the task vector length as required.
939 		 * This is where we ensure that all user tasks have a valid
940 		 * vector length configured: no kernel task can become a user
941 		 * task without an exec and hence a call to this function.
942 		 * By the time the first call to this function is made, all
943 		 * early hardware probing is complete, so sve_default_vl
944 		 * should be valid.
945 		 * If a bug causes this to go wrong, we make some noise and
946 		 * try to fudge thread.sve_vl to a safe value here.
947 		 */
948 		vl = current->thread.sve_vl_onexec ?
949 			current->thread.sve_vl_onexec : sve_default_vl;
950 
951 		if (WARN_ON(!sve_vl_valid(vl)))
952 			vl = SVE_VL_MIN;
953 
954 		supported_vl = find_supported_vector_length(vl);
955 		if (WARN_ON(supported_vl != vl))
956 			vl = supported_vl;
957 
958 		current->thread.sve_vl = vl;
959 
960 		/*
961 		 * If the task is not set to inherit, ensure that the vector
962 		 * length will be reset by a subsequent exec:
963 		 */
964 		if (!test_thread_flag(TIF_SVE_VL_INHERIT))
965 			current->thread.sve_vl_onexec = 0;
966 	}
967 
968 	set_thread_flag(TIF_FOREIGN_FPSTATE);
969 
970 	local_bh_enable();
971 }
972 
973 /*
974  * Save the userland FPSIMD state of 'current' to memory, but only if the state
975  * currently held in the registers does in fact belong to 'current'
976  */
977 void fpsimd_preserve_current_state(void)
978 {
979 	if (!system_supports_fpsimd())
980 		return;
981 
982 	local_bh_disable();
983 	task_fpsimd_save();
984 	local_bh_enable();
985 }
986 
987 /*
988  * Like fpsimd_preserve_current_state(), but ensure that
989  * current->thread.fpsimd_state is updated so that it can be copied to
990  * the signal frame.
991  */
992 void fpsimd_signal_preserve_current_state(void)
993 {
994 	fpsimd_preserve_current_state();
995 	if (system_supports_sve() && test_thread_flag(TIF_SVE))
996 		sve_to_fpsimd(current);
997 }
998 
999 /*
1000  * Associate current's FPSIMD context with this cpu
1001  * Preemption must be disabled when calling this function.
1002  */
1003 static void fpsimd_bind_to_cpu(void)
1004 {
1005 	struct fpsimd_last_state_struct *last =
1006 		this_cpu_ptr(&fpsimd_last_state);
1007 	struct fpsimd_state *st = &current->thread.fpsimd_state;
1008 
1009 	last->st = st;
1010 	last->sve_in_use = test_thread_flag(TIF_SVE);
1011 	st->cpu = smp_processor_id();
1012 }
1013 
1014 /*
1015  * Load the userland FPSIMD state of 'current' from memory, but only if the
1016  * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1017  * state of 'current'
1018  */
1019 void fpsimd_restore_current_state(void)
1020 {
1021 	if (!system_supports_fpsimd())
1022 		return;
1023 
1024 	local_bh_disable();
1025 
1026 	if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1027 		task_fpsimd_load();
1028 		fpsimd_bind_to_cpu();
1029 	}
1030 
1031 	local_bh_enable();
1032 }
1033 
1034 /*
1035  * Load an updated userland FPSIMD state for 'current' from memory and set the
1036  * flag that indicates that the FPSIMD register contents are the most recent
1037  * FPSIMD state of 'current'
1038  */
1039 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1040 {
1041 	if (!system_supports_fpsimd())
1042 		return;
1043 
1044 	local_bh_disable();
1045 
1046 	current->thread.fpsimd_state.user_fpsimd = *state;
1047 	if (system_supports_sve() && test_thread_flag(TIF_SVE))
1048 		fpsimd_to_sve(current);
1049 
1050 	task_fpsimd_load();
1051 
1052 	if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE))
1053 		fpsimd_bind_to_cpu();
1054 
1055 	local_bh_enable();
1056 }
1057 
1058 /*
1059  * Invalidate live CPU copies of task t's FPSIMD state
1060  */
1061 void fpsimd_flush_task_state(struct task_struct *t)
1062 {
1063 	t->thread.fpsimd_state.cpu = NR_CPUS;
1064 }
1065 
1066 static inline void fpsimd_flush_cpu_state(void)
1067 {
1068 	__this_cpu_write(fpsimd_last_state.st, NULL);
1069 }
1070 
1071 /*
1072  * Invalidate any task SVE state currently held in this CPU's regs.
1073  *
1074  * This is used to prevent the kernel from trying to reuse SVE register data
1075  * that is detroyed by KVM guest enter/exit.  This function should go away when
1076  * KVM SVE support is implemented.  Don't use it for anything else.
1077  */
1078 #ifdef CONFIG_ARM64_SVE
1079 void sve_flush_cpu_state(void)
1080 {
1081 	struct fpsimd_last_state_struct const *last =
1082 		this_cpu_ptr(&fpsimd_last_state);
1083 
1084 	if (last->st && last->sve_in_use)
1085 		fpsimd_flush_cpu_state();
1086 }
1087 #endif /* CONFIG_ARM64_SVE */
1088 
1089 #ifdef CONFIG_KERNEL_MODE_NEON
1090 
1091 DEFINE_PER_CPU(bool, kernel_neon_busy);
1092 EXPORT_PER_CPU_SYMBOL(kernel_neon_busy);
1093 
1094 /*
1095  * Kernel-side NEON support functions
1096  */
1097 
1098 /*
1099  * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1100  * context
1101  *
1102  * Must not be called unless may_use_simd() returns true.
1103  * Task context in the FPSIMD registers is saved back to memory as necessary.
1104  *
1105  * A matching call to kernel_neon_end() must be made before returning from the
1106  * calling context.
1107  *
1108  * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1109  * called.
1110  */
1111 void kernel_neon_begin(void)
1112 {
1113 	if (WARN_ON(!system_supports_fpsimd()))
1114 		return;
1115 
1116 	BUG_ON(!may_use_simd());
1117 
1118 	local_bh_disable();
1119 
1120 	__this_cpu_write(kernel_neon_busy, true);
1121 
1122 	/* Save unsaved task fpsimd state, if any: */
1123 	if (current->mm) {
1124 		task_fpsimd_save();
1125 		set_thread_flag(TIF_FOREIGN_FPSTATE);
1126 	}
1127 
1128 	/* Invalidate any task state remaining in the fpsimd regs: */
1129 	fpsimd_flush_cpu_state();
1130 
1131 	preempt_disable();
1132 
1133 	local_bh_enable();
1134 }
1135 EXPORT_SYMBOL(kernel_neon_begin);
1136 
1137 /*
1138  * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1139  *
1140  * Must be called from a context in which kernel_neon_begin() was previously
1141  * called, with no call to kernel_neon_end() in the meantime.
1142  *
1143  * The caller must not use the FPSIMD registers after this function is called,
1144  * unless kernel_neon_begin() is called again in the meantime.
1145  */
1146 void kernel_neon_end(void)
1147 {
1148 	bool busy;
1149 
1150 	if (!system_supports_fpsimd())
1151 		return;
1152 
1153 	busy = __this_cpu_xchg(kernel_neon_busy, false);
1154 	WARN_ON(!busy);	/* No matching kernel_neon_begin()? */
1155 
1156 	preempt_enable();
1157 }
1158 EXPORT_SYMBOL(kernel_neon_end);
1159 
1160 #ifdef CONFIG_EFI
1161 
1162 static DEFINE_PER_CPU(struct fpsimd_state, efi_fpsimd_state);
1163 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1164 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1165 
1166 /*
1167  * EFI runtime services support functions
1168  *
1169  * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1170  * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1171  * is always used rather than being an optional accelerator.
1172  *
1173  * These functions provide the necessary support for ensuring FPSIMD
1174  * save/restore in the contexts from which EFI is used.
1175  *
1176  * Do not use them for any other purpose -- if tempted to do so, you are
1177  * either doing something wrong or you need to propose some refactoring.
1178  */
1179 
1180 /*
1181  * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1182  */
1183 void __efi_fpsimd_begin(void)
1184 {
1185 	if (!system_supports_fpsimd())
1186 		return;
1187 
1188 	WARN_ON(preemptible());
1189 
1190 	if (may_use_simd()) {
1191 		kernel_neon_begin();
1192 	} else {
1193 		/*
1194 		 * If !efi_sve_state, SVE can't be in use yet and doesn't need
1195 		 * preserving:
1196 		 */
1197 		if (system_supports_sve() && likely(efi_sve_state)) {
1198 			char *sve_state = this_cpu_ptr(efi_sve_state);
1199 
1200 			__this_cpu_write(efi_sve_state_used, true);
1201 
1202 			sve_save_state(sve_state + sve_ffr_offset(sve_max_vl),
1203 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr);
1204 		} else {
1205 			fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
1206 		}
1207 
1208 		__this_cpu_write(efi_fpsimd_state_used, true);
1209 	}
1210 }
1211 
1212 /*
1213  * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
1214  */
1215 void __efi_fpsimd_end(void)
1216 {
1217 	if (!system_supports_fpsimd())
1218 		return;
1219 
1220 	if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
1221 		kernel_neon_end();
1222 	} else {
1223 		if (system_supports_sve() &&
1224 		    likely(__this_cpu_read(efi_sve_state_used))) {
1225 			char const *sve_state = this_cpu_ptr(efi_sve_state);
1226 
1227 			sve_load_state(sve_state + sve_ffr_offset(sve_max_vl),
1228 				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
1229 				       sve_vq_from_vl(sve_get_vl()) - 1);
1230 
1231 			__this_cpu_write(efi_sve_state_used, false);
1232 		} else {
1233 			fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
1234 		}
1235 	}
1236 }
1237 
1238 #endif /* CONFIG_EFI */
1239 
1240 #endif /* CONFIG_KERNEL_MODE_NEON */
1241 
1242 #ifdef CONFIG_CPU_PM
1243 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
1244 				  unsigned long cmd, void *v)
1245 {
1246 	switch (cmd) {
1247 	case CPU_PM_ENTER:
1248 		if (current->mm)
1249 			task_fpsimd_save();
1250 		fpsimd_flush_cpu_state();
1251 		break;
1252 	case CPU_PM_EXIT:
1253 		if (current->mm)
1254 			set_thread_flag(TIF_FOREIGN_FPSTATE);
1255 		break;
1256 	case CPU_PM_ENTER_FAILED:
1257 	default:
1258 		return NOTIFY_DONE;
1259 	}
1260 	return NOTIFY_OK;
1261 }
1262 
1263 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
1264 	.notifier_call = fpsimd_cpu_pm_notifier,
1265 };
1266 
1267 static void __init fpsimd_pm_init(void)
1268 {
1269 	cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
1270 }
1271 
1272 #else
1273 static inline void fpsimd_pm_init(void) { }
1274 #endif /* CONFIG_CPU_PM */
1275 
1276 #ifdef CONFIG_HOTPLUG_CPU
1277 static int fpsimd_cpu_dead(unsigned int cpu)
1278 {
1279 	per_cpu(fpsimd_last_state.st, cpu) = NULL;
1280 	return 0;
1281 }
1282 
1283 static inline void fpsimd_hotplug_init(void)
1284 {
1285 	cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
1286 				  NULL, fpsimd_cpu_dead);
1287 }
1288 
1289 #else
1290 static inline void fpsimd_hotplug_init(void) { }
1291 #endif
1292 
1293 /*
1294  * FP/SIMD support code initialisation.
1295  */
1296 static int __init fpsimd_init(void)
1297 {
1298 	if (elf_hwcap & HWCAP_FP) {
1299 		fpsimd_pm_init();
1300 		fpsimd_hotplug_init();
1301 	} else {
1302 		pr_notice("Floating-point is not implemented\n");
1303 	}
1304 
1305 	if (!(elf_hwcap & HWCAP_ASIMD))
1306 		pr_notice("Advanced SIMD is not implemented\n");
1307 
1308 	return sve_sysctl_init();
1309 }
1310 core_initcall(fpsimd_init);
1311