1 // SPDX-License-Identifier: GPL-2.0-only
3 * FP/SIMD context switching and fault handling
5 * Copyright (C) 2012 ARM Ltd.
6 * Author: Catalin Marinas <catalin.marinas@arm.com>
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/kernel.h>
19 #include <linux/linkage.h>
20 #include <linux/irqflags.h>
21 #include <linux/init.h>
22 #include <linux/percpu.h>
23 #include <linux/prctl.h>
24 #include <linux/preempt.h>
25 #include <linux/ptrace.h>
26 #include <linux/sched/signal.h>
27 #include <linux/sched/task_stack.h>
28 #include <linux/signal.h>
29 #include <linux/slab.h>
30 #include <linux/stddef.h>
31 #include <linux/sysctl.h>
32 #include <linux/swab.h>
35 #include <asm/exception.h>
36 #include <asm/fpsimd.h>
37 #include <asm/cpufeature.h>
38 #include <asm/cputype.h>
40 #include <asm/processor.h>
42 #include <asm/sigcontext.h>
43 #include <asm/sysreg.h>
44 #include <asm/traps.h>
47 #define FPEXC_IOF (1 << 0)
48 #define FPEXC_DZF (1 << 1)
49 #define FPEXC_OFF (1 << 2)
50 #define FPEXC_UFF (1 << 3)
51 #define FPEXC_IXF (1 << 4)
52 #define FPEXC_IDF (1 << 7)
55 * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
57 * In order to reduce the number of times the FPSIMD state is needlessly saved
58 * and restored, we need to keep track of two things:
59 * (a) for each task, we need to remember which CPU was the last one to have
60 * the task's FPSIMD state loaded into its FPSIMD registers;
61 * (b) for each CPU, we need to remember which task's userland FPSIMD state has
62 * been loaded into its FPSIMD registers most recently, or whether it has
63 * been used to perform kernel mode NEON in the meantime.
65 * For (a), we add a fpsimd_cpu field to thread_struct, which gets updated to
66 * the id of the current CPU every time the state is loaded onto a CPU. For (b),
67 * we add the per-cpu variable 'fpsimd_last_state' (below), which contains the
68 * address of the userland FPSIMD state of the task that was loaded onto the CPU
69 * the most recently, or NULL if kernel mode NEON has been performed after that.
71 * With this in place, we no longer have to restore the next FPSIMD state right
72 * when switching between tasks. Instead, we can defer this check to userland
73 * resume, at which time we verify whether the CPU's fpsimd_last_state and the
74 * task's fpsimd_cpu are still mutually in sync. If this is the case, we
75 * can omit the FPSIMD restore.
77 * As an optimization, we use the thread_info flag TIF_FOREIGN_FPSTATE to
78 * indicate whether or not the userland FPSIMD state of the current task is
79 * present in the registers. The flag is set unless the FPSIMD registers of this
80 * CPU currently contain the most recent userland FPSIMD state of the current
83 * In order to allow softirq handlers to use FPSIMD, kernel_neon_begin() may
84 * save the task's FPSIMD context back to task_struct from softirq context.
85 * To prevent this from racing with the manipulation of the task's FPSIMD state
86 * from task context and thereby corrupting the state, it is necessary to
87 * protect any manipulation of a task's fpsimd_state or TIF_FOREIGN_FPSTATE
88 * flag with {, __}get_cpu_fpsimd_context(). This will still allow softirqs to
89 * run but prevent them to use FPSIMD.
91 * For a certain task, the sequence may look something like this:
92 * - the task gets scheduled in; if both the task's fpsimd_cpu field
93 * contains the id of the current CPU, and the CPU's fpsimd_last_state per-cpu
94 * variable points to the task's fpsimd_state, the TIF_FOREIGN_FPSTATE flag is
95 * cleared, otherwise it is set;
97 * - the task returns to userland; if TIF_FOREIGN_FPSTATE is set, the task's
98 * userland FPSIMD state is copied from memory to the registers, the task's
99 * fpsimd_cpu field is set to the id of the current CPU, the current
100 * CPU's fpsimd_last_state pointer is set to this task's fpsimd_state and the
101 * TIF_FOREIGN_FPSTATE flag is cleared;
103 * - the task executes an ordinary syscall; upon return to userland, the
104 * TIF_FOREIGN_FPSTATE flag will still be cleared, so no FPSIMD state is
107 * - the task executes a syscall which executes some NEON instructions; this is
108 * preceded by a call to kernel_neon_begin(), which copies the task's FPSIMD
109 * register contents to memory, clears the fpsimd_last_state per-cpu variable
110 * and sets the TIF_FOREIGN_FPSTATE flag;
112 * - the task gets preempted after kernel_neon_end() is called; as we have not
113 * returned from the 2nd syscall yet, TIF_FOREIGN_FPSTATE is still set so
114 * whatever is in the FPSIMD registers is not saved to memory, but discarded.
116 struct fpsimd_last_state_struct {
117 struct user_fpsimd_state *st;
122 static DEFINE_PER_CPU(struct fpsimd_last_state_struct, fpsimd_last_state);
124 /* Default VL for tasks that don't set it explicitly: */
125 static int __sve_default_vl = -1;
127 static int get_sve_default_vl(void)
129 return READ_ONCE(__sve_default_vl);
132 #ifdef CONFIG_ARM64_SVE
134 static void set_sve_default_vl(int val)
136 WRITE_ONCE(__sve_default_vl, val);
139 /* Maximum supported vector length across all CPUs (initially poisoned) */
140 int __ro_after_init sve_max_vl = SVE_VL_MIN;
141 int __ro_after_init sve_max_virtualisable_vl = SVE_VL_MIN;
144 * Set of available vector lengths,
145 * where length vq encoded as bit __vq_to_bit(vq):
147 __ro_after_init DECLARE_BITMAP(sve_vq_map, SVE_VQ_MAX);
148 /* Set of vector lengths present on at least one cpu: */
149 static __ro_after_init DECLARE_BITMAP(sve_vq_partial_map, SVE_VQ_MAX);
151 static void __percpu *efi_sve_state;
153 #else /* ! CONFIG_ARM64_SVE */
155 /* Dummy declaration for code that will be optimised out: */
156 extern __ro_after_init DECLARE_BITMAP(sve_vq_map, SVE_VQ_MAX);
157 extern __ro_after_init DECLARE_BITMAP(sve_vq_partial_map, SVE_VQ_MAX);
158 extern void __percpu *efi_sve_state;
160 #endif /* ! CONFIG_ARM64_SVE */
162 DEFINE_PER_CPU(bool, fpsimd_context_busy);
163 EXPORT_PER_CPU_SYMBOL(fpsimd_context_busy);
165 static void fpsimd_bind_task_to_cpu(void);
167 static void __get_cpu_fpsimd_context(void)
169 bool busy = __this_cpu_xchg(fpsimd_context_busy, true);
175 * Claim ownership of the CPU FPSIMD context for use by the calling context.
177 * The caller may freely manipulate the FPSIMD context metadata until
178 * put_cpu_fpsimd_context() is called.
180 * The double-underscore version must only be called if you know the task
181 * can't be preempted.
183 static void get_cpu_fpsimd_context(void)
186 __get_cpu_fpsimd_context();
189 static void __put_cpu_fpsimd_context(void)
191 bool busy = __this_cpu_xchg(fpsimd_context_busy, false);
193 WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */
197 * Release the CPU FPSIMD context.
199 * Must be called from a context in which get_cpu_fpsimd_context() was
200 * previously called, with no call to put_cpu_fpsimd_context() in the
203 static void put_cpu_fpsimd_context(void)
205 __put_cpu_fpsimd_context();
209 static bool have_cpu_fpsimd_context(void)
211 return !preemptible() && __this_cpu_read(fpsimd_context_busy);
215 * Call __sve_free() directly only if you know task can't be scheduled
218 static void __sve_free(struct task_struct *task)
220 kfree(task->thread.sve_state);
221 task->thread.sve_state = NULL;
224 static void sve_free(struct task_struct *task)
226 WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
232 * TIF_SVE controls whether a task can use SVE without trapping while
233 * in userspace, and also the way a task's FPSIMD/SVE state is stored
236 * The kernel uses this flag to track whether a user task is actively
237 * using SVE, and therefore whether full SVE register state needs to
238 * be tracked. If not, the cheaper FPSIMD context handling code can
239 * be used instead of the more costly SVE equivalents.
243 * The task can execute SVE instructions while in userspace without
244 * trapping to the kernel.
246 * When stored, Z0-Z31 (incorporating Vn in bits[127:0] or the
247 * corresponding Zn), P0-P15 and FFR are encoded in in
248 * task->thread.sve_state, formatted appropriately for vector
249 * length task->thread.sve_vl.
251 * task->thread.sve_state must point to a valid buffer at least
252 * sve_state_size(task) bytes in size.
254 * During any syscall, the kernel may optionally clear TIF_SVE and
255 * discard the vector state except for the FPSIMD subset.
259 * An attempt by the user task to execute an SVE instruction causes
260 * do_sve_acc() to be called, which does some preparation and then
263 * When stored, FPSIMD registers V0-V31 are encoded in
264 * task->thread.uw.fpsimd_state; bits [max : 128] for each of Z0-Z31 are
265 * logically zero but not stored anywhere; P0-P15 and FFR are not
266 * stored and have unspecified values from userspace's point of
267 * view. For hygiene purposes, the kernel zeroes them on next use,
268 * but userspace is discouraged from relying on this.
270 * task->thread.sve_state does not need to be non-NULL, valid or any
271 * particular size: it must not be dereferenced.
273 * * FPSR and FPCR are always stored in task->thread.uw.fpsimd_state
274 * irrespective of whether TIF_SVE is clear or set, since these are
275 * not vector length dependent.
279 * Update current's FPSIMD/SVE registers from thread_struct.
281 * This function should be called only when the FPSIMD/SVE state in
282 * thread_struct is known to be up to date, when preparing to enter
285 static void task_fpsimd_load(void)
287 WARN_ON(!system_supports_fpsimd());
288 WARN_ON(!have_cpu_fpsimd_context());
290 if (IS_ENABLED(CONFIG_ARM64_SVE) && test_thread_flag(TIF_SVE))
291 sve_load_state(sve_pffr(¤t->thread),
292 ¤t->thread.uw.fpsimd_state.fpsr,
293 sve_vq_from_vl(current->thread.sve_vl) - 1);
295 fpsimd_load_state(¤t->thread.uw.fpsimd_state);
299 * Ensure FPSIMD/SVE storage in memory for the loaded context is up to
300 * date with respect to the CPU registers.
302 static void fpsimd_save(void)
304 struct fpsimd_last_state_struct const *last =
305 this_cpu_ptr(&fpsimd_last_state);
306 /* set by fpsimd_bind_task_to_cpu() or fpsimd_bind_state_to_cpu() */
308 WARN_ON(!system_supports_fpsimd());
309 WARN_ON(!have_cpu_fpsimd_context());
311 if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
312 if (IS_ENABLED(CONFIG_ARM64_SVE) &&
313 test_thread_flag(TIF_SVE)) {
314 if (WARN_ON(sve_get_vl() != last->sve_vl)) {
316 * Can't save the user regs, so current would
317 * re-enter user with corrupt state.
318 * There's no way to recover, so kill it:
320 force_signal_inject(SIGKILL, SI_KERNEL, 0, 0);
324 sve_save_state((char *)last->sve_state +
325 sve_ffr_offset(last->sve_vl),
328 fpsimd_save_state(last->st);
333 * All vector length selection from userspace comes through here.
334 * We're on a slow path, so some sanity-checks are included.
335 * If things go wrong there's a bug somewhere, but try to fall back to a
338 static unsigned int find_supported_vector_length(unsigned int vl)
341 int max_vl = sve_max_vl;
343 if (WARN_ON(!sve_vl_valid(vl)))
346 if (WARN_ON(!sve_vl_valid(max_vl)))
352 bit = find_next_bit(sve_vq_map, SVE_VQ_MAX,
353 __vq_to_bit(sve_vq_from_vl(vl)));
354 return sve_vl_from_vq(__bit_to_vq(bit));
357 #if defined(CONFIG_ARM64_SVE) && defined(CONFIG_SYSCTL)
359 static int sve_proc_do_default_vl(struct ctl_table *table, int write,
360 void *buffer, size_t *lenp, loff_t *ppos)
363 int vl = get_sve_default_vl();
364 struct ctl_table tmp_table = {
366 .maxlen = sizeof(vl),
369 ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
373 /* Writing -1 has the special meaning "set to max": */
377 if (!sve_vl_valid(vl))
380 set_sve_default_vl(find_supported_vector_length(vl));
384 static struct ctl_table sve_default_vl_table[] = {
386 .procname = "sve_default_vector_length",
388 .proc_handler = sve_proc_do_default_vl,
393 static int __init sve_sysctl_init(void)
395 if (system_supports_sve())
396 if (!register_sysctl("abi", sve_default_vl_table))
402 #else /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
403 static int __init sve_sysctl_init(void) { return 0; }
404 #endif /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
406 #define ZREG(sve_state, vq, n) ((char *)(sve_state) + \
407 (SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
409 #ifdef CONFIG_CPU_BIG_ENDIAN
410 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
413 u64 b = swab64(x >> 64);
415 return ((__uint128_t)a << 64) | b;
418 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
424 #define arm64_le128_to_cpu(x) arm64_cpu_to_le128(x)
426 static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst,
432 for (i = 0; i < SVE_NUM_ZREGS; ++i) {
433 p = (__uint128_t *)ZREG(sst, vq, i);
434 *p = arm64_cpu_to_le128(fst->vregs[i]);
439 * Transfer the FPSIMD state in task->thread.uw.fpsimd_state to
440 * task->thread.sve_state.
442 * Task can be a non-runnable task, or current. In the latter case,
443 * the caller must have ownership of the cpu FPSIMD context before calling
445 * task->thread.sve_state must point to at least sve_state_size(task)
446 * bytes of allocated kernel memory.
447 * task->thread.uw.fpsimd_state must be up to date before calling this
450 static void fpsimd_to_sve(struct task_struct *task)
453 void *sst = task->thread.sve_state;
454 struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
456 if (!system_supports_sve())
459 vq = sve_vq_from_vl(task->thread.sve_vl);
460 __fpsimd_to_sve(sst, fst, vq);
464 * Transfer the SVE state in task->thread.sve_state to
465 * task->thread.uw.fpsimd_state.
467 * Task can be a non-runnable task, or current. In the latter case,
468 * the caller must have ownership of the cpu FPSIMD context before calling
470 * task->thread.sve_state must point to at least sve_state_size(task)
471 * bytes of allocated kernel memory.
472 * task->thread.sve_state must be up to date before calling this function.
474 static void sve_to_fpsimd(struct task_struct *task)
477 void const *sst = task->thread.sve_state;
478 struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state;
480 __uint128_t const *p;
482 if (!system_supports_sve())
485 vq = sve_vq_from_vl(task->thread.sve_vl);
486 for (i = 0; i < SVE_NUM_ZREGS; ++i) {
487 p = (__uint128_t const *)ZREG(sst, vq, i);
488 fst->vregs[i] = arm64_le128_to_cpu(*p);
492 #ifdef CONFIG_ARM64_SVE
495 * Return how many bytes of memory are required to store the full SVE
496 * state for task, given task's currently configured vector length.
498 size_t sve_state_size(struct task_struct const *task)
500 return SVE_SIG_REGS_SIZE(sve_vq_from_vl(task->thread.sve_vl));
504 * Ensure that task->thread.sve_state is allocated and sufficiently large.
506 * This function should be used only in preparation for replacing
507 * task->thread.sve_state with new data. The memory is always zeroed
508 * here to prevent stale data from showing through: this is done in
509 * the interest of testability and predictability: except in the
510 * do_sve_acc() case, there is no ABI requirement to hide stale data
511 * written previously be task.
513 void sve_alloc(struct task_struct *task)
515 if (task->thread.sve_state) {
516 memset(task->thread.sve_state, 0, sve_state_size(current));
520 /* This is a small allocation (maximum ~8KB) and Should Not Fail. */
521 task->thread.sve_state =
522 kzalloc(sve_state_size(task), GFP_KERNEL);
525 * If future SVE revisions can have larger vectors though,
526 * this may cease to be true:
528 BUG_ON(!task->thread.sve_state);
533 * Ensure that task->thread.sve_state is up to date with respect to
534 * the user task, irrespective of when SVE is in use or not.
536 * This should only be called by ptrace. task must be non-runnable.
537 * task->thread.sve_state must point to at least sve_state_size(task)
538 * bytes of allocated kernel memory.
540 void fpsimd_sync_to_sve(struct task_struct *task)
542 if (!test_tsk_thread_flag(task, TIF_SVE))
547 * Ensure that task->thread.uw.fpsimd_state is up to date with respect to
548 * the user task, irrespective of whether SVE is in use or not.
550 * This should only be called by ptrace. task must be non-runnable.
551 * task->thread.sve_state must point to at least sve_state_size(task)
552 * bytes of allocated kernel memory.
554 void sve_sync_to_fpsimd(struct task_struct *task)
556 if (test_tsk_thread_flag(task, TIF_SVE))
561 * Ensure that task->thread.sve_state is up to date with respect to
562 * the task->thread.uw.fpsimd_state.
564 * This should only be called by ptrace to merge new FPSIMD register
565 * values into a task for which SVE is currently active.
566 * task must be non-runnable.
567 * task->thread.sve_state must point to at least sve_state_size(task)
568 * bytes of allocated kernel memory.
569 * task->thread.uw.fpsimd_state must already have been initialised with
570 * the new FPSIMD register values to be merged in.
572 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
575 void *sst = task->thread.sve_state;
576 struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
578 if (!test_tsk_thread_flag(task, TIF_SVE))
581 vq = sve_vq_from_vl(task->thread.sve_vl);
583 memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
584 __fpsimd_to_sve(sst, fst, vq);
587 int sve_set_vector_length(struct task_struct *task,
588 unsigned long vl, unsigned long flags)
590 if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
591 PR_SVE_SET_VL_ONEXEC))
594 if (!sve_vl_valid(vl))
598 * Clamp to the maximum vector length that VL-agnostic SVE code can
599 * work with. A flag may be assigned in the future to allow setting
600 * of larger vector lengths without confusing older software.
602 if (vl > SVE_VL_ARCH_MAX)
603 vl = SVE_VL_ARCH_MAX;
605 vl = find_supported_vector_length(vl);
607 if (flags & (PR_SVE_VL_INHERIT |
608 PR_SVE_SET_VL_ONEXEC))
609 task->thread.sve_vl_onexec = vl;
611 /* Reset VL to system default on next exec: */
612 task->thread.sve_vl_onexec = 0;
614 /* Only actually set the VL if not deferred: */
615 if (flags & PR_SVE_SET_VL_ONEXEC)
618 if (vl == task->thread.sve_vl)
622 * To ensure the FPSIMD bits of the SVE vector registers are preserved,
623 * write any live register state back to task_struct, and convert to a
626 if (task == current) {
627 get_cpu_fpsimd_context();
632 fpsimd_flush_task_state(task);
633 if (test_and_clear_tsk_thread_flag(task, TIF_SVE))
637 put_cpu_fpsimd_context();
640 * Force reallocation of task SVE state to the correct size
645 task->thread.sve_vl = vl;
648 update_tsk_thread_flag(task, TIF_SVE_VL_INHERIT,
649 flags & PR_SVE_VL_INHERIT);
655 * Encode the current vector length and flags for return.
656 * This is only required for prctl(): ptrace has separate fields
658 * flags are as for sve_set_vector_length().
660 static int sve_prctl_status(unsigned long flags)
664 if (flags & PR_SVE_SET_VL_ONEXEC)
665 ret = current->thread.sve_vl_onexec;
667 ret = current->thread.sve_vl;
669 if (test_thread_flag(TIF_SVE_VL_INHERIT))
670 ret |= PR_SVE_VL_INHERIT;
676 int sve_set_current_vl(unsigned long arg)
678 unsigned long vl, flags;
681 vl = arg & PR_SVE_VL_LEN_MASK;
684 if (!system_supports_sve() || is_compat_task())
687 ret = sve_set_vector_length(current, vl, flags);
691 return sve_prctl_status(flags);
695 int sve_get_current_vl(void)
697 if (!system_supports_sve() || is_compat_task())
700 return sve_prctl_status(0);
703 static void sve_probe_vqs(DECLARE_BITMAP(map, SVE_VQ_MAX))
708 bitmap_zero(map, SVE_VQ_MAX);
710 zcr = ZCR_ELx_LEN_MASK;
711 zcr = read_sysreg_s(SYS_ZCR_EL1) & ~zcr;
713 for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
714 write_sysreg_s(zcr | (vq - 1), SYS_ZCR_EL1); /* self-syncing */
716 vq = sve_vq_from_vl(vl); /* skip intervening lengths */
717 set_bit(__vq_to_bit(vq), map);
722 * Initialise the set of known supported VQs for the boot CPU.
723 * This is called during kernel boot, before secondary CPUs are brought up.
725 void __init sve_init_vq_map(void)
727 sve_probe_vqs(sve_vq_map);
728 bitmap_copy(sve_vq_partial_map, sve_vq_map, SVE_VQ_MAX);
732 * If we haven't committed to the set of supported VQs yet, filter out
733 * those not supported by the current CPU.
734 * This function is called during the bring-up of early secondary CPUs only.
736 void sve_update_vq_map(void)
738 DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
740 sve_probe_vqs(tmp_map);
741 bitmap_and(sve_vq_map, sve_vq_map, tmp_map, SVE_VQ_MAX);
742 bitmap_or(sve_vq_partial_map, sve_vq_partial_map, tmp_map, SVE_VQ_MAX);
746 * Check whether the current CPU supports all VQs in the committed set.
747 * This function is called during the bring-up of late secondary CPUs only.
749 int sve_verify_vq_map(void)
751 DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
754 sve_probe_vqs(tmp_map);
756 bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
757 if (bitmap_intersects(tmp_map, sve_vq_map, SVE_VQ_MAX)) {
758 pr_warn("SVE: cpu%d: Required vector length(s) missing\n",
763 if (!IS_ENABLED(CONFIG_KVM) || !is_hyp_mode_available())
767 * For KVM, it is necessary to ensure that this CPU doesn't
768 * support any vector length that guests may have probed as
772 /* Recover the set of supported VQs: */
773 bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
774 /* Find VQs supported that are not globally supported: */
775 bitmap_andnot(tmp_map, tmp_map, sve_vq_map, SVE_VQ_MAX);
777 /* Find the lowest such VQ, if any: */
778 b = find_last_bit(tmp_map, SVE_VQ_MAX);
780 return 0; /* no mismatches */
783 * Mismatches above sve_max_virtualisable_vl are fine, since
784 * no guest is allowed to configure ZCR_EL2.LEN to exceed this:
786 if (sve_vl_from_vq(__bit_to_vq(b)) <= sve_max_virtualisable_vl) {
787 pr_warn("SVE: cpu%d: Unsupported vector length(s) present\n",
795 static void __init sve_efi_setup(void)
797 if (!IS_ENABLED(CONFIG_EFI))
801 * alloc_percpu() warns and prints a backtrace if this goes wrong.
802 * This is evidence of a crippled system and we are returning void,
803 * so no attempt is made to handle this situation here.
805 if (!sve_vl_valid(sve_max_vl))
808 efi_sve_state = __alloc_percpu(
809 SVE_SIG_REGS_SIZE(sve_vq_from_vl(sve_max_vl)), SVE_VQ_BYTES);
816 panic("Cannot allocate percpu memory for EFI SVE save/restore");
820 * Enable SVE for EL1.
821 * Intended for use by the cpufeatures code during CPU boot.
823 void sve_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
825 write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
830 * Read the pseudo-ZCR used by cpufeatures to identify the supported SVE
833 * Use only if SVE is present.
834 * This function clobbers the SVE vector length.
836 u64 read_zcr_features(void)
842 * Set the maximum possible VL, and write zeroes to all other
843 * bits to see if they stick.
845 sve_kernel_enable(NULL);
846 write_sysreg_s(ZCR_ELx_LEN_MASK, SYS_ZCR_EL1);
848 zcr = read_sysreg_s(SYS_ZCR_EL1);
849 zcr &= ~(u64)ZCR_ELx_LEN_MASK; /* find sticky 1s outside LEN field */
850 vq_max = sve_vq_from_vl(sve_get_vl());
851 zcr |= vq_max - 1; /* set LEN field to maximum effective value */
856 void __init sve_setup(void)
859 DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
862 if (!system_supports_sve())
866 * The SVE architecture mandates support for 128-bit vectors,
867 * so sve_vq_map must have at least SVE_VQ_MIN set.
868 * If something went wrong, at least try to patch it up:
870 if (WARN_ON(!test_bit(__vq_to_bit(SVE_VQ_MIN), sve_vq_map)))
871 set_bit(__vq_to_bit(SVE_VQ_MIN), sve_vq_map);
873 zcr = read_sanitised_ftr_reg(SYS_ZCR_EL1);
874 sve_max_vl = sve_vl_from_vq((zcr & ZCR_ELx_LEN_MASK) + 1);
877 * Sanity-check that the max VL we determined through CPU features
878 * corresponds properly to sve_vq_map. If not, do our best:
880 if (WARN_ON(sve_max_vl != find_supported_vector_length(sve_max_vl)))
881 sve_max_vl = find_supported_vector_length(sve_max_vl);
884 * For the default VL, pick the maximum supported value <= 64.
885 * VL == 64 is guaranteed not to grow the signal frame.
887 set_sve_default_vl(find_supported_vector_length(64));
889 bitmap_andnot(tmp_map, sve_vq_partial_map, sve_vq_map,
892 b = find_last_bit(tmp_map, SVE_VQ_MAX);
894 /* No non-virtualisable VLs found */
895 sve_max_virtualisable_vl = SVE_VQ_MAX;
896 else if (WARN_ON(b == SVE_VQ_MAX - 1))
897 /* No virtualisable VLs? This is architecturally forbidden. */
898 sve_max_virtualisable_vl = SVE_VQ_MIN;
899 else /* b + 1 < SVE_VQ_MAX */
900 sve_max_virtualisable_vl = sve_vl_from_vq(__bit_to_vq(b + 1));
902 if (sve_max_virtualisable_vl > sve_max_vl)
903 sve_max_virtualisable_vl = sve_max_vl;
905 pr_info("SVE: maximum available vector length %u bytes per vector\n",
907 pr_info("SVE: default vector length %u bytes per vector\n",
908 get_sve_default_vl());
910 /* KVM decides whether to support mismatched systems. Just warn here: */
911 if (sve_max_virtualisable_vl < sve_max_vl)
912 pr_warn("SVE: unvirtualisable vector lengths present\n");
918 * Called from the put_task_struct() path, which cannot get here
919 * unless dead_task is really dead and not schedulable.
921 void fpsimd_release_task(struct task_struct *dead_task)
923 __sve_free(dead_task);
926 #endif /* CONFIG_ARM64_SVE */
931 * Storage is allocated for the full SVE state, the current FPSIMD
932 * register contents are migrated across, and the access trap is
935 * TIF_SVE should be clear on entry: otherwise, fpsimd_restore_current_state()
936 * would have disabled the SVE access trap for userspace during
937 * ret_to_user, making an SVE access trap impossible in that case.
939 void do_sve_acc(unsigned int esr, struct pt_regs *regs)
941 /* Even if we chose not to use SVE, the hardware could still trap: */
942 if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
943 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
949 get_cpu_fpsimd_context();
951 if (test_and_set_thread_flag(TIF_SVE))
952 WARN_ON(1); /* SVE access shouldn't have trapped */
955 * Convert the FPSIMD state to SVE, zeroing all the state that
956 * is not shared with FPSIMD. If (as is likely) the current
957 * state is live in the registers then do this there and
958 * update our metadata for the current task including
959 * disabling the trap, otherwise update our in-memory copy.
961 if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
962 unsigned long vq_minus_one =
963 sve_vq_from_vl(current->thread.sve_vl) - 1;
964 sve_set_vq(vq_minus_one);
965 sve_flush_live(vq_minus_one);
966 fpsimd_bind_task_to_cpu();
968 fpsimd_to_sve(current);
971 put_cpu_fpsimd_context();
975 * Trapped FP/ASIMD access.
977 void do_fpsimd_acc(unsigned int esr, struct pt_regs *regs)
979 /* TODO: implement lazy context saving/restoring */
984 * Raise a SIGFPE for the current process.
986 void do_fpsimd_exc(unsigned int esr, struct pt_regs *regs)
988 unsigned int si_code = FPE_FLTUNK;
990 if (esr & ESR_ELx_FP_EXC_TFV) {
992 si_code = FPE_FLTINV;
993 else if (esr & FPEXC_DZF)
994 si_code = FPE_FLTDIV;
995 else if (esr & FPEXC_OFF)
996 si_code = FPE_FLTOVF;
997 else if (esr & FPEXC_UFF)
998 si_code = FPE_FLTUND;
999 else if (esr & FPEXC_IXF)
1000 si_code = FPE_FLTRES;
1003 send_sig_fault(SIGFPE, si_code,
1004 (void __user *)instruction_pointer(regs),
1008 void fpsimd_thread_switch(struct task_struct *next)
1010 bool wrong_task, wrong_cpu;
1012 if (!system_supports_fpsimd())
1015 __get_cpu_fpsimd_context();
1017 /* Save unsaved fpsimd state, if any: */
1021 * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's
1022 * state. For kernel threads, FPSIMD registers are never loaded
1023 * and wrong_task and wrong_cpu will always be true.
1025 wrong_task = __this_cpu_read(fpsimd_last_state.st) !=
1026 &next->thread.uw.fpsimd_state;
1027 wrong_cpu = next->thread.fpsimd_cpu != smp_processor_id();
1029 update_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE,
1030 wrong_task || wrong_cpu);
1032 __put_cpu_fpsimd_context();
1035 void fpsimd_flush_thread(void)
1037 int vl, supported_vl;
1039 if (!system_supports_fpsimd())
1042 get_cpu_fpsimd_context();
1044 fpsimd_flush_task_state(current);
1045 memset(¤t->thread.uw.fpsimd_state, 0,
1046 sizeof(current->thread.uw.fpsimd_state));
1048 if (system_supports_sve()) {
1049 clear_thread_flag(TIF_SVE);
1053 * Reset the task vector length as required.
1054 * This is where we ensure that all user tasks have a valid
1055 * vector length configured: no kernel task can become a user
1056 * task without an exec and hence a call to this function.
1057 * By the time the first call to this function is made, all
1058 * early hardware probing is complete, so __sve_default_vl
1060 * If a bug causes this to go wrong, we make some noise and
1061 * try to fudge thread.sve_vl to a safe value here.
1063 vl = current->thread.sve_vl_onexec ?
1064 current->thread.sve_vl_onexec : get_sve_default_vl();
1066 if (WARN_ON(!sve_vl_valid(vl)))
1069 supported_vl = find_supported_vector_length(vl);
1070 if (WARN_ON(supported_vl != vl))
1073 current->thread.sve_vl = vl;
1076 * If the task is not set to inherit, ensure that the vector
1077 * length will be reset by a subsequent exec:
1079 if (!test_thread_flag(TIF_SVE_VL_INHERIT))
1080 current->thread.sve_vl_onexec = 0;
1083 put_cpu_fpsimd_context();
1087 * Save the userland FPSIMD state of 'current' to memory, but only if the state
1088 * currently held in the registers does in fact belong to 'current'
1090 void fpsimd_preserve_current_state(void)
1092 if (!system_supports_fpsimd())
1095 get_cpu_fpsimd_context();
1097 put_cpu_fpsimd_context();
1101 * Like fpsimd_preserve_current_state(), but ensure that
1102 * current->thread.uw.fpsimd_state is updated so that it can be copied to
1105 void fpsimd_signal_preserve_current_state(void)
1107 fpsimd_preserve_current_state();
1108 if (test_thread_flag(TIF_SVE))
1109 sve_to_fpsimd(current);
1113 * Associate current's FPSIMD context with this cpu
1114 * The caller must have ownership of the cpu FPSIMD context before calling
1117 static void fpsimd_bind_task_to_cpu(void)
1119 struct fpsimd_last_state_struct *last =
1120 this_cpu_ptr(&fpsimd_last_state);
1122 WARN_ON(!system_supports_fpsimd());
1123 last->st = ¤t->thread.uw.fpsimd_state;
1124 last->sve_state = current->thread.sve_state;
1125 last->sve_vl = current->thread.sve_vl;
1126 current->thread.fpsimd_cpu = smp_processor_id();
1128 if (system_supports_sve()) {
1129 /* Toggle SVE trapping for userspace if needed */
1130 if (test_thread_flag(TIF_SVE))
1135 /* Serialised by exception return to user */
1139 void fpsimd_bind_state_to_cpu(struct user_fpsimd_state *st, void *sve_state,
1140 unsigned int sve_vl)
1142 struct fpsimd_last_state_struct *last =
1143 this_cpu_ptr(&fpsimd_last_state);
1145 WARN_ON(!system_supports_fpsimd());
1146 WARN_ON(!in_softirq() && !irqs_disabled());
1149 last->sve_state = sve_state;
1150 last->sve_vl = sve_vl;
1154 * Load the userland FPSIMD state of 'current' from memory, but only if the
1155 * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1156 * state of 'current'
1158 void fpsimd_restore_current_state(void)
1161 * For the tasks that were created before we detected the absence of
1162 * FP/SIMD, the TIF_FOREIGN_FPSTATE could be set via fpsimd_thread_switch(),
1163 * e.g, init. This could be then inherited by the children processes.
1164 * If we later detect that the system doesn't support FP/SIMD,
1165 * we must clear the flag for all the tasks to indicate that the
1166 * FPSTATE is clean (as we can't have one) to avoid looping for ever in
1167 * do_notify_resume().
1169 if (!system_supports_fpsimd()) {
1170 clear_thread_flag(TIF_FOREIGN_FPSTATE);
1174 get_cpu_fpsimd_context();
1176 if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1178 fpsimd_bind_task_to_cpu();
1181 put_cpu_fpsimd_context();
1185 * Load an updated userland FPSIMD state for 'current' from memory and set the
1186 * flag that indicates that the FPSIMD register contents are the most recent
1187 * FPSIMD state of 'current'
1189 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1191 if (WARN_ON(!system_supports_fpsimd()))
1194 get_cpu_fpsimd_context();
1196 current->thread.uw.fpsimd_state = *state;
1197 if (test_thread_flag(TIF_SVE))
1198 fpsimd_to_sve(current);
1201 fpsimd_bind_task_to_cpu();
1203 clear_thread_flag(TIF_FOREIGN_FPSTATE);
1205 put_cpu_fpsimd_context();
1209 * Invalidate live CPU copies of task t's FPSIMD state
1211 * This function may be called with preemption enabled. The barrier()
1212 * ensures that the assignment to fpsimd_cpu is visible to any
1213 * preemption/softirq that could race with set_tsk_thread_flag(), so
1214 * that TIF_FOREIGN_FPSTATE cannot be spuriously re-cleared.
1216 * The final barrier ensures that TIF_FOREIGN_FPSTATE is seen set by any
1219 void fpsimd_flush_task_state(struct task_struct *t)
1221 t->thread.fpsimd_cpu = NR_CPUS;
1223 * If we don't support fpsimd, bail out after we have
1224 * reset the fpsimd_cpu for this task and clear the
1227 if (!system_supports_fpsimd())
1230 set_tsk_thread_flag(t, TIF_FOREIGN_FPSTATE);
1236 * Invalidate any task's FPSIMD state that is present on this cpu.
1237 * The FPSIMD context should be acquired with get_cpu_fpsimd_context()
1238 * before calling this function.
1240 static void fpsimd_flush_cpu_state(void)
1242 WARN_ON(!system_supports_fpsimd());
1243 __this_cpu_write(fpsimd_last_state.st, NULL);
1244 set_thread_flag(TIF_FOREIGN_FPSTATE);
1248 * Save the FPSIMD state to memory and invalidate cpu view.
1249 * This function must be called with preemption disabled.
1251 void fpsimd_save_and_flush_cpu_state(void)
1253 if (!system_supports_fpsimd())
1255 WARN_ON(preemptible());
1256 __get_cpu_fpsimd_context();
1258 fpsimd_flush_cpu_state();
1259 __put_cpu_fpsimd_context();
1262 #ifdef CONFIG_KERNEL_MODE_NEON
1265 * Kernel-side NEON support functions
1269 * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1272 * Must not be called unless may_use_simd() returns true.
1273 * Task context in the FPSIMD registers is saved back to memory as necessary.
1275 * A matching call to kernel_neon_end() must be made before returning from the
1278 * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1281 void kernel_neon_begin(void)
1283 if (WARN_ON(!system_supports_fpsimd()))
1286 BUG_ON(!may_use_simd());
1288 get_cpu_fpsimd_context();
1290 /* Save unsaved fpsimd state, if any: */
1293 /* Invalidate any task state remaining in the fpsimd regs: */
1294 fpsimd_flush_cpu_state();
1296 EXPORT_SYMBOL(kernel_neon_begin);
1299 * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1301 * Must be called from a context in which kernel_neon_begin() was previously
1302 * called, with no call to kernel_neon_end() in the meantime.
1304 * The caller must not use the FPSIMD registers after this function is called,
1305 * unless kernel_neon_begin() is called again in the meantime.
1307 void kernel_neon_end(void)
1309 if (!system_supports_fpsimd())
1312 put_cpu_fpsimd_context();
1314 EXPORT_SYMBOL(kernel_neon_end);
1318 static DEFINE_PER_CPU(struct user_fpsimd_state, efi_fpsimd_state);
1319 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1320 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1323 * EFI runtime services support functions
1325 * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1326 * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1327 * is always used rather than being an optional accelerator.
1329 * These functions provide the necessary support for ensuring FPSIMD
1330 * save/restore in the contexts from which EFI is used.
1332 * Do not use them for any other purpose -- if tempted to do so, you are
1333 * either doing something wrong or you need to propose some refactoring.
1337 * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1339 void __efi_fpsimd_begin(void)
1341 if (!system_supports_fpsimd())
1344 WARN_ON(preemptible());
1346 if (may_use_simd()) {
1347 kernel_neon_begin();
1350 * If !efi_sve_state, SVE can't be in use yet and doesn't need
1353 if (system_supports_sve() && likely(efi_sve_state)) {
1354 char *sve_state = this_cpu_ptr(efi_sve_state);
1356 __this_cpu_write(efi_sve_state_used, true);
1358 sve_save_state(sve_state + sve_ffr_offset(sve_max_vl),
1359 &this_cpu_ptr(&efi_fpsimd_state)->fpsr);
1361 fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
1364 __this_cpu_write(efi_fpsimd_state_used, true);
1369 * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
1371 void __efi_fpsimd_end(void)
1373 if (!system_supports_fpsimd())
1376 if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
1379 if (system_supports_sve() &&
1380 likely(__this_cpu_read(efi_sve_state_used))) {
1381 char const *sve_state = this_cpu_ptr(efi_sve_state);
1383 sve_load_state(sve_state + sve_ffr_offset(sve_max_vl),
1384 &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
1385 sve_vq_from_vl(sve_get_vl()) - 1);
1387 __this_cpu_write(efi_sve_state_used, false);
1389 fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
1394 #endif /* CONFIG_EFI */
1396 #endif /* CONFIG_KERNEL_MODE_NEON */
1398 #ifdef CONFIG_CPU_PM
1399 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
1400 unsigned long cmd, void *v)
1404 fpsimd_save_and_flush_cpu_state();
1408 case CPU_PM_ENTER_FAILED:
1415 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
1416 .notifier_call = fpsimd_cpu_pm_notifier,
1419 static void __init fpsimd_pm_init(void)
1421 cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
1425 static inline void fpsimd_pm_init(void) { }
1426 #endif /* CONFIG_CPU_PM */
1428 #ifdef CONFIG_HOTPLUG_CPU
1429 static int fpsimd_cpu_dead(unsigned int cpu)
1431 per_cpu(fpsimd_last_state.st, cpu) = NULL;
1435 static inline void fpsimd_hotplug_init(void)
1437 cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
1438 NULL, fpsimd_cpu_dead);
1442 static inline void fpsimd_hotplug_init(void) { }
1446 * FP/SIMD support code initialisation.
1448 static int __init fpsimd_init(void)
1450 if (cpu_have_named_feature(FP)) {
1452 fpsimd_hotplug_init();
1454 pr_notice("Floating-point is not implemented\n");
1457 if (!cpu_have_named_feature(ASIMD))
1458 pr_notice("Advanced SIMD is not implemented\n");
1460 return sve_sysctl_init();
1462 core_initcall(fpsimd_init);