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