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