a66b8640a0a438a8f6c06a345d3da80044251ba3
[sfrench/cifs-2.6.git] / arch / arm64 / kernel / fpsimd.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * FP/SIMD context switching and fault handling
4  *
5  * Copyright (C) 2012 ARM Ltd.
6  * Author: Catalin Marinas <catalin.marinas@arm.com>
7  */
8
9 #include <linux/bitmap.h>
10 #include <linux/bitops.h>
11 #include <linux/bottom_half.h>
12 #include <linux/bug.h>
13 #include <linux/cache.h>
14 #include <linux/compat.h>
15 #include <linux/compiler.h>
16 #include <linux/cpu.h>
17 #include <linux/cpu_pm.h>
18 #include <linux/ctype.h>
19 #include <linux/kernel.h>
20 #include <linux/linkage.h>
21 #include <linux/irqflags.h>
22 #include <linux/init.h>
23 #include <linux/percpu.h>
24 #include <linux/prctl.h>
25 #include <linux/preempt.h>
26 #include <linux/ptrace.h>
27 #include <linux/sched/signal.h>
28 #include <linux/sched/task_stack.h>
29 #include <linux/signal.h>
30 #include <linux/slab.h>
31 #include <linux/stddef.h>
32 #include <linux/sysctl.h>
33 #include <linux/swab.h>
34
35 #include <asm/esr.h>
36 #include <asm/exception.h>
37 #include <asm/fpsimd.h>
38 #include <asm/cpufeature.h>
39 #include <asm/cputype.h>
40 #include <asm/neon.h>
41 #include <asm/processor.h>
42 #include <asm/simd.h>
43 #include <asm/sigcontext.h>
44 #include <asm/sysreg.h>
45 #include <asm/traps.h>
46 #include <asm/virt.h>
47
48 #define FPEXC_IOF       (1 << 0)
49 #define FPEXC_DZF       (1 << 1)
50 #define FPEXC_OFF       (1 << 2)
51 #define FPEXC_UFF       (1 << 3)
52 #define FPEXC_IXF       (1 << 4)
53 #define FPEXC_IDF       (1 << 7)
54
55 /*
56  * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
57  *
58  * In order to reduce the number of times the FPSIMD state is needlessly saved
59  * and restored, we need to keep track of two things:
60  * (a) for each task, we need to remember which CPU was the last one to have
61  *     the task's FPSIMD state loaded into its FPSIMD registers;
62  * (b) for each CPU, we need to remember which task's userland FPSIMD state has
63  *     been loaded into its FPSIMD registers most recently, or whether it has
64  *     been used to perform kernel mode NEON in the meantime.
65  *
66  * For (a), we add a fpsimd_cpu field to thread_struct, which gets updated to
67  * the id of the current CPU every time the state is loaded onto a CPU. For (b),
68  * we add the per-cpu variable 'fpsimd_last_state' (below), which contains the
69  * address of the userland FPSIMD state of the task that was loaded onto the CPU
70  * the most recently, or NULL if kernel mode NEON has been performed after that.
71  *
72  * With this in place, we no longer have to restore the next FPSIMD state right
73  * when switching between tasks. Instead, we can defer this check to userland
74  * resume, at which time we verify whether the CPU's fpsimd_last_state and the
75  * task's fpsimd_cpu are still mutually in sync. If this is the case, we
76  * can omit the FPSIMD restore.
77  *
78  * As an optimization, we use the thread_info flag TIF_FOREIGN_FPSTATE to
79  * indicate whether or not the userland FPSIMD state of the current task is
80  * present in the registers. The flag is set unless the FPSIMD registers of this
81  * CPU currently contain the most recent userland FPSIMD state of the current
82  * task. If the task is behaving as a VMM, then this is will be managed by
83  * KVM which will clear it to indicate that the vcpu FPSIMD state is currently
84  * loaded on the CPU, allowing the state to be saved if a FPSIMD-aware
85  * softirq kicks in. Upon vcpu_put(), KVM will save the vcpu FP state and
86  * flag the register state as invalid.
87  *
88  * In order to allow softirq handlers to use FPSIMD, kernel_neon_begin() may
89  * save the task's FPSIMD context back to task_struct from softirq context.
90  * To prevent this from racing with the manipulation of the task's FPSIMD state
91  * from task context and thereby corrupting the state, it is necessary to
92  * protect any manipulation of a task's fpsimd_state or TIF_FOREIGN_FPSTATE
93  * flag with {, __}get_cpu_fpsimd_context(). This will still allow softirqs to
94  * run but prevent them to use FPSIMD.
95  *
96  * For a certain task, the sequence may look something like this:
97  * - the task gets scheduled in; if both the task's fpsimd_cpu field
98  *   contains the id of the current CPU, and the CPU's fpsimd_last_state per-cpu
99  *   variable points to the task's fpsimd_state, the TIF_FOREIGN_FPSTATE flag is
100  *   cleared, otherwise it is set;
101  *
102  * - the task returns to userland; if TIF_FOREIGN_FPSTATE is set, the task's
103  *   userland FPSIMD state is copied from memory to the registers, the task's
104  *   fpsimd_cpu field is set to the id of the current CPU, the current
105  *   CPU's fpsimd_last_state pointer is set to this task's fpsimd_state and the
106  *   TIF_FOREIGN_FPSTATE flag is cleared;
107  *
108  * - the task executes an ordinary syscall; upon return to userland, the
109  *   TIF_FOREIGN_FPSTATE flag will still be cleared, so no FPSIMD state is
110  *   restored;
111  *
112  * - the task executes a syscall which executes some NEON instructions; this is
113  *   preceded by a call to kernel_neon_begin(), which copies the task's FPSIMD
114  *   register contents to memory, clears the fpsimd_last_state per-cpu variable
115  *   and sets the TIF_FOREIGN_FPSTATE flag;
116  *
117  * - the task gets preempted after kernel_neon_end() is called; as we have not
118  *   returned from the 2nd syscall yet, TIF_FOREIGN_FPSTATE is still set so
119  *   whatever is in the FPSIMD registers is not saved to memory, but discarded.
120  */
121 struct fpsimd_last_state_struct {
122         struct user_fpsimd_state *st;
123         void *sve_state;
124         void *za_state;
125         u64 *svcr;
126         unsigned int sve_vl;
127         unsigned int sme_vl;
128         enum fp_type *fp_type;
129         enum fp_type to_save;
130 };
131
132 static DEFINE_PER_CPU(struct fpsimd_last_state_struct, fpsimd_last_state);
133
134 __ro_after_init struct vl_info vl_info[ARM64_VEC_MAX] = {
135 #ifdef CONFIG_ARM64_SVE
136         [ARM64_VEC_SVE] = {
137                 .type                   = ARM64_VEC_SVE,
138                 .name                   = "SVE",
139                 .min_vl                 = SVE_VL_MIN,
140                 .max_vl                 = SVE_VL_MIN,
141                 .max_virtualisable_vl   = SVE_VL_MIN,
142         },
143 #endif
144 #ifdef CONFIG_ARM64_SME
145         [ARM64_VEC_SME] = {
146                 .type                   = ARM64_VEC_SME,
147                 .name                   = "SME",
148         },
149 #endif
150 };
151
152 static unsigned int vec_vl_inherit_flag(enum vec_type type)
153 {
154         switch (type) {
155         case ARM64_VEC_SVE:
156                 return TIF_SVE_VL_INHERIT;
157         case ARM64_VEC_SME:
158                 return TIF_SME_VL_INHERIT;
159         default:
160                 WARN_ON_ONCE(1);
161                 return 0;
162         }
163 }
164
165 struct vl_config {
166         int __default_vl;               /* Default VL for tasks */
167 };
168
169 static struct vl_config vl_config[ARM64_VEC_MAX];
170
171 static inline int get_default_vl(enum vec_type type)
172 {
173         return READ_ONCE(vl_config[type].__default_vl);
174 }
175
176 #ifdef CONFIG_ARM64_SVE
177
178 static inline int get_sve_default_vl(void)
179 {
180         return get_default_vl(ARM64_VEC_SVE);
181 }
182
183 static inline void set_default_vl(enum vec_type type, int val)
184 {
185         WRITE_ONCE(vl_config[type].__default_vl, val);
186 }
187
188 static inline void set_sve_default_vl(int val)
189 {
190         set_default_vl(ARM64_VEC_SVE, val);
191 }
192
193 static void __percpu *efi_sve_state;
194
195 #else /* ! CONFIG_ARM64_SVE */
196
197 /* Dummy declaration for code that will be optimised out: */
198 extern void __percpu *efi_sve_state;
199
200 #endif /* ! CONFIG_ARM64_SVE */
201
202 #ifdef CONFIG_ARM64_SME
203
204 static int get_sme_default_vl(void)
205 {
206         return get_default_vl(ARM64_VEC_SME);
207 }
208
209 static void set_sme_default_vl(int val)
210 {
211         set_default_vl(ARM64_VEC_SME, val);
212 }
213
214 static void sme_free(struct task_struct *);
215
216 #else
217
218 static inline void sme_free(struct task_struct *t) { }
219
220 #endif
221
222 DEFINE_PER_CPU(bool, fpsimd_context_busy);
223 EXPORT_PER_CPU_SYMBOL(fpsimd_context_busy);
224
225 static void fpsimd_bind_task_to_cpu(void);
226
227 static void __get_cpu_fpsimd_context(void)
228 {
229         bool busy = __this_cpu_xchg(fpsimd_context_busy, true);
230
231         WARN_ON(busy);
232 }
233
234 /*
235  * Claim ownership of the CPU FPSIMD context for use by the calling context.
236  *
237  * The caller may freely manipulate the FPSIMD context metadata until
238  * put_cpu_fpsimd_context() is called.
239  *
240  * The double-underscore version must only be called if you know the task
241  * can't be preempted.
242  *
243  * On RT kernels local_bh_disable() is not sufficient because it only
244  * serializes soft interrupt related sections via a local lock, but stays
245  * preemptible. Disabling preemption is the right choice here as bottom
246  * half processing is always in thread context on RT kernels so it
247  * implicitly prevents bottom half processing as well.
248  */
249 static void get_cpu_fpsimd_context(void)
250 {
251         if (!IS_ENABLED(CONFIG_PREEMPT_RT))
252                 local_bh_disable();
253         else
254                 preempt_disable();
255         __get_cpu_fpsimd_context();
256 }
257
258 static void __put_cpu_fpsimd_context(void)
259 {
260         bool busy = __this_cpu_xchg(fpsimd_context_busy, false);
261
262         WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */
263 }
264
265 /*
266  * Release the CPU FPSIMD context.
267  *
268  * Must be called from a context in which get_cpu_fpsimd_context() was
269  * previously called, with no call to put_cpu_fpsimd_context() in the
270  * meantime.
271  */
272 static void put_cpu_fpsimd_context(void)
273 {
274         __put_cpu_fpsimd_context();
275         if (!IS_ENABLED(CONFIG_PREEMPT_RT))
276                 local_bh_enable();
277         else
278                 preempt_enable();
279 }
280
281 static bool have_cpu_fpsimd_context(void)
282 {
283         return !preemptible() && __this_cpu_read(fpsimd_context_busy);
284 }
285
286 unsigned int task_get_vl(const struct task_struct *task, enum vec_type type)
287 {
288         return task->thread.vl[type];
289 }
290
291 void task_set_vl(struct task_struct *task, enum vec_type type,
292                  unsigned long vl)
293 {
294         task->thread.vl[type] = vl;
295 }
296
297 unsigned int task_get_vl_onexec(const struct task_struct *task,
298                                 enum vec_type type)
299 {
300         return task->thread.vl_onexec[type];
301 }
302
303 void task_set_vl_onexec(struct task_struct *task, enum vec_type type,
304                         unsigned long vl)
305 {
306         task->thread.vl_onexec[type] = vl;
307 }
308
309 /*
310  * TIF_SME controls whether a task can use SME without trapping while
311  * in userspace, when TIF_SME is set then we must have storage
312  * alocated in sve_state and za_state to store the contents of both ZA
313  * and the SVE registers for both streaming and non-streaming modes.
314  *
315  * If both SVCR.ZA and SVCR.SM are disabled then at any point we
316  * may disable TIF_SME and reenable traps.
317  */
318
319
320 /*
321  * TIF_SVE controls whether a task can use SVE without trapping while
322  * in userspace, and also (together with TIF_SME) the way a task's
323  * FPSIMD/SVE state is stored in thread_struct.
324  *
325  * The kernel uses this flag to track whether a user task is actively
326  * using SVE, and therefore whether full SVE register state needs to
327  * be tracked.  If not, the cheaper FPSIMD context handling code can
328  * be used instead of the more costly SVE equivalents.
329  *
330  *  * TIF_SVE or SVCR.SM set:
331  *
332  *    The task can execute SVE instructions while in userspace without
333  *    trapping to the kernel.
334  *
335  *    During any syscall, the kernel may optionally clear TIF_SVE and
336  *    discard the vector state except for the FPSIMD subset.
337  *
338  *  * TIF_SVE clear:
339  *
340  *    An attempt by the user task to execute an SVE instruction causes
341  *    do_sve_acc() to be called, which does some preparation and then
342  *    sets TIF_SVE.
343  *
344  * During any syscall, the kernel may optionally clear TIF_SVE and
345  * discard the vector state except for the FPSIMD subset.
346  *
347  * The data will be stored in one of two formats:
348  *
349  *  * FPSIMD only - FP_STATE_FPSIMD:
350  *
351  *    When the FPSIMD only state stored task->thread.fp_type is set to
352  *    FP_STATE_FPSIMD, the FPSIMD registers V0-V31 are encoded in
353  *    task->thread.uw.fpsimd_state; bits [max : 128] for each of Z0-Z31 are
354  *    logically zero but not stored anywhere; P0-P15 and FFR are not
355  *    stored and have unspecified values from userspace's point of
356  *    view.  For hygiene purposes, the kernel zeroes them on next use,
357  *    but userspace is discouraged from relying on this.
358  *
359  *    task->thread.sve_state does not need to be non-NULL, valid or any
360  *    particular size: it must not be dereferenced and any data stored
361  *    there should be considered stale and not referenced.
362  *
363  *  * SVE state - FP_STATE_SVE:
364  *
365  *    When the full SVE state is stored task->thread.fp_type is set to
366  *    FP_STATE_SVE and Z0-Z31 (incorporating Vn in bits[127:0] or the
367  *    corresponding Zn), P0-P15 and FFR are encoded in in
368  *    task->thread.sve_state, formatted appropriately for vector
369  *    length task->thread.sve_vl or, if SVCR.SM is set,
370  *    task->thread.sme_vl. The storage for the vector registers in
371  *    task->thread.uw.fpsimd_state should be ignored.
372  *
373  *    task->thread.sve_state must point to a valid buffer at least
374  *    sve_state_size(task) bytes in size. The data stored in
375  *    task->thread.uw.fpsimd_state.vregs should be considered stale
376  *    and not referenced.
377  *
378  *  * FPSR and FPCR are always stored in task->thread.uw.fpsimd_state
379  *    irrespective of whether TIF_SVE is clear or set, since these are
380  *    not vector length dependent.
381  */
382
383 /*
384  * Update current's FPSIMD/SVE registers from thread_struct.
385  *
386  * This function should be called only when the FPSIMD/SVE state in
387  * thread_struct is known to be up to date, when preparing to enter
388  * userspace.
389  */
390 static void task_fpsimd_load(void)
391 {
392         bool restore_sve_regs = false;
393         bool restore_ffr;
394
395         WARN_ON(!system_supports_fpsimd());
396         WARN_ON(!have_cpu_fpsimd_context());
397
398         if (system_supports_sve()) {
399                 switch (current->thread.fp_type) {
400                 case FP_STATE_FPSIMD:
401                         /* Stop tracking SVE for this task until next use. */
402                         if (test_and_clear_thread_flag(TIF_SVE))
403                                 sve_user_disable();
404                         break;
405                 case FP_STATE_SVE:
406                         if (!thread_sm_enabled(&current->thread) &&
407                             !WARN_ON_ONCE(!test_and_set_thread_flag(TIF_SVE)))
408                                 sve_user_enable();
409
410                         if (test_thread_flag(TIF_SVE))
411                                 sve_set_vq(sve_vq_from_vl(task_get_sve_vl(current)) - 1);
412
413                         restore_sve_regs = true;
414                         restore_ffr = true;
415                         break;
416                 default:
417                         /*
418                          * This indicates either a bug in
419                          * fpsimd_save() or memory corruption, we
420                          * should always record an explicit format
421                          * when we save. We always at least have the
422                          * memory allocated for FPSMID registers so
423                          * try that and hope for the best.
424                          */
425                         WARN_ON_ONCE(1);
426                         clear_thread_flag(TIF_SVE);
427                         break;
428                 }
429         }
430
431         /* Restore SME, override SVE register configuration if needed */
432         if (system_supports_sme()) {
433                 unsigned long sme_vl = task_get_sme_vl(current);
434
435                 /* Ensure VL is set up for restoring data */
436                 if (test_thread_flag(TIF_SME))
437                         sme_set_vq(sve_vq_from_vl(sme_vl) - 1);
438
439                 write_sysreg_s(current->thread.svcr, SYS_SVCR);
440
441                 if (thread_za_enabled(&current->thread))
442                         za_load_state(current->thread.za_state);
443
444                 if (thread_sm_enabled(&current->thread))
445                         restore_ffr = system_supports_fa64();
446         }
447
448         if (restore_sve_regs) {
449                 WARN_ON_ONCE(current->thread.fp_type != FP_STATE_SVE);
450                 sve_load_state(sve_pffr(&current->thread),
451                                &current->thread.uw.fpsimd_state.fpsr,
452                                restore_ffr);
453         } else {
454                 WARN_ON_ONCE(current->thread.fp_type != FP_STATE_FPSIMD);
455                 fpsimd_load_state(&current->thread.uw.fpsimd_state);
456         }
457 }
458
459 /*
460  * Ensure FPSIMD/SVE storage in memory for the loaded context is up to
461  * date with respect to the CPU registers. Note carefully that the
462  * current context is the context last bound to the CPU stored in
463  * last, if KVM is involved this may be the guest VM context rather
464  * than the host thread for the VM pointed to by current. This means
465  * that we must always reference the state storage via last rather
466  * than via current, if we are saving KVM state then it will have
467  * ensured that the type of registers to save is set in last->to_save.
468  */
469 static void fpsimd_save(void)
470 {
471         struct fpsimd_last_state_struct const *last =
472                 this_cpu_ptr(&fpsimd_last_state);
473         /* set by fpsimd_bind_task_to_cpu() or fpsimd_bind_state_to_cpu() */
474         bool save_sve_regs = false;
475         bool save_ffr;
476         unsigned int vl;
477
478         WARN_ON(!system_supports_fpsimd());
479         WARN_ON(!have_cpu_fpsimd_context());
480
481         if (test_thread_flag(TIF_FOREIGN_FPSTATE))
482                 return;
483
484         /*
485          * If a task is in a syscall the ABI allows us to only
486          * preserve the state shared with FPSIMD so don't bother
487          * saving the full SVE state in that case.
488          */
489         if ((last->to_save == FP_STATE_CURRENT && test_thread_flag(TIF_SVE) &&
490              !in_syscall(current_pt_regs())) ||
491             last->to_save == FP_STATE_SVE) {
492                 save_sve_regs = true;
493                 save_ffr = true;
494                 vl = last->sve_vl;
495         }
496
497         if (system_supports_sme()) {
498                 u64 *svcr = last->svcr;
499
500                 *svcr = read_sysreg_s(SYS_SVCR);
501
502                 if (*svcr & SVCR_ZA_MASK)
503                         za_save_state(last->za_state);
504
505                 /* If we are in streaming mode override regular SVE. */
506                 if (*svcr & SVCR_SM_MASK) {
507                         save_sve_regs = true;
508                         save_ffr = system_supports_fa64();
509                         vl = last->sme_vl;
510                 }
511         }
512
513         if (IS_ENABLED(CONFIG_ARM64_SVE) && save_sve_regs) {
514                 /* Get the configured VL from RDVL, will account for SM */
515                 if (WARN_ON(sve_get_vl() != vl)) {
516                         /*
517                          * Can't save the user regs, so current would
518                          * re-enter user with corrupt state.
519                          * There's no way to recover, so kill it:
520                          */
521                         force_signal_inject(SIGKILL, SI_KERNEL, 0, 0);
522                         return;
523                 }
524
525                 sve_save_state((char *)last->sve_state +
526                                         sve_ffr_offset(vl),
527                                &last->st->fpsr, save_ffr);
528                 *last->fp_type = FP_STATE_SVE;
529         } else {
530                 fpsimd_save_state(last->st);
531                 *last->fp_type = FP_STATE_FPSIMD;
532         }
533 }
534
535 /*
536  * All vector length selection from userspace comes through here.
537  * We're on a slow path, so some sanity-checks are included.
538  * If things go wrong there's a bug somewhere, but try to fall back to a
539  * safe choice.
540  */
541 static unsigned int find_supported_vector_length(enum vec_type type,
542                                                  unsigned int vl)
543 {
544         struct vl_info *info = &vl_info[type];
545         int bit;
546         int max_vl = info->max_vl;
547
548         if (WARN_ON(!sve_vl_valid(vl)))
549                 vl = info->min_vl;
550
551         if (WARN_ON(!sve_vl_valid(max_vl)))
552                 max_vl = info->min_vl;
553
554         if (vl > max_vl)
555                 vl = max_vl;
556         if (vl < info->min_vl)
557                 vl = info->min_vl;
558
559         bit = find_next_bit(info->vq_map, SVE_VQ_MAX,
560                             __vq_to_bit(sve_vq_from_vl(vl)));
561         return sve_vl_from_vq(__bit_to_vq(bit));
562 }
563
564 #if defined(CONFIG_ARM64_SVE) && defined(CONFIG_SYSCTL)
565
566 static int vec_proc_do_default_vl(struct ctl_table *table, int write,
567                                   void *buffer, size_t *lenp, loff_t *ppos)
568 {
569         struct vl_info *info = table->extra1;
570         enum vec_type type = info->type;
571         int ret;
572         int vl = get_default_vl(type);
573         struct ctl_table tmp_table = {
574                 .data = &vl,
575                 .maxlen = sizeof(vl),
576         };
577
578         ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
579         if (ret || !write)
580                 return ret;
581
582         /* Writing -1 has the special meaning "set to max": */
583         if (vl == -1)
584                 vl = info->max_vl;
585
586         if (!sve_vl_valid(vl))
587                 return -EINVAL;
588
589         set_default_vl(type, find_supported_vector_length(type, vl));
590         return 0;
591 }
592
593 static struct ctl_table sve_default_vl_table[] = {
594         {
595                 .procname       = "sve_default_vector_length",
596                 .mode           = 0644,
597                 .proc_handler   = vec_proc_do_default_vl,
598                 .extra1         = &vl_info[ARM64_VEC_SVE],
599         },
600         { }
601 };
602
603 static int __init sve_sysctl_init(void)
604 {
605         if (system_supports_sve())
606                 if (!register_sysctl("abi", sve_default_vl_table))
607                         return -EINVAL;
608
609         return 0;
610 }
611
612 #else /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
613 static int __init sve_sysctl_init(void) { return 0; }
614 #endif /* ! (CONFIG_ARM64_SVE && CONFIG_SYSCTL) */
615
616 #if defined(CONFIG_ARM64_SME) && defined(CONFIG_SYSCTL)
617 static struct ctl_table sme_default_vl_table[] = {
618         {
619                 .procname       = "sme_default_vector_length",
620                 .mode           = 0644,
621                 .proc_handler   = vec_proc_do_default_vl,
622                 .extra1         = &vl_info[ARM64_VEC_SME],
623         },
624         { }
625 };
626
627 static int __init sme_sysctl_init(void)
628 {
629         if (system_supports_sme())
630                 if (!register_sysctl("abi", sme_default_vl_table))
631                         return -EINVAL;
632
633         return 0;
634 }
635
636 #else /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
637 static int __init sme_sysctl_init(void) { return 0; }
638 #endif /* ! (CONFIG_ARM64_SME && CONFIG_SYSCTL) */
639
640 #define ZREG(sve_state, vq, n) ((char *)(sve_state) +           \
641         (SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
642
643 #ifdef CONFIG_CPU_BIG_ENDIAN
644 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
645 {
646         u64 a = swab64(x);
647         u64 b = swab64(x >> 64);
648
649         return ((__uint128_t)a << 64) | b;
650 }
651 #else
652 static __uint128_t arm64_cpu_to_le128(__uint128_t x)
653 {
654         return x;
655 }
656 #endif
657
658 #define arm64_le128_to_cpu(x) arm64_cpu_to_le128(x)
659
660 static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst,
661                             unsigned int vq)
662 {
663         unsigned int i;
664         __uint128_t *p;
665
666         for (i = 0; i < SVE_NUM_ZREGS; ++i) {
667                 p = (__uint128_t *)ZREG(sst, vq, i);
668                 *p = arm64_cpu_to_le128(fst->vregs[i]);
669         }
670 }
671
672 /*
673  * Transfer the FPSIMD state in task->thread.uw.fpsimd_state to
674  * task->thread.sve_state.
675  *
676  * Task can be a non-runnable task, or current.  In the latter case,
677  * the caller must have ownership of the cpu FPSIMD context before calling
678  * this function.
679  * task->thread.sve_state must point to at least sve_state_size(task)
680  * bytes of allocated kernel memory.
681  * task->thread.uw.fpsimd_state must be up to date before calling this
682  * function.
683  */
684 static void fpsimd_to_sve(struct task_struct *task)
685 {
686         unsigned int vq;
687         void *sst = task->thread.sve_state;
688         struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
689
690         if (!system_supports_sve())
691                 return;
692
693         vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
694         __fpsimd_to_sve(sst, fst, vq);
695 }
696
697 /*
698  * Transfer the SVE state in task->thread.sve_state to
699  * task->thread.uw.fpsimd_state.
700  *
701  * Task can be a non-runnable task, or current.  In the latter case,
702  * the caller must have ownership of the cpu FPSIMD context before calling
703  * this function.
704  * task->thread.sve_state must point to at least sve_state_size(task)
705  * bytes of allocated kernel memory.
706  * task->thread.sve_state must be up to date before calling this function.
707  */
708 static void sve_to_fpsimd(struct task_struct *task)
709 {
710         unsigned int vq, vl;
711         void const *sst = task->thread.sve_state;
712         struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state;
713         unsigned int i;
714         __uint128_t const *p;
715
716         if (!system_supports_sve())
717                 return;
718
719         vl = thread_get_cur_vl(&task->thread);
720         vq = sve_vq_from_vl(vl);
721         for (i = 0; i < SVE_NUM_ZREGS; ++i) {
722                 p = (__uint128_t const *)ZREG(sst, vq, i);
723                 fst->vregs[i] = arm64_le128_to_cpu(*p);
724         }
725 }
726
727 #ifdef CONFIG_ARM64_SVE
728 /*
729  * Call __sve_free() directly only if you know task can't be scheduled
730  * or preempted.
731  */
732 static void __sve_free(struct task_struct *task)
733 {
734         kfree(task->thread.sve_state);
735         task->thread.sve_state = NULL;
736 }
737
738 static void sve_free(struct task_struct *task)
739 {
740         WARN_ON(test_tsk_thread_flag(task, TIF_SVE));
741
742         __sve_free(task);
743 }
744
745 /*
746  * Return how many bytes of memory are required to store the full SVE
747  * state for task, given task's currently configured vector length.
748  */
749 size_t sve_state_size(struct task_struct const *task)
750 {
751         unsigned int vl = 0;
752
753         if (system_supports_sve())
754                 vl = task_get_sve_vl(task);
755         if (system_supports_sme())
756                 vl = max(vl, task_get_sme_vl(task));
757
758         return SVE_SIG_REGS_SIZE(sve_vq_from_vl(vl));
759 }
760
761 /*
762  * Ensure that task->thread.sve_state is allocated and sufficiently large.
763  *
764  * This function should be used only in preparation for replacing
765  * task->thread.sve_state with new data.  The memory is always zeroed
766  * here to prevent stale data from showing through: this is done in
767  * the interest of testability and predictability: except in the
768  * do_sve_acc() case, there is no ABI requirement to hide stale data
769  * written previously be task.
770  */
771 void sve_alloc(struct task_struct *task, bool flush)
772 {
773         if (task->thread.sve_state) {
774                 if (flush)
775                         memset(task->thread.sve_state, 0,
776                                sve_state_size(task));
777                 return;
778         }
779
780         /* This is a small allocation (maximum ~8KB) and Should Not Fail. */
781         task->thread.sve_state =
782                 kzalloc(sve_state_size(task), GFP_KERNEL);
783 }
784
785
786 /*
787  * Force the FPSIMD state shared with SVE to be updated in the SVE state
788  * even if the SVE state is the current active state.
789  *
790  * This should only be called by ptrace.  task must be non-runnable.
791  * task->thread.sve_state must point to at least sve_state_size(task)
792  * bytes of allocated kernel memory.
793  */
794 void fpsimd_force_sync_to_sve(struct task_struct *task)
795 {
796         fpsimd_to_sve(task);
797 }
798
799 /*
800  * Ensure that task->thread.sve_state is up to date with respect to
801  * the user task, irrespective of when SVE is in use or not.
802  *
803  * This should only be called by ptrace.  task must be non-runnable.
804  * task->thread.sve_state must point to at least sve_state_size(task)
805  * bytes of allocated kernel memory.
806  */
807 void fpsimd_sync_to_sve(struct task_struct *task)
808 {
809         if (!test_tsk_thread_flag(task, TIF_SVE) &&
810             !thread_sm_enabled(&task->thread))
811                 fpsimd_to_sve(task);
812 }
813
814 /*
815  * Ensure that task->thread.uw.fpsimd_state is up to date with respect to
816  * the user task, irrespective of whether SVE is in use or not.
817  *
818  * This should only be called by ptrace.  task must be non-runnable.
819  * task->thread.sve_state must point to at least sve_state_size(task)
820  * bytes of allocated kernel memory.
821  */
822 void sve_sync_to_fpsimd(struct task_struct *task)
823 {
824         if (task->thread.fp_type == FP_STATE_SVE)
825                 sve_to_fpsimd(task);
826 }
827
828 /*
829  * Ensure that task->thread.sve_state is up to date with respect to
830  * the task->thread.uw.fpsimd_state.
831  *
832  * This should only be called by ptrace to merge new FPSIMD register
833  * values into a task for which SVE is currently active.
834  * task must be non-runnable.
835  * task->thread.sve_state must point to at least sve_state_size(task)
836  * bytes of allocated kernel memory.
837  * task->thread.uw.fpsimd_state must already have been initialised with
838  * the new FPSIMD register values to be merged in.
839  */
840 void sve_sync_from_fpsimd_zeropad(struct task_struct *task)
841 {
842         unsigned int vq;
843         void *sst = task->thread.sve_state;
844         struct user_fpsimd_state const *fst = &task->thread.uw.fpsimd_state;
845
846         if (!test_tsk_thread_flag(task, TIF_SVE))
847                 return;
848
849         vq = sve_vq_from_vl(thread_get_cur_vl(&task->thread));
850
851         memset(sst, 0, SVE_SIG_REGS_SIZE(vq));
852         __fpsimd_to_sve(sst, fst, vq);
853 }
854
855 int vec_set_vector_length(struct task_struct *task, enum vec_type type,
856                           unsigned long vl, unsigned long flags)
857 {
858         if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT |
859                                      PR_SVE_SET_VL_ONEXEC))
860                 return -EINVAL;
861
862         if (!sve_vl_valid(vl))
863                 return -EINVAL;
864
865         /*
866          * Clamp to the maximum vector length that VL-agnostic code
867          * can work with.  A flag may be assigned in the future to
868          * allow setting of larger vector lengths without confusing
869          * older software.
870          */
871         if (vl > VL_ARCH_MAX)
872                 vl = VL_ARCH_MAX;
873
874         vl = find_supported_vector_length(type, vl);
875
876         if (flags & (PR_SVE_VL_INHERIT |
877                      PR_SVE_SET_VL_ONEXEC))
878                 task_set_vl_onexec(task, type, vl);
879         else
880                 /* Reset VL to system default on next exec: */
881                 task_set_vl_onexec(task, type, 0);
882
883         /* Only actually set the VL if not deferred: */
884         if (flags & PR_SVE_SET_VL_ONEXEC)
885                 goto out;
886
887         if (vl == task_get_vl(task, type))
888                 goto out;
889
890         /*
891          * To ensure the FPSIMD bits of the SVE vector registers are preserved,
892          * write any live register state back to task_struct, and convert to a
893          * regular FPSIMD thread.
894          */
895         if (task == current) {
896                 get_cpu_fpsimd_context();
897
898                 fpsimd_save();
899         }
900
901         fpsimd_flush_task_state(task);
902         if (test_and_clear_tsk_thread_flag(task, TIF_SVE) ||
903             thread_sm_enabled(&task->thread)) {
904                 sve_to_fpsimd(task);
905                 task->thread.fp_type = FP_STATE_FPSIMD;
906         }
907
908         if (system_supports_sme() && type == ARM64_VEC_SME) {
909                 task->thread.svcr &= ~(SVCR_SM_MASK |
910                                        SVCR_ZA_MASK);
911                 clear_thread_flag(TIF_SME);
912         }
913
914         if (task == current)
915                 put_cpu_fpsimd_context();
916
917         /*
918          * Force reallocation of task SVE and SME state to the correct
919          * size on next use:
920          */
921         sve_free(task);
922         if (system_supports_sme() && type == ARM64_VEC_SME)
923                 sme_free(task);
924
925         task_set_vl(task, type, vl);
926
927 out:
928         update_tsk_thread_flag(task, vec_vl_inherit_flag(type),
929                                flags & PR_SVE_VL_INHERIT);
930
931         return 0;
932 }
933
934 /*
935  * Encode the current vector length and flags for return.
936  * This is only required for prctl(): ptrace has separate fields.
937  * SVE and SME use the same bits for _ONEXEC and _INHERIT.
938  *
939  * flags are as for vec_set_vector_length().
940  */
941 static int vec_prctl_status(enum vec_type type, unsigned long flags)
942 {
943         int ret;
944
945         if (flags & PR_SVE_SET_VL_ONEXEC)
946                 ret = task_get_vl_onexec(current, type);
947         else
948                 ret = task_get_vl(current, type);
949
950         if (test_thread_flag(vec_vl_inherit_flag(type)))
951                 ret |= PR_SVE_VL_INHERIT;
952
953         return ret;
954 }
955
956 /* PR_SVE_SET_VL */
957 int sve_set_current_vl(unsigned long arg)
958 {
959         unsigned long vl, flags;
960         int ret;
961
962         vl = arg & PR_SVE_VL_LEN_MASK;
963         flags = arg & ~vl;
964
965         if (!system_supports_sve() || is_compat_task())
966                 return -EINVAL;
967
968         ret = vec_set_vector_length(current, ARM64_VEC_SVE, vl, flags);
969         if (ret)
970                 return ret;
971
972         return vec_prctl_status(ARM64_VEC_SVE, flags);
973 }
974
975 /* PR_SVE_GET_VL */
976 int sve_get_current_vl(void)
977 {
978         if (!system_supports_sve() || is_compat_task())
979                 return -EINVAL;
980
981         return vec_prctl_status(ARM64_VEC_SVE, 0);
982 }
983
984 #ifdef CONFIG_ARM64_SME
985 /* PR_SME_SET_VL */
986 int sme_set_current_vl(unsigned long arg)
987 {
988         unsigned long vl, flags;
989         int ret;
990
991         vl = arg & PR_SME_VL_LEN_MASK;
992         flags = arg & ~vl;
993
994         if (!system_supports_sme() || is_compat_task())
995                 return -EINVAL;
996
997         ret = vec_set_vector_length(current, ARM64_VEC_SME, vl, flags);
998         if (ret)
999                 return ret;
1000
1001         return vec_prctl_status(ARM64_VEC_SME, flags);
1002 }
1003
1004 /* PR_SME_GET_VL */
1005 int sme_get_current_vl(void)
1006 {
1007         if (!system_supports_sme() || is_compat_task())
1008                 return -EINVAL;
1009
1010         return vec_prctl_status(ARM64_VEC_SME, 0);
1011 }
1012 #endif /* CONFIG_ARM64_SME */
1013
1014 static void vec_probe_vqs(struct vl_info *info,
1015                           DECLARE_BITMAP(map, SVE_VQ_MAX))
1016 {
1017         unsigned int vq, vl;
1018
1019         bitmap_zero(map, SVE_VQ_MAX);
1020
1021         for (vq = SVE_VQ_MAX; vq >= SVE_VQ_MIN; --vq) {
1022                 write_vl(info->type, vq - 1); /* self-syncing */
1023
1024                 switch (info->type) {
1025                 case ARM64_VEC_SVE:
1026                         vl = sve_get_vl();
1027                         break;
1028                 case ARM64_VEC_SME:
1029                         vl = sme_get_vl();
1030                         break;
1031                 default:
1032                         vl = 0;
1033                         break;
1034                 }
1035
1036                 /* Minimum VL identified? */
1037                 if (sve_vq_from_vl(vl) > vq)
1038                         break;
1039
1040                 vq = sve_vq_from_vl(vl); /* skip intervening lengths */
1041                 set_bit(__vq_to_bit(vq), map);
1042         }
1043 }
1044
1045 /*
1046  * Initialise the set of known supported VQs for the boot CPU.
1047  * This is called during kernel boot, before secondary CPUs are brought up.
1048  */
1049 void __init vec_init_vq_map(enum vec_type type)
1050 {
1051         struct vl_info *info = &vl_info[type];
1052         vec_probe_vqs(info, info->vq_map);
1053         bitmap_copy(info->vq_partial_map, info->vq_map, SVE_VQ_MAX);
1054 }
1055
1056 /*
1057  * If we haven't committed to the set of supported VQs yet, filter out
1058  * those not supported by the current CPU.
1059  * This function is called during the bring-up of early secondary CPUs only.
1060  */
1061 void vec_update_vq_map(enum vec_type type)
1062 {
1063         struct vl_info *info = &vl_info[type];
1064         DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1065
1066         vec_probe_vqs(info, tmp_map);
1067         bitmap_and(info->vq_map, info->vq_map, tmp_map, SVE_VQ_MAX);
1068         bitmap_or(info->vq_partial_map, info->vq_partial_map, tmp_map,
1069                   SVE_VQ_MAX);
1070 }
1071
1072 /*
1073  * Check whether the current CPU supports all VQs in the committed set.
1074  * This function is called during the bring-up of late secondary CPUs only.
1075  */
1076 int vec_verify_vq_map(enum vec_type type)
1077 {
1078         struct vl_info *info = &vl_info[type];
1079         DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1080         unsigned long b;
1081
1082         vec_probe_vqs(info, tmp_map);
1083
1084         bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1085         if (bitmap_intersects(tmp_map, info->vq_map, SVE_VQ_MAX)) {
1086                 pr_warn("%s: cpu%d: Required vector length(s) missing\n",
1087                         info->name, smp_processor_id());
1088                 return -EINVAL;
1089         }
1090
1091         if (!IS_ENABLED(CONFIG_KVM) || !is_hyp_mode_available())
1092                 return 0;
1093
1094         /*
1095          * For KVM, it is necessary to ensure that this CPU doesn't
1096          * support any vector length that guests may have probed as
1097          * unsupported.
1098          */
1099
1100         /* Recover the set of supported VQs: */
1101         bitmap_complement(tmp_map, tmp_map, SVE_VQ_MAX);
1102         /* Find VQs supported that are not globally supported: */
1103         bitmap_andnot(tmp_map, tmp_map, info->vq_map, SVE_VQ_MAX);
1104
1105         /* Find the lowest such VQ, if any: */
1106         b = find_last_bit(tmp_map, SVE_VQ_MAX);
1107         if (b >= SVE_VQ_MAX)
1108                 return 0; /* no mismatches */
1109
1110         /*
1111          * Mismatches above sve_max_virtualisable_vl are fine, since
1112          * no guest is allowed to configure ZCR_EL2.LEN to exceed this:
1113          */
1114         if (sve_vl_from_vq(__bit_to_vq(b)) <= info->max_virtualisable_vl) {
1115                 pr_warn("%s: cpu%d: Unsupported vector length(s) present\n",
1116                         info->name, smp_processor_id());
1117                 return -EINVAL;
1118         }
1119
1120         return 0;
1121 }
1122
1123 static void __init sve_efi_setup(void)
1124 {
1125         int max_vl = 0;
1126         int i;
1127
1128         if (!IS_ENABLED(CONFIG_EFI))
1129                 return;
1130
1131         for (i = 0; i < ARRAY_SIZE(vl_info); i++)
1132                 max_vl = max(vl_info[i].max_vl, max_vl);
1133
1134         /*
1135          * alloc_percpu() warns and prints a backtrace if this goes wrong.
1136          * This is evidence of a crippled system and we are returning void,
1137          * so no attempt is made to handle this situation here.
1138          */
1139         if (!sve_vl_valid(max_vl))
1140                 goto fail;
1141
1142         efi_sve_state = __alloc_percpu(
1143                 SVE_SIG_REGS_SIZE(sve_vq_from_vl(max_vl)), SVE_VQ_BYTES);
1144         if (!efi_sve_state)
1145                 goto fail;
1146
1147         return;
1148
1149 fail:
1150         panic("Cannot allocate percpu memory for EFI SVE save/restore");
1151 }
1152
1153 /*
1154  * Enable SVE for EL1.
1155  * Intended for use by the cpufeatures code during CPU boot.
1156  */
1157 void sve_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1158 {
1159         write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_ZEN_EL1EN, CPACR_EL1);
1160         isb();
1161 }
1162
1163 /*
1164  * Read the pseudo-ZCR used by cpufeatures to identify the supported SVE
1165  * vector length.
1166  *
1167  * Use only if SVE is present.
1168  * This function clobbers the SVE vector length.
1169  */
1170 u64 read_zcr_features(void)
1171 {
1172         u64 zcr;
1173         unsigned int vq_max;
1174
1175         /*
1176          * Set the maximum possible VL, and write zeroes to all other
1177          * bits to see if they stick.
1178          */
1179         sve_kernel_enable(NULL);
1180         write_sysreg_s(ZCR_ELx_LEN_MASK, SYS_ZCR_EL1);
1181
1182         zcr = read_sysreg_s(SYS_ZCR_EL1);
1183         zcr &= ~(u64)ZCR_ELx_LEN_MASK; /* find sticky 1s outside LEN field */
1184         vq_max = sve_vq_from_vl(sve_get_vl());
1185         zcr |= vq_max - 1; /* set LEN field to maximum effective value */
1186
1187         return zcr;
1188 }
1189
1190 void __init sve_setup(void)
1191 {
1192         struct vl_info *info = &vl_info[ARM64_VEC_SVE];
1193         u64 zcr;
1194         DECLARE_BITMAP(tmp_map, SVE_VQ_MAX);
1195         unsigned long b;
1196
1197         if (!system_supports_sve())
1198                 return;
1199
1200         /*
1201          * The SVE architecture mandates support for 128-bit vectors,
1202          * so sve_vq_map must have at least SVE_VQ_MIN set.
1203          * If something went wrong, at least try to patch it up:
1204          */
1205         if (WARN_ON(!test_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map)))
1206                 set_bit(__vq_to_bit(SVE_VQ_MIN), info->vq_map);
1207
1208         zcr = read_sanitised_ftr_reg(SYS_ZCR_EL1);
1209         info->max_vl = sve_vl_from_vq((zcr & ZCR_ELx_LEN_MASK) + 1);
1210
1211         /*
1212          * Sanity-check that the max VL we determined through CPU features
1213          * corresponds properly to sve_vq_map.  If not, do our best:
1214          */
1215         if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SVE,
1216                                                                  info->max_vl)))
1217                 info->max_vl = find_supported_vector_length(ARM64_VEC_SVE,
1218                                                             info->max_vl);
1219
1220         /*
1221          * For the default VL, pick the maximum supported value <= 64.
1222          * VL == 64 is guaranteed not to grow the signal frame.
1223          */
1224         set_sve_default_vl(find_supported_vector_length(ARM64_VEC_SVE, 64));
1225
1226         bitmap_andnot(tmp_map, info->vq_partial_map, info->vq_map,
1227                       SVE_VQ_MAX);
1228
1229         b = find_last_bit(tmp_map, SVE_VQ_MAX);
1230         if (b >= SVE_VQ_MAX)
1231                 /* No non-virtualisable VLs found */
1232                 info->max_virtualisable_vl = SVE_VQ_MAX;
1233         else if (WARN_ON(b == SVE_VQ_MAX - 1))
1234                 /* No virtualisable VLs?  This is architecturally forbidden. */
1235                 info->max_virtualisable_vl = SVE_VQ_MIN;
1236         else /* b + 1 < SVE_VQ_MAX */
1237                 info->max_virtualisable_vl = sve_vl_from_vq(__bit_to_vq(b + 1));
1238
1239         if (info->max_virtualisable_vl > info->max_vl)
1240                 info->max_virtualisable_vl = info->max_vl;
1241
1242         pr_info("%s: maximum available vector length %u bytes per vector\n",
1243                 info->name, info->max_vl);
1244         pr_info("%s: default vector length %u bytes per vector\n",
1245                 info->name, get_sve_default_vl());
1246
1247         /* KVM decides whether to support mismatched systems. Just warn here: */
1248         if (sve_max_virtualisable_vl() < sve_max_vl())
1249                 pr_warn("%s: unvirtualisable vector lengths present\n",
1250                         info->name);
1251
1252         sve_efi_setup();
1253 }
1254
1255 /*
1256  * Called from the put_task_struct() path, which cannot get here
1257  * unless dead_task is really dead and not schedulable.
1258  */
1259 void fpsimd_release_task(struct task_struct *dead_task)
1260 {
1261         __sve_free(dead_task);
1262         sme_free(dead_task);
1263 }
1264
1265 #endif /* CONFIG_ARM64_SVE */
1266
1267 #ifdef CONFIG_ARM64_SME
1268
1269 /*
1270  * Ensure that task->thread.za_state is allocated and sufficiently large.
1271  *
1272  * This function should be used only in preparation for replacing
1273  * task->thread.za_state with new data.  The memory is always zeroed
1274  * here to prevent stale data from showing through: this is done in
1275  * the interest of testability and predictability, the architecture
1276  * guarantees that when ZA is enabled it will be zeroed.
1277  */
1278 void sme_alloc(struct task_struct *task)
1279 {
1280         if (task->thread.za_state) {
1281                 memset(task->thread.za_state, 0, za_state_size(task));
1282                 return;
1283         }
1284
1285         /* This could potentially be up to 64K. */
1286         task->thread.za_state =
1287                 kzalloc(za_state_size(task), GFP_KERNEL);
1288 }
1289
1290 static void sme_free(struct task_struct *task)
1291 {
1292         kfree(task->thread.za_state);
1293         task->thread.za_state = NULL;
1294 }
1295
1296 void sme_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1297 {
1298         /* Set priority for all PEs to architecturally defined minimum */
1299         write_sysreg_s(read_sysreg_s(SYS_SMPRI_EL1) & ~SMPRI_EL1_PRIORITY_MASK,
1300                        SYS_SMPRI_EL1);
1301
1302         /* Allow SME in kernel */
1303         write_sysreg(read_sysreg(CPACR_EL1) | CPACR_EL1_SMEN_EL1EN, CPACR_EL1);
1304         isb();
1305
1306         /* Allow EL0 to access TPIDR2 */
1307         write_sysreg(read_sysreg(SCTLR_EL1) | SCTLR_ELx_ENTP2, SCTLR_EL1);
1308         isb();
1309 }
1310
1311 /*
1312  * This must be called after sme_kernel_enable(), we rely on the
1313  * feature table being sorted to ensure this.
1314  */
1315 void fa64_kernel_enable(const struct arm64_cpu_capabilities *__always_unused p)
1316 {
1317         /* Allow use of FA64 */
1318         write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_FA64_MASK,
1319                        SYS_SMCR_EL1);
1320 }
1321
1322 /*
1323  * Read the pseudo-SMCR used by cpufeatures to identify the supported
1324  * vector length.
1325  *
1326  * Use only if SME is present.
1327  * This function clobbers the SME vector length.
1328  */
1329 u64 read_smcr_features(void)
1330 {
1331         u64 smcr;
1332         unsigned int vq_max;
1333
1334         sme_kernel_enable(NULL);
1335         sme_smstart_sm();
1336
1337         /*
1338          * Set the maximum possible VL.
1339          */
1340         write_sysreg_s(read_sysreg_s(SYS_SMCR_EL1) | SMCR_ELx_LEN_MASK,
1341                        SYS_SMCR_EL1);
1342
1343         smcr = read_sysreg_s(SYS_SMCR_EL1);
1344         smcr &= ~(u64)SMCR_ELx_LEN_MASK; /* Only the LEN field */
1345         vq_max = sve_vq_from_vl(sve_get_vl());
1346         smcr |= vq_max - 1; /* set LEN field to maximum effective value */
1347
1348         sme_smstop_sm();
1349
1350         return smcr;
1351 }
1352
1353 void __init sme_setup(void)
1354 {
1355         struct vl_info *info = &vl_info[ARM64_VEC_SME];
1356         u64 smcr;
1357         int min_bit;
1358
1359         if (!system_supports_sme())
1360                 return;
1361
1362         /*
1363          * SME doesn't require any particular vector length be
1364          * supported but it does require at least one.  We should have
1365          * disabled the feature entirely while bringing up CPUs but
1366          * let's double check here.
1367          */
1368         WARN_ON(bitmap_empty(info->vq_map, SVE_VQ_MAX));
1369
1370         min_bit = find_last_bit(info->vq_map, SVE_VQ_MAX);
1371         info->min_vl = sve_vl_from_vq(__bit_to_vq(min_bit));
1372
1373         smcr = read_sanitised_ftr_reg(SYS_SMCR_EL1);
1374         info->max_vl = sve_vl_from_vq((smcr & SMCR_ELx_LEN_MASK) + 1);
1375
1376         /*
1377          * Sanity-check that the max VL we determined through CPU features
1378          * corresponds properly to sme_vq_map.  If not, do our best:
1379          */
1380         if (WARN_ON(info->max_vl != find_supported_vector_length(ARM64_VEC_SME,
1381                                                                  info->max_vl)))
1382                 info->max_vl = find_supported_vector_length(ARM64_VEC_SME,
1383                                                             info->max_vl);
1384
1385         WARN_ON(info->min_vl > info->max_vl);
1386
1387         /*
1388          * For the default VL, pick the maximum supported value <= 32
1389          * (256 bits) if there is one since this is guaranteed not to
1390          * grow the signal frame when in streaming mode, otherwise the
1391          * minimum available VL will be used.
1392          */
1393         set_sme_default_vl(find_supported_vector_length(ARM64_VEC_SME, 32));
1394
1395         pr_info("SME: minimum available vector length %u bytes per vector\n",
1396                 info->min_vl);
1397         pr_info("SME: maximum available vector length %u bytes per vector\n",
1398                 info->max_vl);
1399         pr_info("SME: default vector length %u bytes per vector\n",
1400                 get_sme_default_vl());
1401 }
1402
1403 #endif /* CONFIG_ARM64_SME */
1404
1405 static void sve_init_regs(void)
1406 {
1407         /*
1408          * Convert the FPSIMD state to SVE, zeroing all the state that
1409          * is not shared with FPSIMD. If (as is likely) the current
1410          * state is live in the registers then do this there and
1411          * update our metadata for the current task including
1412          * disabling the trap, otherwise update our in-memory copy.
1413          * We are guaranteed to not be in streaming mode, we can only
1414          * take a SVE trap when not in streaming mode and we can't be
1415          * in streaming mode when taking a SME trap.
1416          */
1417         if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1418                 unsigned long vq_minus_one =
1419                         sve_vq_from_vl(task_get_sve_vl(current)) - 1;
1420                 sve_set_vq(vq_minus_one);
1421                 sve_flush_live(true, vq_minus_one);
1422                 fpsimd_bind_task_to_cpu();
1423         } else {
1424                 fpsimd_to_sve(current);
1425                 current->thread.fp_type = FP_STATE_SVE;
1426         }
1427 }
1428
1429 /*
1430  * Trapped SVE access
1431  *
1432  * Storage is allocated for the full SVE state, the current FPSIMD
1433  * register contents are migrated across, and the access trap is
1434  * disabled.
1435  *
1436  * TIF_SVE should be clear on entry: otherwise, fpsimd_restore_current_state()
1437  * would have disabled the SVE access trap for userspace during
1438  * ret_to_user, making an SVE access trap impossible in that case.
1439  */
1440 void do_sve_acc(unsigned long esr, struct pt_regs *regs)
1441 {
1442         /* Even if we chose not to use SVE, the hardware could still trap: */
1443         if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) {
1444                 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1445                 return;
1446         }
1447
1448         sve_alloc(current, true);
1449         if (!current->thread.sve_state) {
1450                 force_sig(SIGKILL);
1451                 return;
1452         }
1453
1454         get_cpu_fpsimd_context();
1455
1456         if (test_and_set_thread_flag(TIF_SVE))
1457                 WARN_ON(1); /* SVE access shouldn't have trapped */
1458
1459         /*
1460          * Even if the task can have used streaming mode we can only
1461          * generate SVE access traps in normal SVE mode and
1462          * transitioning out of streaming mode may discard any
1463          * streaming mode state.  Always clear the high bits to avoid
1464          * any potential errors tracking what is properly initialised.
1465          */
1466         sve_init_regs();
1467
1468         put_cpu_fpsimd_context();
1469 }
1470
1471 /*
1472  * Trapped SME access
1473  *
1474  * Storage is allocated for the full SVE and SME state, the current
1475  * FPSIMD register contents are migrated to SVE if SVE is not already
1476  * active, and the access trap is disabled.
1477  *
1478  * TIF_SME should be clear on entry: otherwise, fpsimd_restore_current_state()
1479  * would have disabled the SME access trap for userspace during
1480  * ret_to_user, making an SVE access trap impossible in that case.
1481  */
1482 void do_sme_acc(unsigned long esr, struct pt_regs *regs)
1483 {
1484         /* Even if we chose not to use SME, the hardware could still trap: */
1485         if (unlikely(!system_supports_sme()) || WARN_ON(is_compat_task())) {
1486                 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1487                 return;
1488         }
1489
1490         /*
1491          * If this not a trap due to SME being disabled then something
1492          * is being used in the wrong mode, report as SIGILL.
1493          */
1494         if (ESR_ELx_ISS(esr) != ESR_ELx_SME_ISS_SME_DISABLED) {
1495                 force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0);
1496                 return;
1497         }
1498
1499         sve_alloc(current, false);
1500         sme_alloc(current);
1501         if (!current->thread.sve_state || !current->thread.za_state) {
1502                 force_sig(SIGKILL);
1503                 return;
1504         }
1505
1506         get_cpu_fpsimd_context();
1507
1508         /* With TIF_SME userspace shouldn't generate any traps */
1509         if (test_and_set_thread_flag(TIF_SME))
1510                 WARN_ON(1);
1511
1512         if (!test_thread_flag(TIF_FOREIGN_FPSTATE)) {
1513                 unsigned long vq_minus_one =
1514                         sve_vq_from_vl(task_get_sme_vl(current)) - 1;
1515                 sme_set_vq(vq_minus_one);
1516
1517                 fpsimd_bind_task_to_cpu();
1518         }
1519
1520         put_cpu_fpsimd_context();
1521 }
1522
1523 /*
1524  * Trapped FP/ASIMD access.
1525  */
1526 void do_fpsimd_acc(unsigned long esr, struct pt_regs *regs)
1527 {
1528         /* TODO: implement lazy context saving/restoring */
1529         WARN_ON(1);
1530 }
1531
1532 /*
1533  * Raise a SIGFPE for the current process.
1534  */
1535 void do_fpsimd_exc(unsigned long esr, struct pt_regs *regs)
1536 {
1537         unsigned int si_code = FPE_FLTUNK;
1538
1539         if (esr & ESR_ELx_FP_EXC_TFV) {
1540                 if (esr & FPEXC_IOF)
1541                         si_code = FPE_FLTINV;
1542                 else if (esr & FPEXC_DZF)
1543                         si_code = FPE_FLTDIV;
1544                 else if (esr & FPEXC_OFF)
1545                         si_code = FPE_FLTOVF;
1546                 else if (esr & FPEXC_UFF)
1547                         si_code = FPE_FLTUND;
1548                 else if (esr & FPEXC_IXF)
1549                         si_code = FPE_FLTRES;
1550         }
1551
1552         send_sig_fault(SIGFPE, si_code,
1553                        (void __user *)instruction_pointer(regs),
1554                        current);
1555 }
1556
1557 void fpsimd_thread_switch(struct task_struct *next)
1558 {
1559         bool wrong_task, wrong_cpu;
1560
1561         if (!system_supports_fpsimd())
1562                 return;
1563
1564         __get_cpu_fpsimd_context();
1565
1566         /* Save unsaved fpsimd state, if any: */
1567         fpsimd_save();
1568
1569         /*
1570          * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's
1571          * state.  For kernel threads, FPSIMD registers are never loaded
1572          * and wrong_task and wrong_cpu will always be true.
1573          */
1574         wrong_task = __this_cpu_read(fpsimd_last_state.st) !=
1575                                         &next->thread.uw.fpsimd_state;
1576         wrong_cpu = next->thread.fpsimd_cpu != smp_processor_id();
1577
1578         update_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE,
1579                                wrong_task || wrong_cpu);
1580
1581         __put_cpu_fpsimd_context();
1582 }
1583
1584 static void fpsimd_flush_thread_vl(enum vec_type type)
1585 {
1586         int vl, supported_vl;
1587
1588         /*
1589          * Reset the task vector length as required.  This is where we
1590          * ensure that all user tasks have a valid vector length
1591          * configured: no kernel task can become a user task without
1592          * an exec and hence a call to this function.  By the time the
1593          * first call to this function is made, all early hardware
1594          * probing is complete, so __sve_default_vl should be valid.
1595          * If a bug causes this to go wrong, we make some noise and
1596          * try to fudge thread.sve_vl to a safe value here.
1597          */
1598         vl = task_get_vl_onexec(current, type);
1599         if (!vl)
1600                 vl = get_default_vl(type);
1601
1602         if (WARN_ON(!sve_vl_valid(vl)))
1603                 vl = vl_info[type].min_vl;
1604
1605         supported_vl = find_supported_vector_length(type, vl);
1606         if (WARN_ON(supported_vl != vl))
1607                 vl = supported_vl;
1608
1609         task_set_vl(current, type, vl);
1610
1611         /*
1612          * If the task is not set to inherit, ensure that the vector
1613          * length will be reset by a subsequent exec:
1614          */
1615         if (!test_thread_flag(vec_vl_inherit_flag(type)))
1616                 task_set_vl_onexec(current, type, 0);
1617 }
1618
1619 void fpsimd_flush_thread(void)
1620 {
1621         void *sve_state = NULL;
1622         void *za_state = NULL;
1623
1624         if (!system_supports_fpsimd())
1625                 return;
1626
1627         get_cpu_fpsimd_context();
1628
1629         fpsimd_flush_task_state(current);
1630         memset(&current->thread.uw.fpsimd_state, 0,
1631                sizeof(current->thread.uw.fpsimd_state));
1632
1633         if (system_supports_sve()) {
1634                 clear_thread_flag(TIF_SVE);
1635
1636                 /* Defer kfree() while in atomic context */
1637                 sve_state = current->thread.sve_state;
1638                 current->thread.sve_state = NULL;
1639
1640                 fpsimd_flush_thread_vl(ARM64_VEC_SVE);
1641         }
1642
1643         if (system_supports_sme()) {
1644                 clear_thread_flag(TIF_SME);
1645
1646                 /* Defer kfree() while in atomic context */
1647                 za_state = current->thread.za_state;
1648                 current->thread.za_state = NULL;
1649
1650                 fpsimd_flush_thread_vl(ARM64_VEC_SME);
1651                 current->thread.svcr = 0;
1652         }
1653
1654         current->thread.fp_type = FP_STATE_FPSIMD;
1655
1656         put_cpu_fpsimd_context();
1657         kfree(sve_state);
1658         kfree(za_state);
1659 }
1660
1661 /*
1662  * Save the userland FPSIMD state of 'current' to memory, but only if the state
1663  * currently held in the registers does in fact belong to 'current'
1664  */
1665 void fpsimd_preserve_current_state(void)
1666 {
1667         if (!system_supports_fpsimd())
1668                 return;
1669
1670         get_cpu_fpsimd_context();
1671         fpsimd_save();
1672         put_cpu_fpsimd_context();
1673 }
1674
1675 /*
1676  * Like fpsimd_preserve_current_state(), but ensure that
1677  * current->thread.uw.fpsimd_state is updated so that it can be copied to
1678  * the signal frame.
1679  */
1680 void fpsimd_signal_preserve_current_state(void)
1681 {
1682         fpsimd_preserve_current_state();
1683         if (test_thread_flag(TIF_SVE))
1684                 sve_to_fpsimd(current);
1685 }
1686
1687 /*
1688  * Called by KVM when entering the guest.
1689  */
1690 void fpsimd_kvm_prepare(void)
1691 {
1692         if (!system_supports_sve())
1693                 return;
1694
1695         /*
1696          * KVM does not save host SVE state since we can only enter
1697          * the guest from a syscall so the ABI means that only the
1698          * non-saved SVE state needs to be saved.  If we have left
1699          * SVE enabled for performance reasons then update the task
1700          * state to be FPSIMD only.
1701          */
1702         get_cpu_fpsimd_context();
1703
1704         if (test_and_clear_thread_flag(TIF_SVE)) {
1705                 sve_to_fpsimd(current);
1706                 current->thread.fp_type = FP_STATE_FPSIMD;
1707         }
1708
1709         put_cpu_fpsimd_context();
1710 }
1711
1712 /*
1713  * Associate current's FPSIMD context with this cpu
1714  * The caller must have ownership of the cpu FPSIMD context before calling
1715  * this function.
1716  */
1717 static void fpsimd_bind_task_to_cpu(void)
1718 {
1719         struct fpsimd_last_state_struct *last =
1720                 this_cpu_ptr(&fpsimd_last_state);
1721
1722         WARN_ON(!system_supports_fpsimd());
1723         last->st = &current->thread.uw.fpsimd_state;
1724         last->sve_state = current->thread.sve_state;
1725         last->za_state = current->thread.za_state;
1726         last->sve_vl = task_get_sve_vl(current);
1727         last->sme_vl = task_get_sme_vl(current);
1728         last->svcr = &current->thread.svcr;
1729         last->fp_type = &current->thread.fp_type;
1730         last->to_save = FP_STATE_CURRENT;
1731         current->thread.fpsimd_cpu = smp_processor_id();
1732
1733         /*
1734          * Toggle SVE and SME trapping for userspace if needed, these
1735          * are serialsied by ret_to_user().
1736          */
1737         if (system_supports_sme()) {
1738                 if (test_thread_flag(TIF_SME))
1739                         sme_user_enable();
1740                 else
1741                         sme_user_disable();
1742         }
1743
1744         if (system_supports_sve()) {
1745                 if (test_thread_flag(TIF_SVE))
1746                         sve_user_enable();
1747                 else
1748                         sve_user_disable();
1749         }
1750 }
1751
1752 void fpsimd_bind_state_to_cpu(struct user_fpsimd_state *st, void *sve_state,
1753                               unsigned int sve_vl, void *za_state,
1754                               unsigned int sme_vl, u64 *svcr,
1755                               enum fp_type *type, enum fp_type to_save)
1756 {
1757         struct fpsimd_last_state_struct *last =
1758                 this_cpu_ptr(&fpsimd_last_state);
1759
1760         WARN_ON(!system_supports_fpsimd());
1761         WARN_ON(!in_softirq() && !irqs_disabled());
1762
1763         last->st = st;
1764         last->svcr = svcr;
1765         last->sve_state = sve_state;
1766         last->za_state = za_state;
1767         last->sve_vl = sve_vl;
1768         last->sme_vl = sme_vl;
1769         last->fp_type = type;
1770         last->to_save = to_save;
1771 }
1772
1773 /*
1774  * Load the userland FPSIMD state of 'current' from memory, but only if the
1775  * FPSIMD state already held in the registers is /not/ the most recent FPSIMD
1776  * state of 'current'.  This is called when we are preparing to return to
1777  * userspace to ensure that userspace sees a good register state.
1778  */
1779 void fpsimd_restore_current_state(void)
1780 {
1781         /*
1782          * For the tasks that were created before we detected the absence of
1783          * FP/SIMD, the TIF_FOREIGN_FPSTATE could be set via fpsimd_thread_switch(),
1784          * e.g, init. This could be then inherited by the children processes.
1785          * If we later detect that the system doesn't support FP/SIMD,
1786          * we must clear the flag for  all the tasks to indicate that the
1787          * FPSTATE is clean (as we can't have one) to avoid looping for ever in
1788          * do_notify_resume().
1789          */
1790         if (!system_supports_fpsimd()) {
1791                 clear_thread_flag(TIF_FOREIGN_FPSTATE);
1792                 return;
1793         }
1794
1795         get_cpu_fpsimd_context();
1796
1797         if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) {
1798                 task_fpsimd_load();
1799                 fpsimd_bind_task_to_cpu();
1800         }
1801
1802         put_cpu_fpsimd_context();
1803 }
1804
1805 /*
1806  * Load an updated userland FPSIMD state for 'current' from memory and set the
1807  * flag that indicates that the FPSIMD register contents are the most recent
1808  * FPSIMD state of 'current'. This is used by the signal code to restore the
1809  * register state when returning from a signal handler in FPSIMD only cases,
1810  * any SVE context will be discarded.
1811  */
1812 void fpsimd_update_current_state(struct user_fpsimd_state const *state)
1813 {
1814         if (WARN_ON(!system_supports_fpsimd()))
1815                 return;
1816
1817         get_cpu_fpsimd_context();
1818
1819         current->thread.uw.fpsimd_state = *state;
1820         if (test_thread_flag(TIF_SVE))
1821                 fpsimd_to_sve(current);
1822
1823         task_fpsimd_load();
1824         fpsimd_bind_task_to_cpu();
1825
1826         clear_thread_flag(TIF_FOREIGN_FPSTATE);
1827
1828         put_cpu_fpsimd_context();
1829 }
1830
1831 /*
1832  * Invalidate live CPU copies of task t's FPSIMD state
1833  *
1834  * This function may be called with preemption enabled.  The barrier()
1835  * ensures that the assignment to fpsimd_cpu is visible to any
1836  * preemption/softirq that could race with set_tsk_thread_flag(), so
1837  * that TIF_FOREIGN_FPSTATE cannot be spuriously re-cleared.
1838  *
1839  * The final barrier ensures that TIF_FOREIGN_FPSTATE is seen set by any
1840  * subsequent code.
1841  */
1842 void fpsimd_flush_task_state(struct task_struct *t)
1843 {
1844         t->thread.fpsimd_cpu = NR_CPUS;
1845         /*
1846          * If we don't support fpsimd, bail out after we have
1847          * reset the fpsimd_cpu for this task and clear the
1848          * FPSTATE.
1849          */
1850         if (!system_supports_fpsimd())
1851                 return;
1852         barrier();
1853         set_tsk_thread_flag(t, TIF_FOREIGN_FPSTATE);
1854
1855         barrier();
1856 }
1857
1858 /*
1859  * Invalidate any task's FPSIMD state that is present on this cpu.
1860  * The FPSIMD context should be acquired with get_cpu_fpsimd_context()
1861  * before calling this function.
1862  */
1863 static void fpsimd_flush_cpu_state(void)
1864 {
1865         WARN_ON(!system_supports_fpsimd());
1866         __this_cpu_write(fpsimd_last_state.st, NULL);
1867
1868         /*
1869          * Leaving streaming mode enabled will cause issues for any kernel
1870          * NEON and leaving streaming mode or ZA enabled may increase power
1871          * consumption.
1872          */
1873         if (system_supports_sme())
1874                 sme_smstop();
1875
1876         set_thread_flag(TIF_FOREIGN_FPSTATE);
1877 }
1878
1879 /*
1880  * Save the FPSIMD state to memory and invalidate cpu view.
1881  * This function must be called with preemption disabled.
1882  */
1883 void fpsimd_save_and_flush_cpu_state(void)
1884 {
1885         if (!system_supports_fpsimd())
1886                 return;
1887         WARN_ON(preemptible());
1888         __get_cpu_fpsimd_context();
1889         fpsimd_save();
1890         fpsimd_flush_cpu_state();
1891         __put_cpu_fpsimd_context();
1892 }
1893
1894 #ifdef CONFIG_KERNEL_MODE_NEON
1895
1896 /*
1897  * Kernel-side NEON support functions
1898  */
1899
1900 /*
1901  * kernel_neon_begin(): obtain the CPU FPSIMD registers for use by the calling
1902  * context
1903  *
1904  * Must not be called unless may_use_simd() returns true.
1905  * Task context in the FPSIMD registers is saved back to memory as necessary.
1906  *
1907  * A matching call to kernel_neon_end() must be made before returning from the
1908  * calling context.
1909  *
1910  * The caller may freely use the FPSIMD registers until kernel_neon_end() is
1911  * called.
1912  */
1913 void kernel_neon_begin(void)
1914 {
1915         if (WARN_ON(!system_supports_fpsimd()))
1916                 return;
1917
1918         BUG_ON(!may_use_simd());
1919
1920         get_cpu_fpsimd_context();
1921
1922         /* Save unsaved fpsimd state, if any: */
1923         fpsimd_save();
1924
1925         /* Invalidate any task state remaining in the fpsimd regs: */
1926         fpsimd_flush_cpu_state();
1927 }
1928 EXPORT_SYMBOL(kernel_neon_begin);
1929
1930 /*
1931  * kernel_neon_end(): give the CPU FPSIMD registers back to the current task
1932  *
1933  * Must be called from a context in which kernel_neon_begin() was previously
1934  * called, with no call to kernel_neon_end() in the meantime.
1935  *
1936  * The caller must not use the FPSIMD registers after this function is called,
1937  * unless kernel_neon_begin() is called again in the meantime.
1938  */
1939 void kernel_neon_end(void)
1940 {
1941         if (!system_supports_fpsimd())
1942                 return;
1943
1944         put_cpu_fpsimd_context();
1945 }
1946 EXPORT_SYMBOL(kernel_neon_end);
1947
1948 #ifdef CONFIG_EFI
1949
1950 static DEFINE_PER_CPU(struct user_fpsimd_state, efi_fpsimd_state);
1951 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
1952 static DEFINE_PER_CPU(bool, efi_sve_state_used);
1953 static DEFINE_PER_CPU(bool, efi_sm_state);
1954
1955 /*
1956  * EFI runtime services support functions
1957  *
1958  * The ABI for EFI runtime services allows EFI to use FPSIMD during the call.
1959  * This means that for EFI (and only for EFI), we have to assume that FPSIMD
1960  * is always used rather than being an optional accelerator.
1961  *
1962  * These functions provide the necessary support for ensuring FPSIMD
1963  * save/restore in the contexts from which EFI is used.
1964  *
1965  * Do not use them for any other purpose -- if tempted to do so, you are
1966  * either doing something wrong or you need to propose some refactoring.
1967  */
1968
1969 /*
1970  * __efi_fpsimd_begin(): prepare FPSIMD for making an EFI runtime services call
1971  */
1972 void __efi_fpsimd_begin(void)
1973 {
1974         if (!system_supports_fpsimd())
1975                 return;
1976
1977         WARN_ON(preemptible());
1978
1979         if (may_use_simd()) {
1980                 kernel_neon_begin();
1981         } else {
1982                 /*
1983                  * If !efi_sve_state, SVE can't be in use yet and doesn't need
1984                  * preserving:
1985                  */
1986                 if (system_supports_sve() && likely(efi_sve_state)) {
1987                         char *sve_state = this_cpu_ptr(efi_sve_state);
1988                         bool ffr = true;
1989                         u64 svcr;
1990
1991                         __this_cpu_write(efi_sve_state_used, true);
1992
1993                         if (system_supports_sme()) {
1994                                 svcr = read_sysreg_s(SYS_SVCR);
1995
1996                                 __this_cpu_write(efi_sm_state,
1997                                                  svcr & SVCR_SM_MASK);
1998
1999                                 /*
2000                                  * Unless we have FA64 FFR does not
2001                                  * exist in streaming mode.
2002                                  */
2003                                 if (!system_supports_fa64())
2004                                         ffr = !(svcr & SVCR_SM_MASK);
2005                         }
2006
2007                         sve_save_state(sve_state + sve_ffr_offset(sve_max_vl()),
2008                                        &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
2009                                        ffr);
2010
2011                         if (system_supports_sme())
2012                                 sysreg_clear_set_s(SYS_SVCR,
2013                                                    SVCR_SM_MASK, 0);
2014
2015                 } else {
2016                         fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
2017                 }
2018
2019                 __this_cpu_write(efi_fpsimd_state_used, true);
2020         }
2021 }
2022
2023 /*
2024  * __efi_fpsimd_end(): clean up FPSIMD after an EFI runtime services call
2025  */
2026 void __efi_fpsimd_end(void)
2027 {
2028         if (!system_supports_fpsimd())
2029                 return;
2030
2031         if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
2032                 kernel_neon_end();
2033         } else {
2034                 if (system_supports_sve() &&
2035                     likely(__this_cpu_read(efi_sve_state_used))) {
2036                         char const *sve_state = this_cpu_ptr(efi_sve_state);
2037                         bool ffr = true;
2038
2039                         /*
2040                          * Restore streaming mode; EFI calls are
2041                          * normal function calls so should not return in
2042                          * streaming mode.
2043                          */
2044                         if (system_supports_sme()) {
2045                                 if (__this_cpu_read(efi_sm_state)) {
2046                                         sysreg_clear_set_s(SYS_SVCR,
2047                                                            0,
2048                                                            SVCR_SM_MASK);
2049
2050                                         /*
2051                                          * Unless we have FA64 FFR does not
2052                                          * exist in streaming mode.
2053                                          */
2054                                         if (!system_supports_fa64())
2055                                                 ffr = false;
2056                                 }
2057                         }
2058
2059                         sve_load_state(sve_state + sve_ffr_offset(sve_max_vl()),
2060                                        &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
2061                                        ffr);
2062
2063                         __this_cpu_write(efi_sve_state_used, false);
2064                 } else {
2065                         fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
2066                 }
2067         }
2068 }
2069
2070 #endif /* CONFIG_EFI */
2071
2072 #endif /* CONFIG_KERNEL_MODE_NEON */
2073
2074 #ifdef CONFIG_CPU_PM
2075 static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
2076                                   unsigned long cmd, void *v)
2077 {
2078         switch (cmd) {
2079         case CPU_PM_ENTER:
2080                 fpsimd_save_and_flush_cpu_state();
2081                 break;
2082         case CPU_PM_EXIT:
2083                 break;
2084         case CPU_PM_ENTER_FAILED:
2085         default:
2086                 return NOTIFY_DONE;
2087         }
2088         return NOTIFY_OK;
2089 }
2090
2091 static struct notifier_block fpsimd_cpu_pm_notifier_block = {
2092         .notifier_call = fpsimd_cpu_pm_notifier,
2093 };
2094
2095 static void __init fpsimd_pm_init(void)
2096 {
2097         cpu_pm_register_notifier(&fpsimd_cpu_pm_notifier_block);
2098 }
2099
2100 #else
2101 static inline void fpsimd_pm_init(void) { }
2102 #endif /* CONFIG_CPU_PM */
2103
2104 #ifdef CONFIG_HOTPLUG_CPU
2105 static int fpsimd_cpu_dead(unsigned int cpu)
2106 {
2107         per_cpu(fpsimd_last_state.st, cpu) = NULL;
2108         return 0;
2109 }
2110
2111 static inline void fpsimd_hotplug_init(void)
2112 {
2113         cpuhp_setup_state_nocalls(CPUHP_ARM64_FPSIMD_DEAD, "arm64/fpsimd:dead",
2114                                   NULL, fpsimd_cpu_dead);
2115 }
2116
2117 #else
2118 static inline void fpsimd_hotplug_init(void) { }
2119 #endif
2120
2121 /*
2122  * FP/SIMD support code initialisation.
2123  */
2124 static int __init fpsimd_init(void)
2125 {
2126         if (cpu_have_named_feature(FP)) {
2127                 fpsimd_pm_init();
2128                 fpsimd_hotplug_init();
2129         } else {
2130                 pr_notice("Floating-point is not implemented\n");
2131         }
2132
2133         if (!cpu_have_named_feature(ASIMD))
2134                 pr_notice("Advanced SIMD is not implemented\n");
2135
2136
2137         if (cpu_have_named_feature(SME) && !cpu_have_named_feature(SVE))
2138                 pr_notice("SME is implemented but not SVE\n");
2139
2140         sve_sysctl_init();
2141         sme_sysctl_init();
2142
2143         return 0;
2144 }
2145 core_initcall(fpsimd_init);