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