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/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>
36 #include <asm/exception.h>
37 #include <asm/fpsimd.h>
38 #include <asm/cpufeature.h>
39 #include <asm/cputype.h>
41 #include <asm/processor.h>
43 #include <asm/sigcontext.h>
44 #include <asm/sysreg.h>
45 #include <asm/traps.h>
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)
56 * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
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.
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.
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.
78 * As an optimization, we use the thread_info flag TIF_FOREIGN_FPSTATE to
79 * indicate whether or not the userland FPSIMD state of the current task is
80 * present in the registers. The flag is set unless the FPSIMD registers of this
81 * CPU currently contain the most recent userland FPSIMD state of the current
82 * task. If the task is behaving as a VMM, then this is will be managed by
83 * KVM which will clear it to indicate that the vcpu FPSIMD state is currently
84 * loaded on the CPU, allowing the state to be saved if a FPSIMD-aware
85 * softirq kicks in. Upon vcpu_put(), KVM will save the vcpu FP state and
86 * flag the register state as invalid.
88 * In order to allow softirq handlers to use FPSIMD, kernel_neon_begin() may
89 * save the task's FPSIMD context back to task_struct from softirq context.
90 * To prevent this from racing with the manipulation of the task's FPSIMD state
91 * from task context and thereby corrupting the state, it is necessary to
92 * protect any manipulation of a task's fpsimd_state or TIF_FOREIGN_FPSTATE
93 * flag with {, __}get_cpu_fpsimd_context(). This will still allow softirqs to
94 * run but prevent them to use FPSIMD.
96 * For a certain task, the sequence may look something like this:
97 * - the task gets scheduled in; if both the task's fpsimd_cpu field
98 * contains the id of the current CPU, and the CPU's fpsimd_last_state per-cpu
99 * variable points to the task's fpsimd_state, the TIF_FOREIGN_FPSTATE flag is
100 * cleared, otherwise it is set;
102 * - the task returns to userland; if TIF_FOREIGN_FPSTATE is set, the task's
103 * userland FPSIMD state is copied from memory to the registers, the task's
104 * fpsimd_cpu field is set to the id of the current CPU, the current
105 * CPU's fpsimd_last_state pointer is set to this task's fpsimd_state and the
106 * TIF_FOREIGN_FPSTATE flag is cleared;
108 * - the task executes an ordinary syscall; upon return to userland, the
109 * TIF_FOREIGN_FPSTATE flag will still be cleared, so no FPSIMD state is
112 * - the task executes a syscall which executes some NEON instructions; this is
113 * preceded by a call to kernel_neon_begin(), which copies the task's FPSIMD
114 * register contents to memory, clears the fpsimd_last_state per-cpu variable
115 * and sets the TIF_FOREIGN_FPSTATE flag;
117 * - the task gets preempted after kernel_neon_end() is called; as we have not
118 * returned from the 2nd syscall yet, TIF_FOREIGN_FPSTATE is still set so
119 * whatever is in the FPSIMD registers is not saved to memory, but discarded.
122 static DEFINE_PER_CPU(struct cpu_fp_state, fpsimd_last_state);
124 __ro_after_init struct vl_info vl_info[ARM64_VEC_MAX] = {
125 #ifdef CONFIG_ARM64_SVE
127 .type = ARM64_VEC_SVE,
129 .min_vl = SVE_VL_MIN,
130 .max_vl = SVE_VL_MIN,
131 .max_virtualisable_vl = SVE_VL_MIN,
134 #ifdef CONFIG_ARM64_SME
136 .type = ARM64_VEC_SME,
142 static unsigned int vec_vl_inherit_flag(enum vec_type type)
146 return TIF_SVE_VL_INHERIT;
148 return TIF_SME_VL_INHERIT;
156 int __default_vl; /* Default VL for tasks */
159 static struct vl_config vl_config[ARM64_VEC_MAX];
161 static inline int get_default_vl(enum vec_type type)
163 return READ_ONCE(vl_config[type].__default_vl);
166 #ifdef CONFIG_ARM64_SVE
168 static inline int get_sve_default_vl(void)
170 return get_default_vl(ARM64_VEC_SVE);
173 static inline void set_default_vl(enum vec_type type, int val)
175 WRITE_ONCE(vl_config[type].__default_vl, val);
178 static inline void set_sve_default_vl(int val)
180 set_default_vl(ARM64_VEC_SVE, val);
183 static void __percpu *efi_sve_state;
185 #else /* ! CONFIG_ARM64_SVE */
187 /* Dummy declaration for code that will be optimised out: */
188 extern void __percpu *efi_sve_state;
190 #endif /* ! CONFIG_ARM64_SVE */
192 #ifdef CONFIG_ARM64_SME
194 static int get_sme_default_vl(void)
196 return get_default_vl(ARM64_VEC_SME);
199 static void set_sme_default_vl(int val)
201 set_default_vl(ARM64_VEC_SME, val);
204 static void sme_free(struct task_struct *);
208 static inline void sme_free(struct task_struct *t) { }
212 DEFINE_PER_CPU(bool, fpsimd_context_busy);
213 EXPORT_PER_CPU_SYMBOL(fpsimd_context_busy);
215 static void fpsimd_bind_task_to_cpu(void);
217 static void __get_cpu_fpsimd_context(void)
219 bool busy = __this_cpu_xchg(fpsimd_context_busy, true);
225 * Claim ownership of the CPU FPSIMD context for use by the calling context.
227 * The caller may freely manipulate the FPSIMD context metadata until
228 * put_cpu_fpsimd_context() is called.
230 * The double-underscore version must only be called if you know the task
231 * can't be preempted.
233 * On RT kernels local_bh_disable() is not sufficient because it only
234 * serializes soft interrupt related sections via a local lock, but stays
235 * preemptible. Disabling preemption is the right choice here as bottom
236 * half processing is always in thread context on RT kernels so it
237 * implicitly prevents bottom half processing as well.
239 static void get_cpu_fpsimd_context(void)
241 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
245 __get_cpu_fpsimd_context();
248 static void __put_cpu_fpsimd_context(void)
250 bool busy = __this_cpu_xchg(fpsimd_context_busy, false);
252 WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */
256 * Release the CPU FPSIMD context.
258 * Must be called from a context in which get_cpu_fpsimd_context() was
259 * previously called, with no call to put_cpu_fpsimd_context() in the
262 static void put_cpu_fpsimd_context(void)
264 __put_cpu_fpsimd_context();
265 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
271 static bool have_cpu_fpsimd_context(void)
273 return !preemptible() && __this_cpu_read(fpsimd_context_busy);
276 unsigned int task_get_vl(const struct task_struct *task, enum vec_type type)
278 return task->thread.vl[type];
281 void task_set_vl(struct task_struct *task, enum vec_type type,
284 task->thread.vl[type] = vl;
287 unsigned int task_get_vl_onexec(const struct task_struct *task,
290 return task->thread.vl_onexec[type];
293 void task_set_vl_onexec(struct task_struct *task, enum vec_type type,
296 task->thread.vl_onexec[type] = vl;
300 * TIF_SME controls whether a task can use SME without trapping while
301 * in userspace, when TIF_SME is set then we must have storage
302 * alocated in sve_state and za_state to store the contents of both ZA
303 * and the SVE registers for both streaming and non-streaming modes.
305 * If both SVCR.ZA and SVCR.SM are disabled then at any point we
306 * may disable TIF_SME and reenable traps.
311 * TIF_SVE controls whether a task can use SVE without trapping while
312 * in userspace, and also (together with TIF_SME) the way a task's
313 * FPSIMD/SVE state is stored in thread_struct.
315 * The kernel uses this flag to track whether a user task is actively
316 * using SVE, and therefore whether full SVE register state needs to
317 * be tracked. If not, the cheaper FPSIMD context handling code can
318 * be used instead of the more costly SVE equivalents.
320 * * TIF_SVE or SVCR.SM set:
322 * The task can execute SVE instructions while in userspace without
323 * trapping to the kernel.
325 * During any syscall, the kernel may optionally clear TIF_SVE and
326 * discard the vector state except for the FPSIMD subset.
330 * An attempt by the user task to execute an SVE instruction causes
331 * do_sve_acc() to be called, which does some preparation and then
334 * During any syscall, the kernel may optionally clear TIF_SVE and
335 * discard the vector state except for the FPSIMD subset.
337 * The data will be stored in one of two formats:
339 * * FPSIMD only - FP_STATE_FPSIMD:
341 * When the FPSIMD only state stored task->thread.fp_type is set to
342 * FP_STATE_FPSIMD, the FPSIMD registers V0-V31 are encoded in
343 * task->thread.uw.fpsimd_state; bits [max : 128] for each of Z0-Z31 are
344 * logically zero but not stored anywhere; P0-P15 and FFR are not
345 * stored and have unspecified values from userspace's point of
346 * view. For hygiene purposes, the kernel zeroes them on next use,
347 * but userspace is discouraged from relying on this.
349 * task->thread.sve_state does not need to be non-NULL, valid or any
350 * particular size: it must not be dereferenced and any data stored
351 * there should be considered stale and not referenced.
353 * * SVE state - FP_STATE_SVE:
355 * When the full SVE state is stored task->thread.fp_type is set to
356 * FP_STATE_SVE and Z0-Z31 (incorporating Vn in bits[127:0] or the
357 * corresponding Zn), P0-P15 and FFR are encoded in in
358 * task->thread.sve_state, formatted appropriately for vector
359 * length task->thread.sve_vl or, if SVCR.SM is set,
360 * task->thread.sme_vl. The storage for the vector registers in
361 * task->thread.uw.fpsimd_state should be ignored.
363 * task->thread.sve_state must point to a valid buffer at least
364 * sve_state_size(task) bytes in size. The data stored in
365 * task->thread.uw.fpsimd_state.vregs should be considered stale
366 * and not referenced.
368 * * FPSR and FPCR are always stored in task->thread.uw.fpsimd_state
369 * irrespective of whether TIF_SVE is clear or set, since these are
370 * not vector length dependent.
374 * Update current's FPSIMD/SVE registers from thread_struct.
376 * This function should be called only when the FPSIMD/SVE state in
377 * thread_struct is known to be up to date, when preparing to enter
380 static void task_fpsimd_load(void)
382 bool restore_sve_regs = false;
385 WARN_ON(!system_supports_fpsimd());
386 WARN_ON(!have_cpu_fpsimd_context());
388 if (system_supports_sve()) {
389 switch (current->thread.fp_type) {
390 case FP_STATE_FPSIMD:
391 /* Stop tracking SVE for this task until next use. */
392 if (test_and_clear_thread_flag(TIF_SVE))
396 if (!thread_sm_enabled(¤t->thread) &&
397 !WARN_ON_ONCE(!test_and_set_thread_flag(TIF_SVE)))
400 if (test_thread_flag(TIF_SVE))
401 sve_set_vq(sve_vq_from_vl(task_get_sve_vl(current)) - 1);
403 restore_sve_regs = true;
408 * This indicates either a bug in
409 * fpsimd_save() or memory corruption, we
410 * should always record an explicit format
411 * when we save. We always at least have the
412 * memory allocated for FPSMID registers so
413 * try that and hope for the best.
416 clear_thread_flag(TIF_SVE);
421 /* Restore SME, override SVE register configuration if needed */
422 if (system_supports_sme()) {
423 unsigned long sme_vl = task_get_sme_vl(current);
425 /* Ensure VL is set up for restoring data */
426 if (test_thread_flag(TIF_SME))
427 sme_set_vq(sve_vq_from_vl(sme_vl) - 1);
429 write_sysreg_s(current->thread.svcr, SYS_SVCR);
431 if (thread_za_enabled(¤t->thread))
432 za_load_state(current->thread.za_state);
434 if (thread_sm_enabled(¤t->thread))
435 restore_ffr = system_supports_fa64();
438 if (restore_sve_regs) {
439 WARN_ON_ONCE(current->thread.fp_type != FP_STATE_SVE);
440 sve_load_state(sve_pffr(¤t->thread),
441 ¤t->thread.uw.fpsimd_state.fpsr,
444 WARN_ON_ONCE(current->thread.fp_type != FP_STATE_FPSIMD);
445 fpsimd_load_state(¤t->thread.uw.fpsimd_state);
450 * Ensure FPSIMD/SVE storage in memory for the loaded context is up to
451 * date with respect to the CPU registers. Note carefully that the
452 * current context is the context last bound to the CPU stored in
453 * last, if KVM is involved this may be the guest VM context rather
454 * than the host thread for the VM pointed to by current. This means
455 * that we must always reference the state storage via last rather
456 * than via current, if we are saving KVM state then it will have
457 * ensured that the type of registers to save is set in last->to_save.
459 static void fpsimd_save(void)
461 struct cpu_fp_state const *last =
462 this_cpu_ptr(&fpsimd_last_state);
463 /* set by fpsimd_bind_task_to_cpu() or fpsimd_bind_state_to_cpu() */
464 bool save_sve_regs = false;
468 WARN_ON(!system_supports_fpsimd());
469 WARN_ON(!have_cpu_fpsimd_context());
471 if (test_thread_flag(TIF_FOREIGN_FPSTATE))
475 * If a task is in a syscall the ABI allows us to only
476 * preserve the state shared with FPSIMD so don't bother
477 * saving the full SVE state in that case.
479 if ((last->to_save == FP_STATE_CURRENT && test_thread_flag(TIF_SVE) &&
480 !in_syscall(current_pt_regs())) ||
481 last->to_save == FP_STATE_SVE) {
482 save_sve_regs = true;
487 if (system_supports_sme()) {
488 u64 *svcr = last->svcr;
490 *svcr = read_sysreg_s(SYS_SVCR);
492 if (*svcr & SVCR_ZA_MASK)
493 za_save_state(last->za_state);
495 /* If we are in streaming mode override regular SVE. */
496 if (*svcr & SVCR_SM_MASK) {
497 save_sve_regs = true;
498 save_ffr = system_supports_fa64();
503 if (IS_ENABLED(CONFIG_ARM64_SVE) && save_sve_regs) {
504 /* Get the configured VL from RDVL, will account for SM */
505 if (WARN_ON(sve_get_vl() != vl)) {
507 * Can't save the user regs, so current would
508 * re-enter user with corrupt state.
509 * There's no way to recover, so kill it:
511 force_signal_inject(SIGKILL, SI_KERNEL, 0, 0);
515 sve_save_state((char *)last->sve_state +
517 &last->st->fpsr, save_ffr);
518 *last->fp_type = FP_STATE_SVE;
520 fpsimd_save_state(last->st);
521 *last->fp_type = FP_STATE_FPSIMD;
526 * All vector length selection from userspace comes through here.
527 * We're on a slow path, so some sanity-checks are included.
528 * If things go wrong there's a bug somewhere, but try to fall back to a
531 static unsigned int find_supported_vector_length(enum vec_type type,
534 struct vl_info *info = &vl_info[type];
536 int max_vl = info->max_vl;
538 if (WARN_ON(!sve_vl_valid(vl)))
541 if (WARN_ON(!sve_vl_valid(max_vl)))
542 max_vl = info->min_vl;
546 if (vl < info->min_vl)
549 bit = find_next_bit(info->vq_map, SVE_VQ_MAX,
550 __vq_to_bit(sve_vq_from_vl(vl)));
551 return sve_vl_from_vq(__bit_to_vq(bit));
554 #if defined(CONFIG_ARM64_SVE) && defined(CONFIG_SYSCTL)
556 static int vec_proc_do_default_vl(struct ctl_table *table, int write,
557 void *buffer, size_t *lenp, loff_t *ppos)
559 struct vl_info *info = table->extra1;
560 enum vec_type type = info->type;
562 int vl = get_default_vl(type);
563 struct ctl_table tmp_table = {
565 .maxlen = sizeof(vl),
568 ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
572 /* Writing -1 has the special meaning "set to max": */
576 if (!sve_vl_valid(vl))
579 set_default_vl(type, find_supported_vector_length(type, vl));
583 static struct ctl_table sve_default_vl_table[] = {
585 .procname = "sve_default_vector_length",
587 .proc_handler = vec_proc_do_default_vl,
588 .extra1 = &vl_info[ARM64_VEC_SVE],
593 static int __init sve_sysctl_init(void)
595 if (system_supports_sve())
596 if (!register_sysctl("abi", sve_default_vl_table))
602 #else /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
603 static int __init sve_sysctl_init(void) { return 0; }
604 #endif /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
606 #if defined(CONFIG_ARM64_SME) && defined(CONFIG_SYSCTL)
607 static struct ctl_table sme_default_vl_table[] = {
609 .procname = "sme_default_vector_length",
611 .proc_handler = vec_proc_do_default_vl,
612 .extra1 = &vl_info[ARM64_VEC_SME],
617 static int __init sme_sysctl_init(void)
619 if (system_supports_sme())
620 if (!register_sysctl("abi", sme_default_vl_table))
626 #else /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
627 static int __init sme_sysctl_init(void) { return 0; }
628 #endif /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
630 #define ZREG(sve_state, vq, n) ((char *)(sve_state) + \
631 (SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
633 #ifdef CONFIG_CPU_BIG_ENDIAN
634 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
637 u64 b = swab64(x >> 64);
639 return ((__uint128_t)a << 64) | b;
642 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
648 #define arm64_le128_to_cpu(x) arm64_cpu_to_le128(x)
650 static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst,
656 for (i = 0; i < SVE_NUM_ZREGS; ++i) {
657 p = (__uint128_t *)ZREG(sst, vq, i);
658 *p = arm64_cpu_to_le128(fst->vregs[i]);
663 * Transfer the FPSIMD state in task->thread.uw.fpsimd_state to
664 * task->thread.sve_state.
666 * Task can be a non-runnable task, or current. In the latter case,
667 * the caller must have ownership of the cpu FPSIMD context before calling
669 * task->thread.sve_state must point to at least sve_state_size(task)
670 * bytes of allocated kernel memory.
671 * task->thread.uw.fpsimd_state must be up to date before calling this
674 static void fpsimd_to_sve(struct task_struct *task)
677 void *sst = task->thread.sve_state;
678 struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
680 if (!system_supports_sve())
683 vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
684 __fpsimd_to_sve(sst, fst, vq);
688 * Transfer the SVE state in task->thread.sve_state to
689 * task->thread.uw.fpsimd_state.
691 * Task can be a non-runnable task, or current. In the latter case,
692 * the caller must have ownership of the cpu FPSIMD context before calling
694 * task->thread.sve_state must point to at least sve_state_size(task)
695 * bytes of allocated kernel memory.
696 * task->thread.sve_state must be up to date before calling this function.
698 static void sve_to_fpsimd(struct task_struct *task)
701 void const *sst = task->thread.sve_state;
702 struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state;
704 __uint128_t const *p;
706 if (!system_supports_sve())
709 vl = thread_get_cur_vl(&task->thread);
710 vq = sve_vq_from_vl(vl);
711 for (i = 0; i < SVE_NUM_ZREGS; ++i) {
712 p = (__uint128_t const *)ZREG(sst, vq, i);
713 fst->vregs[i] = arm64_le128_to_cpu(*p);
717 #ifdef CONFIG_ARM64_SVE
719 * Call __sve_free() directly only if you know task can't be scheduled
722 static void __sve_free(struct task_struct *task)
724 kfree(task->thread.sve_state);
725 task->thread.sve_state = NULL;
728 static void sve_free(struct task_struct *task)
730 WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
736 * Return how many bytes of memory are required to store the full SVE
737 * state for task, given task's currently configured vector length.
739 size_t sve_state_size(struct task_struct const *task)
743 if (system_supports_sve())
744 vl = task_get_sve_vl(task);
745 if (system_supports_sme())
746 vl = max(vl, task_get_sme_vl(task));
748 return SVE_SIG_REGS_SIZE(sve_vq_from_vl(vl));
752 * Ensure that task->thread.sve_state is allocated and sufficiently large.
754 * This function should be used only in preparation for replacing
755 * task->thread.sve_state with new data. The memory is always zeroed
756 * here to prevent stale data from showing through: this is done in
757 * the interest of testability and predictability: except in the
758 * do_sve_acc() case, there is no ABI requirement to hide stale data
759 * written previously be task.
761 void sve_alloc(struct task_struct *task, bool flush)
763 if (task->thread.sve_state) {
765 memset(task->thread.sve_state, 0,
766 sve_state_size(task));
770 /* This is a small allocation (maximum ~8KB) and Should Not Fail. */
771 task->thread.sve_state =
772 kzalloc(sve_state_size(task), GFP_KERNEL);
777 * Force the FPSIMD state shared with SVE to be updated in the SVE state
778 * even if the SVE state is the current active state.
780 * This should only be called by ptrace. task must be non-runnable.
781 * task->thread.sve_state must point to at least sve_state_size(task)
782 * bytes of allocated kernel memory.
784 void fpsimd_force_sync_to_sve(struct task_struct *task)
790 * Ensure that task->thread.sve_state is up to date with respect to
791 * the user task, irrespective of when SVE is in use or not.
793 * This should only be called by ptrace. task must be non-runnable.
794 * task->thread.sve_state must point to at least sve_state_size(task)
795 * bytes of allocated kernel memory.
797 void fpsimd_sync_to_sve(struct task_struct *task)
799 if (!test_tsk_thread_flag(task, TIF_SVE) &&
800 !thread_sm_enabled(&task->thread))
805 * Ensure that task->thread.uw.fpsimd_state is up to date with respect to
806 * the user task, irrespective of whether SVE is in use or not.
808 * This should only be called by ptrace. task must be non-runnable.
809 * task->thread.sve_state must point to at least sve_state_size(task)
810 * bytes of allocated kernel memory.
812 void sve_sync_to_fpsimd(struct task_struct *task)
814 if (task->thread.fp_type == FP_STATE_SVE)
819 * Ensure that task->thread.sve_state is up to date with respect to
820 * the task->thread.uw.fpsimd_state.
822 * This should only be called by ptrace to merge new FPSIMD register
823 * values into a task for which SVE is currently active.
824 * task must be non-runnable.
825 * task->thread.sve_state must point to at least sve_state_size(task)
826 * bytes of allocated kernel memory.
827 * task->thread.uw.fpsimd_state must already have been initialised with
828 * the new FPSIMD register values to be merged in.
830 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
833 void *sst = task->thread.sve_state;
834 struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
836 if (!test_tsk_thread_flag(task, TIF_SVE))
839 vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
841 memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
842 __fpsimd_to_sve(sst, fst, vq);
845 int vec_set_vector_length(struct task_struct *task, enum vec_type type,
846 unsigned long vl, unsigned long flags)
848 if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
849 PR_SVE_SET_VL_ONEXEC))
852 if (!sve_vl_valid(vl))
856 * Clamp to the maximum vector length that VL-agnostic code
857 * can work with. A flag may be assigned in the future to
858 * allow setting of larger vector lengths without confusing
861 if (vl > VL_ARCH_MAX)
864 vl = find_supported_vector_length(type, vl);
866 if (flags & (PR_SVE_VL_INHERIT |
867 PR_SVE_SET_VL_ONEXEC))
868 task_set_vl_onexec(task, type, vl);
870 /* Reset VL to system default on next exec: */
871 task_set_vl_onexec(task, type, 0);
873 /* Only actually set the VL if not deferred: */
874 if (flags & PR_SVE_SET_VL_ONEXEC)
877 if (vl == task_get_vl(task, type))
881 * To ensure the FPSIMD bits of the SVE vector registers are preserved,
882 * write any live register state back to task_struct, and convert to a
883 * regular FPSIMD thread.
885 if (task == current) {
886 get_cpu_fpsimd_context();
891 fpsimd_flush_task_state(task);
892 if (test_and_clear_tsk_thread_flag(task, TIF_SVE) ||
893 thread_sm_enabled(&task->thread)) {
895 task->thread.fp_type = FP_STATE_FPSIMD;
898 if (system_supports_sme() && type == ARM64_VEC_SME) {
899 task->thread.svcr &= ~(SVCR_SM_MASK |
901 clear_thread_flag(TIF_SME);
905 put_cpu_fpsimd_context();
908 * Force reallocation of task SVE and SME state to the correct
912 if (system_supports_sme() && type == ARM64_VEC_SME)
915 task_set_vl(task, type, vl);
918 update_tsk_thread_flag(task, vec_vl_inherit_flag(type),
919 flags & PR_SVE_VL_INHERIT);
925 * Encode the current vector length and flags for return.
926 * This is only required for prctl(): ptrace has separate fields.
927 * SVE and SME use the same bits for _ONEXEC and _INHERIT.
929 * flags are as for vec_set_vector_length().
931 static int vec_prctl_status(enum vec_type type, unsigned long flags)
935 if (flags & PR_SVE_SET_VL_ONEXEC)
936 ret = task_get_vl_onexec(current, type);
938 ret = task_get_vl(current, type);
940 if (test_thread_flag(vec_vl_inherit_flag(type)))
941 ret |= PR_SVE_VL_INHERIT;
947 int sve_set_current_vl(unsigned long arg)
949 unsigned long vl, flags;
952 vl = arg & PR_SVE_VL_LEN_MASK;
955 if (!system_supports_sve() || is_compat_task())
958 ret = vec_set_vector_length(current, ARM64_VEC_SVE, vl, flags);
962 return vec_prctl_status(ARM64_VEC_SVE, flags);
966 int sve_get_current_vl(void)
968 if (!system_supports_sve() || is_compat_task())
971 return vec_prctl_status(ARM64_VEC_SVE, 0);
974 #ifdef CONFIG_ARM64_SME
976 int sme_set_current_vl(unsigned long arg)
978 unsigned long vl, flags;
981 vl = arg & PR_SME_VL_LEN_MASK;
984 if (!system_supports_sme() || is_compat_task())
987 ret = vec_set_vector_length(current, ARM64_VEC_SME, vl, flags);
991 return vec_prctl_status(ARM64_VEC_SME, flags);
995 int sme_get_current_vl(void)
997 if (!system_supports_sme() || is_compat_task())
1000 return vec_prctl_status(ARM64_VEC_SME, 0);
1002 #endif /* CONFIG_ARM64_SME */
1004 static void vec_probe_vqs(struct vl_info *info,
1005 DECLARE_BITMAP(map, SVE_VQ_MAX))
1007 unsigned int vq, vl;
1009 bitmap_zero(map, SVE_VQ_MAX);
1011 for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
1012 write_vl(info->type, vq - 1); /* self-syncing */
1014 switch (info->type) {
1026 /* Minimum VL identified? */
1027 if (sve_vq_from_vl(vl) > vq)
1030 vq = sve_vq_from_vl(vl); /* skip intervening lengths */
1031 set_bit(__vq_to_bit(vq), map);
1036 * Initialise the set of known supported VQs for the boot CPU.
1037 * This is called during kernel boot, before secondary CPUs are brought up.
1039 void __init vec_init_vq_map(enum vec_type type)
1041 struct vl_info *info = &vl_info[type];
1042 vec_probe_vqs(info, info->vq_map);
1043 bitmap_copy(info->vq_partial_map, info->vq_map, SVE_VQ_MAX);
1047 * If we haven't committed to the set of supported VQs yet, filter out
1048 * those not supported by the current CPU.
1049 * This function is called during the bring-up of early secondary CPUs only.
1051 void vec_update_vq_map(enum vec_type type)
1053 struct vl_info *info = &vl_info[type];
1054 DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1056 vec_probe_vqs(info, tmp_map);
1057 bitmap_and(info->vq_map, info->vq_map, tmp_map, SVE_VQ_MAX);
1058 bitmap_or(info->vq_partial_map, info->vq_partial_map, tmp_map,
1063 * Check whether the current CPU supports all VQs in the committed set.
1064 * This function is called during the bring-up of late secondary CPUs only.
1066 int vec_verify_vq_map(enum vec_type type)
1068 struct vl_info *info = &vl_info[type];
1069 DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1072 vec_probe_vqs(info, tmp_map);
1074 bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1075 if (bitmap_intersects(tmp_map, info->vq_map, SVE_VQ_MAX)) {
1076 pr_warn("%s: cpu%d: Required vector length(s) missing\n",
1077 info->name, smp_processor_id());
1081 if (!IS_ENABLED(CONFIG_KVM) || !is_hyp_mode_available())
1085 * For KVM, it is necessary to ensure that this CPU doesn't
1086 * support any vector length that guests may have probed as
1090 /* Recover the set of supported VQs: */
1091 bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1092 /* Find VQs supported that are not globally supported: */
1093 bitmap_andnot(tmp_map, tmp_map, info->vq_map, SVE_VQ_MAX);
1095 /* Find the lowest such VQ, if any: */
1096 b = find_last_bit(tmp_map, SVE_VQ_MAX);
1097 if (b >= SVE_VQ_MAX)
1098 return 0; /* no mismatches */
1101 * Mismatches above sve_max_virtualisable_vl are fine, since
1102 * no guest is allowed to configure ZCR_EL2.LEN to exceed this:
1104 if (sve_vl_from_vq(__bit_to_vq(b)) <= info->max_virtualisable_vl) {
1105 pr_warn("%s: cpu%d: Unsupported vector length(s) present\n",
1106 info->name, smp_processor_id());
1113 static void __init sve_efi_setup(void)
1118 if (!IS_ENABLED(CONFIG_EFI))
1121 for (i = 0; i < ARRAY_SIZE(vl_info); i++)
1122 max_vl = max(vl_info[i].max_vl, max_vl);
1125 * alloc_percpu() warns and prints a backtrace if this goes wrong.
1126 * This is evidence of a crippled system and we are returning void,
1127 * so no attempt is made to handle this situation here.
1129 if (!sve_vl_valid(max_vl))
1132 efi_sve_state = __alloc_percpu(
1133 SVE_SIG_REGS_SIZE(sve_vq_from_vl(max_vl)), SVE_VQ_BYTES);
1140 panic("Cannot allocate percpu memory for EFI SVE save/restore");
1144 * Enable SVE for EL1.
1145 * Intended for use by the cpufeatures code during CPU boot.
1147 void sve_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1149 write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
1154 * Read the pseudo-ZCR used by cpufeatures to identify the supported SVE
1157 * Use only if SVE is present.
1158 * This function clobbers the SVE vector length.
1160 u64 read_zcr_features(void)
1163 unsigned int vq_max;
1166 * Set the maximum possible VL, and write zeroes to all other
1167 * bits to see if they stick.
1169 sve_kernel_enable(NULL);
1170 write_sysreg_s(ZCR_ELx_LEN_MASK, SYS_ZCR_EL1);
1172 zcr = read_sysreg_s(SYS_ZCR_EL1);
1173 zcr &= ~(u64)ZCR_ELx_LEN_MASK; /* find sticky 1s outside LEN field */
1174 vq_max = sve_vq_from_vl(sve_get_vl());
1175 zcr |= vq_max - 1; /* set LEN field to maximum effective value */
1180 void __init sve_setup(void)
1182 struct vl_info *info = &vl_info[ARM64_VEC_SVE];
1184 DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1187 if (!system_supports_sve())
1191 * The SVE architecture mandates support for 128-bit vectors,
1192 * so sve_vq_map must have at least SVE_VQ_MIN set.
1193 * If something went wrong, at least try to patch it up:
1195 if (WARN_ON(!test_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map)))
1196 set_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map);
1198 zcr = read_sanitised_ftr_reg(SYS_ZCR_EL1);
1199 info->max_vl = sve_vl_from_vq((zcr & ZCR_ELx_LEN_MASK) + 1);
1202 * Sanity-check that the max VL we determined through CPU features
1203 * corresponds properly to sve_vq_map. If not, do our best:
1205 if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SVE,
1207 info->max_vl = find_supported_vector_length(ARM64_VEC_SVE,
1211 * For the default VL, pick the maximum supported value <= 64.
1212 * VL == 64 is guaranteed not to grow the signal frame.
1214 set_sve_default_vl(find_supported_vector_length(ARM64_VEC_SVE, 64));
1216 bitmap_andnot(tmp_map, info->vq_partial_map, info->vq_map,
1219 b = find_last_bit(tmp_map, SVE_VQ_MAX);
1220 if (b >= SVE_VQ_MAX)
1221 /* No non-virtualisable VLs found */
1222 info->max_virtualisable_vl = SVE_VQ_MAX;
1223 else if (WARN_ON(b == SVE_VQ_MAX - 1))
1224 /* No virtualisable VLs? This is architecturally forbidden. */
1225 info->max_virtualisable_vl = SVE_VQ_MIN;
1226 else /* b + 1 < SVE_VQ_MAX */
1227 info->max_virtualisable_vl = sve_vl_from_vq(__bit_to_vq(b + 1));
1229 if (info->max_virtualisable_vl > info->max_vl)
1230 info->max_virtualisable_vl = info->max_vl;
1232 pr_info("%s: maximum available vector length %u bytes per vector\n",
1233 info->name, info->max_vl);
1234 pr_info("%s: default vector length %u bytes per vector\n",
1235 info->name, get_sve_default_vl());
1237 /* KVM decides whether to support mismatched systems. Just warn here: */
1238 if (sve_max_virtualisable_vl() < sve_max_vl())
1239 pr_warn("%s: unvirtualisable vector lengths present\n",
1246 * Called from the put_task_struct() path, which cannot get here
1247 * unless dead_task is really dead and not schedulable.
1249 void fpsimd_release_task(struct task_struct *dead_task)
1251 __sve_free(dead_task);
1252 sme_free(dead_task);
1255 #endif /* CONFIG_ARM64_SVE */
1257 #ifdef CONFIG_ARM64_SME
1260 * Ensure that task->thread.za_state is allocated and sufficiently large.
1262 * This function should be used only in preparation for replacing
1263 * task->thread.za_state with new data. The memory is always zeroed
1264 * here to prevent stale data from showing through: this is done in
1265 * the interest of testability and predictability, the architecture
1266 * guarantees that when ZA is enabled it will be zeroed.
1268 void sme_alloc(struct task_struct *task)
1270 if (task->thread.za_state) {
1271 memset(task->thread.za_state, 0, za_state_size(task));
1275 /* This could potentially be up to 64K. */
1276 task->thread.za_state =
1277 kzalloc(za_state_size(task), GFP_KERNEL);
1280 static void sme_free(struct task_struct *task)
1282 kfree(task->thread.za_state);
1283 task->thread.za_state = NULL;
1286 void sme_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1288 /* Set priority for all PEs to architecturally defined minimum */
1289 write_sysreg_s(read_sysreg_s(SYS_SMPRI_EL1) & ~SMPRI_EL1_PRIORITY_MASK,
1292 /* Allow SME in kernel */
1293 write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_SMEN_EL1EN, CPACR_EL1);
1296 /* Allow EL0 to access TPIDR2 */
1297 write_sysreg(read_sysreg(SCTLR_EL1) | SCTLR_ELx_ENTP2, SCTLR_EL1);
1302 * This must be called after sme_kernel_enable(), we rely on the
1303 * feature table being sorted to ensure this.
1305 void fa64_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1307 /* Allow use of FA64 */
1308 write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_FA64_MASK,
1313 * Read the pseudo-SMCR used by cpufeatures to identify the supported
1316 * Use only if SME is present.
1317 * This function clobbers the SME vector length.
1319 u64 read_smcr_features(void)
1322 unsigned int vq_max;
1324 sme_kernel_enable(NULL);
1328 * Set the maximum possible VL.
1330 write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_LEN_MASK,
1333 smcr = read_sysreg_s(SYS_SMCR_EL1);
1334 smcr &= ~(u64)SMCR_ELx_LEN_MASK; /* Only the LEN field */
1335 vq_max = sve_vq_from_vl(sve_get_vl());
1336 smcr |= vq_max - 1; /* set LEN field to maximum effective value */
1343 void __init sme_setup(void)
1345 struct vl_info *info = &vl_info[ARM64_VEC_SME];
1349 if (!system_supports_sme())
1353 * SME doesn't require any particular vector length be
1354 * supported but it does require at least one. We should have
1355 * disabled the feature entirely while bringing up CPUs but
1356 * let's double check here.
1358 WARN_ON(bitmap_empty(info->vq_map, SVE_VQ_MAX));
1360 min_bit = find_last_bit(info->vq_map, SVE_VQ_MAX);
1361 info->min_vl = sve_vl_from_vq(__bit_to_vq(min_bit));
1363 smcr = read_sanitised_ftr_reg(SYS_SMCR_EL1);
1364 info->max_vl = sve_vl_from_vq((smcr & SMCR_ELx_LEN_MASK) + 1);
1367 * Sanity-check that the max VL we determined through CPU features
1368 * corresponds properly to sme_vq_map. If not, do our best:
1370 if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SME,
1372 info->max_vl = find_supported_vector_length(ARM64_VEC_SME,
1375 WARN_ON(info->min_vl > info->max_vl);
1378 * For the default VL, pick the maximum supported value <= 32
1379 * (256 bits) if there is one since this is guaranteed not to
1380 * grow the signal frame when in streaming mode, otherwise the
1381 * minimum available VL will be used.
1383 set_sme_default_vl(find_supported_vector_length(ARM64_VEC_SME, 32));
1385 pr_info("SME: minimum available vector length %u bytes per vector\n",
1387 pr_info("SME: maximum available vector length %u bytes per vector\n",
1389 pr_info("SME: default vector length %u bytes per vector\n",
1390 get_sme_default_vl());
1393 #endif /* CONFIG_ARM64_SME */
1395 static void sve_init_regs(void)
1398 * Convert the FPSIMD state to SVE, zeroing all the state that
1399 * is not shared with FPSIMD. If (as is likely) the current
1400 * state is live in the registers then do this there and
1401 * update our metadata for the current task including
1402 * disabling the trap, otherwise update our in-memory copy.
1403 * We are guaranteed to not be in streaming mode, we can only
1404 * take a SVE trap when not in streaming mode and we can't be
1405 * in streaming mode when taking a SME trap.
1407 if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1408 unsigned long vq_minus_one =
1409 sve_vq_from_vl(task_get_sve_vl(current)) - 1;
1410 sve_set_vq(vq_minus_one);
1411 sve_flush_live(true, vq_minus_one);
1412 fpsimd_bind_task_to_cpu();
1414 fpsimd_to_sve(current);
1415 current->thread.fp_type = FP_STATE_SVE;
1420 * Trapped SVE access
1422 * Storage is allocated for the full SVE state, the current FPSIMD
1423 * register contents are migrated across, and the access trap is
1426 * TIF_SVE should be clear on entry: otherwise, fpsimd_restore_current_state()
1427 * would have disabled the SVE access trap for userspace during
1428 * ret_to_user, making an SVE access trap impossible in that case.
1430 void do_sve_acc(unsigned long esr, struct pt_regs *regs)
1432 /* Even if we chose not to use SVE, the hardware could still trap: */
1433 if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
1434 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1438 sve_alloc(current, true);
1439 if (!current->thread.sve_state) {
1444 get_cpu_fpsimd_context();
1446 if (test_and_set_thread_flag(TIF_SVE))
1447 WARN_ON(1); /* SVE access shouldn't have trapped */
1450 * Even if the task can have used streaming mode we can only
1451 * generate SVE access traps in normal SVE mode and
1452 * transitioning out of streaming mode may discard any
1453 * streaming mode state. Always clear the high bits to avoid
1454 * any potential errors tracking what is properly initialised.
1458 put_cpu_fpsimd_context();
1462 * Trapped SME access
1464 * Storage is allocated for the full SVE and SME state, the current
1465 * FPSIMD register contents are migrated to SVE if SVE is not already
1466 * active, and the access trap is disabled.
1468 * TIF_SME should be clear on entry: otherwise, fpsimd_restore_current_state()
1469 * would have disabled the SME access trap for userspace during
1470 * ret_to_user, making an SVE access trap impossible in that case.
1472 void do_sme_acc(unsigned long esr, struct pt_regs *regs)
1474 /* Even if we chose not to use SME, the hardware could still trap: */
1475 if (unlikely(!system_supports_sme()) || WARN_ON(is_compat_task())) {
1476 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1481 * If this not a trap due to SME being disabled then something
1482 * is being used in the wrong mode, report as SIGILL.
1484 if (ESR_ELx_ISS(esr) != ESR_ELx_SME_ISS_SME_DISABLED) {
1485 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1489 sve_alloc(current, false);
1491 if (!current->thread.sve_state || !current->thread.za_state) {
1496 get_cpu_fpsimd_context();
1498 /* With TIF_SME userspace shouldn't generate any traps */
1499 if (test_and_set_thread_flag(TIF_SME))
1502 if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1503 unsigned long vq_minus_one =
1504 sve_vq_from_vl(task_get_sme_vl(current)) - 1;
1505 sme_set_vq(vq_minus_one);
1507 fpsimd_bind_task_to_cpu();
1510 put_cpu_fpsimd_context();
1514 * Trapped FP/ASIMD access.
1516 void do_fpsimd_acc(unsigned long esr, struct pt_regs *regs)
1518 /* TODO: implement lazy context saving/restoring */
1523 * Raise a SIGFPE for the current process.
1525 void do_fpsimd_exc(unsigned long esr, struct pt_regs *regs)
1527 unsigned int si_code = FPE_FLTUNK;
1529 if (esr & ESR_ELx_FP_EXC_TFV) {
1530 if (esr & FPEXC_IOF)
1531 si_code = FPE_FLTINV;
1532 else if (esr & FPEXC_DZF)
1533 si_code = FPE_FLTDIV;
1534 else if (esr & FPEXC_OFF)
1535 si_code = FPE_FLTOVF;
1536 else if (esr & FPEXC_UFF)
1537 si_code = FPE_FLTUND;
1538 else if (esr & FPEXC_IXF)
1539 si_code = FPE_FLTRES;
1542 send_sig_fault(SIGFPE, si_code,
1543 (void __user *)instruction_pointer(regs),
1547 void fpsimd_thread_switch(struct task_struct *next)
1549 bool wrong_task, wrong_cpu;
1551 if (!system_supports_fpsimd())
1554 __get_cpu_fpsimd_context();
1556 /* Save unsaved fpsimd state, if any: */
1560 * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's
1561 * state. For kernel threads, FPSIMD registers are never loaded
1562 * and wrong_task and wrong_cpu will always be true.
1564 wrong_task = __this_cpu_read(fpsimd_last_state.st) !=
1565 &next->thread.uw.fpsimd_state;
1566 wrong_cpu = next->thread.fpsimd_cpu != smp_processor_id();
1568 update_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE,
1569 wrong_task || wrong_cpu);
1571 __put_cpu_fpsimd_context();
1574 static void fpsimd_flush_thread_vl(enum vec_type type)
1576 int vl, supported_vl;
1579 * Reset the task vector length as required. This is where we
1580 * ensure that all user tasks have a valid vector length
1581 * configured: no kernel task can become a user task without
1582 * an exec and hence a call to this function. By the time the
1583 * first call to this function is made, all early hardware
1584 * probing is complete, so __sve_default_vl should be valid.
1585 * If a bug causes this to go wrong, we make some noise and
1586 * try to fudge thread.sve_vl to a safe value here.
1588 vl = task_get_vl_onexec(current, type);
1590 vl = get_default_vl(type);
1592 if (WARN_ON(!sve_vl_valid(vl)))
1593 vl = vl_info[type].min_vl;
1595 supported_vl = find_supported_vector_length(type, vl);
1596 if (WARN_ON(supported_vl != vl))
1599 task_set_vl(current, type, vl);
1602 * If the task is not set to inherit, ensure that the vector
1603 * length will be reset by a subsequent exec:
1605 if (!test_thread_flag(vec_vl_inherit_flag(type)))
1606 task_set_vl_onexec(current, type, 0);
1609 void fpsimd_flush_thread(void)
1611 void *sve_state = NULL;
1612 void *za_state = NULL;
1614 if (!system_supports_fpsimd())
1617 get_cpu_fpsimd_context();
1619 fpsimd_flush_task_state(current);
1620 memset(¤t->thread.uw.fpsimd_state, 0,
1621 sizeof(current->thread.uw.fpsimd_state));
1623 if (system_supports_sve()) {
1624 clear_thread_flag(TIF_SVE);
1626 /* Defer kfree() while in atomic context */
1627 sve_state = current->thread.sve_state;
1628 current->thread.sve_state = NULL;
1630 fpsimd_flush_thread_vl(ARM64_VEC_SVE);
1633 if (system_supports_sme()) {
1634 clear_thread_flag(TIF_SME);
1636 /* Defer kfree() while in atomic context */
1637 za_state = current->thread.za_state;
1638 current->thread.za_state = NULL;
1640 fpsimd_flush_thread_vl(ARM64_VEC_SME);
1641 current->thread.svcr = 0;
1644 current->thread.fp_type = FP_STATE_FPSIMD;
1646 put_cpu_fpsimd_context();
1652 * Save the userland FPSIMD state of 'current' to memory, but only if the state
1653 * currently held in the registers does in fact belong to 'current'
1655 void fpsimd_preserve_current_state(void)
1657 if (!system_supports_fpsimd())
1660 get_cpu_fpsimd_context();
1662 put_cpu_fpsimd_context();
1666 * Like fpsimd_preserve_current_state(), but ensure that
1667 * current->thread.uw.fpsimd_state is updated so that it can be copied to
1670 void fpsimd_signal_preserve_current_state(void)
1672 fpsimd_preserve_current_state();
1673 if (test_thread_flag(TIF_SVE))
1674 sve_to_fpsimd(current);
1678 * Called by KVM when entering the guest.
1680 void fpsimd_kvm_prepare(void)
1682 if (!system_supports_sve())
1686 * KVM does not save host SVE state since we can only enter
1687 * the guest from a syscall so the ABI means that only the
1688 * non-saved SVE state needs to be saved. If we have left
1689 * SVE enabled for performance reasons then update the task
1690 * state to be FPSIMD only.
1692 get_cpu_fpsimd_context();
1694 if (test_and_clear_thread_flag(TIF_SVE)) {
1695 sve_to_fpsimd(current);
1696 current->thread.fp_type = FP_STATE_FPSIMD;
1699 put_cpu_fpsimd_context();
1703 * Associate current's FPSIMD context with this cpu
1704 * The caller must have ownership of the cpu FPSIMD context before calling
1707 static void fpsimd_bind_task_to_cpu(void)
1709 struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state);
1711 WARN_ON(!system_supports_fpsimd());
1712 last->st = ¤t->thread.uw.fpsimd_state;
1713 last->sve_state = current->thread.sve_state;
1714 last->za_state = current->thread.za_state;
1715 last->sve_vl = task_get_sve_vl(current);
1716 last->sme_vl = task_get_sme_vl(current);
1717 last->svcr = ¤t->thread.svcr;
1718 last->fp_type = ¤t->thread.fp_type;
1719 last->to_save = FP_STATE_CURRENT;
1720 current->thread.fpsimd_cpu = smp_processor_id();
1723 * Toggle SVE and SME trapping for userspace if needed, these
1724 * are serialsied by ret_to_user().
1726 if (system_supports_sme()) {
1727 if (test_thread_flag(TIF_SME))
1733 if (system_supports_sve()) {
1734 if (test_thread_flag(TIF_SVE))
1741 void fpsimd_bind_state_to_cpu(struct cpu_fp_state *state)
1743 struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state);
1745 WARN_ON(!system_supports_fpsimd());
1746 WARN_ON(!in_softirq() && !irqs_disabled());
1752 * Load the userland FPSIMD state of 'current' from memory, but only if the
1753 * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1754 * state of 'current'. This is called when we are preparing to return to
1755 * userspace to ensure that userspace sees a good register state.
1757 void fpsimd_restore_current_state(void)
1760 * For the tasks that were created before we detected the absence of
1761 * FP/SIMD, the TIF_FOREIGN_FPSTATE could be set via fpsimd_thread_switch(),
1762 * e.g, init. This could be then inherited by the children processes.
1763 * If we later detect that the system doesn't support FP/SIMD,
1764 * we must clear the flag for all the tasks to indicate that the
1765 * FPSTATE is clean (as we can't have one) to avoid looping for ever in
1766 * do_notify_resume().
1768 if (!system_supports_fpsimd()) {
1769 clear_thread_flag(TIF_FOREIGN_FPSTATE);
1773 get_cpu_fpsimd_context();
1775 if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1777 fpsimd_bind_task_to_cpu();
1780 put_cpu_fpsimd_context();
1784 * Load an updated userland FPSIMD state for 'current' from memory and set the
1785 * flag that indicates that the FPSIMD register contents are the most recent
1786 * FPSIMD state of 'current'. This is used by the signal code to restore the
1787 * register state when returning from a signal handler in FPSIMD only cases,
1788 * any SVE context will be discarded.
1790 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1792 if (WARN_ON(!system_supports_fpsimd()))
1795 get_cpu_fpsimd_context();
1797 current->thread.uw.fpsimd_state = *state;
1798 if (test_thread_flag(TIF_SVE))
1799 fpsimd_to_sve(current);
1802 fpsimd_bind_task_to_cpu();
1804 clear_thread_flag(TIF_FOREIGN_FPSTATE);
1806 put_cpu_fpsimd_context();
1810 * Invalidate live CPU copies of task t's FPSIMD state
1812 * This function may be called with preemption enabled. The barrier()
1813 * ensures that the assignment to fpsimd_cpu is visible to any
1814 * preemption/softirq that could race with set_tsk_thread_flag(), so
1815 * that TIF_FOREIGN_FPSTATE cannot be spuriously re-cleared.
1817 * The final barrier ensures that TIF_FOREIGN_FPSTATE is seen set by any
1820 void fpsimd_flush_task_state(struct task_struct *t)
1822 t->thread.fpsimd_cpu = NR_CPUS;
1824 * If we don't support fpsimd, bail out after we have
1825 * reset the fpsimd_cpu for this task and clear the
1828 if (!system_supports_fpsimd())
1831 set_tsk_thread_flag(t, TIF_FOREIGN_FPSTATE);
1837 * Invalidate any task's FPSIMD state that is present on this cpu.
1838 * The FPSIMD context should be acquired with get_cpu_fpsimd_context()
1839 * before calling this function.
1841 static void fpsimd_flush_cpu_state(void)
1843 WARN_ON(!system_supports_fpsimd());
1844 __this_cpu_write(fpsimd_last_state.st, NULL);
1847 * Leaving streaming mode enabled will cause issues for any kernel
1848 * NEON and leaving streaming mode or ZA enabled may increase power
1851 if (system_supports_sme())
1854 set_thread_flag(TIF_FOREIGN_FPSTATE);
1858 * Save the FPSIMD state to memory and invalidate cpu view.
1859 * This function must be called with preemption disabled.
1861 void fpsimd_save_and_flush_cpu_state(void)
1863 if (!system_supports_fpsimd())
1865 WARN_ON(preemptible());
1866 __get_cpu_fpsimd_context();
1868 fpsimd_flush_cpu_state();
1869 __put_cpu_fpsimd_context();
1872 #ifdef CONFIG_KERNEL_MODE_NEON
1875 * Kernel-side NEON support functions
1879 * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1882 * Must not be called unless may_use_simd() returns true.
1883 * Task context in the FPSIMD registers is saved back to memory as necessary.
1885 * A matching call to kernel_neon_end() must be made before returning from the
1888 * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1891 void kernel_neon_begin(void)
1893 if (WARN_ON(!system_supports_fpsimd()))
1896 BUG_ON(!may_use_simd());
1898 get_cpu_fpsimd_context();
1900 /* Save unsaved fpsimd state, if any: */
1903 /* Invalidate any task state remaining in the fpsimd regs: */
1904 fpsimd_flush_cpu_state();
1906 EXPORT_SYMBOL_GPL(kernel_neon_begin);
1909 * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1911 * Must be called from a context in which kernel_neon_begin() was previously
1912 * called, with no call to kernel_neon_end() in the meantime.
1914 * The caller must not use the FPSIMD registers after this function is called,
1915 * unless kernel_neon_begin() is called again in the meantime.
1917 void kernel_neon_end(void)
1919 if (!system_supports_fpsimd())
1922 put_cpu_fpsimd_context();
1924 EXPORT_SYMBOL_GPL(kernel_neon_end);
1928 static DEFINE_PER_CPU(struct user_fpsimd_state, efi_fpsimd_state);
1929 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1930 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1931 static DEFINE_PER_CPU(bool, efi_sm_state);
1934 * EFI runtime services support functions
1936 * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1937 * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1938 * is always used rather than being an optional accelerator.
1940 * These functions provide the necessary support for ensuring FPSIMD
1941 * save/restore in the contexts from which EFI is used.
1943 * Do not use them for any other purpose -- if tempted to do so, you are
1944 * either doing something wrong or you need to propose some refactoring.
1948 * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1950 void __efi_fpsimd_begin(void)
1952 if (!system_supports_fpsimd())
1955 WARN_ON(preemptible());
1957 if (may_use_simd()) {
1958 kernel_neon_begin();
1961 * If !efi_sve_state, SVE can't be in use yet and doesn't need
1964 if (system_supports_sve() && likely(efi_sve_state)) {
1965 char *sve_state = this_cpu_ptr(efi_sve_state);
1969 __this_cpu_write(efi_sve_state_used, true);
1971 if (system_supports_sme()) {
1972 svcr = read_sysreg_s(SYS_SVCR);
1974 __this_cpu_write(efi_sm_state,
1975 svcr & SVCR_SM_MASK);
1978 * Unless we have FA64 FFR does not
1979 * exist in streaming mode.
1981 if (!system_supports_fa64())
1982 ffr = !(svcr & SVCR_SM_MASK);
1985 sve_save_state(sve_state + sve_ffr_offset(sve_max_vl()),
1986 &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
1989 if (system_supports_sme())
1990 sysreg_clear_set_s(SYS_SVCR,
1994 fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
1997 __this_cpu_write(efi_fpsimd_state_used, true);
2002 * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
2004 void __efi_fpsimd_end(void)
2006 if (!system_supports_fpsimd())
2009 if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
2012 if (system_supports_sve() &&
2013 likely(__this_cpu_read(efi_sve_state_used))) {
2014 char const *sve_state = this_cpu_ptr(efi_sve_state);
2018 * Restore streaming mode; EFI calls are
2019 * normal function calls so should not return in
2022 if (system_supports_sme()) {
2023 if (__this_cpu_read(efi_sm_state)) {
2024 sysreg_clear_set_s(SYS_SVCR,
2029 * Unless we have FA64 FFR does not
2030 * exist in streaming mode.
2032 if (!system_supports_fa64())
2037 sve_load_state(sve_state + sve_ffr_offset(sve_max_vl()),
2038 &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
2041 __this_cpu_write(efi_sve_state_used, false);
2043 fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
2048 #endif /* CONFIG_EFI */
2050 #endif /* CONFIG_KERNEL_MODE_NEON */
2052 #ifdef CONFIG_CPU_PM
2053 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
2054 unsigned long cmd, void *v)
2058 fpsimd_save_and_flush_cpu_state();
2062 case CPU_PM_ENTER_FAILED:
2069 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
2070 .notifier_call = fpsimd_cpu_pm_notifier,
2073 static void __init fpsimd_pm_init(void)
2075 cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
2079 static inline void fpsimd_pm_init(void) { }
2080 #endif /* CONFIG_CPU_PM */
2082 #ifdef CONFIG_HOTPLUG_CPU
2083 static int fpsimd_cpu_dead(unsigned int cpu)
2085 per_cpu(fpsimd_last_state.st, cpu) = NULL;
2089 static inline void fpsimd_hotplug_init(void)
2091 cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
2092 NULL, fpsimd_cpu_dead);
2096 static inline void fpsimd_hotplug_init(void) { }
2100 * FP/SIMD support code initialisation.
2102 static int __init fpsimd_init(void)
2104 if (cpu_have_named_feature(FP)) {
2106 fpsimd_hotplug_init();
2108 pr_notice("Floating-point is not implemented\n");
2111 if (!cpu_have_named_feature(ASIMD))
2112 pr_notice("Advanced SIMD is not implemented\n");
2115 if (cpu_have_named_feature(SME) && !cpu_have_named_feature(SVE))
2116 pr_notice("SME is implemented but not SVE\n");
2123 core_initcall(fpsimd_init);