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