3558cd05c62f64e7fee60b2b208ca0160239fb09
[platform/kernel/linux-rpi.git] / arch / x86 / include / asm / fpu / internal.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Copyright (C) 1994 Linus Torvalds
4  *
5  * Pentium III FXSR, SSE support
6  * General FPU state handling cleanups
7  *      Gareth Hughes <gareth@valinux.com>, May 2000
8  * x86-64 work by Andi Kleen 2002
9  */
10
11 #ifndef _ASM_X86_FPU_INTERNAL_H
12 #define _ASM_X86_FPU_INTERNAL_H
13
14 #include <linux/compat.h>
15 #include <linux/sched.h>
16 #include <linux/slab.h>
17 #include <linux/mm.h>
18
19 #include <asm/user.h>
20 #include <asm/fpu/api.h>
21 #include <asm/fpu/xstate.h>
22 #include <asm/fpu/xcr.h>
23 #include <asm/cpufeature.h>
24 #include <asm/trace/fpu.h>
25
26 /*
27  * High level FPU state handling functions:
28  */
29 extern void fpu__save(struct fpu *fpu);
30 extern int  fpu__restore_sig(void __user *buf, int ia32_frame);
31 extern void fpu__drop(struct fpu *fpu);
32 extern int  fpu__copy(struct task_struct *dst, struct task_struct *src);
33 extern void fpu__clear_user_states(struct fpu *fpu);
34 extern void fpu__clear_all(struct fpu *fpu);
35 extern int  fpu__exception_code(struct fpu *fpu, int trap_nr);
36
37 /*
38  * Boot time FPU initialization functions:
39  */
40 extern void fpu__init_cpu(void);
41 extern void fpu__init_system_xstate(void);
42 extern void fpu__init_cpu_xstate(void);
43 extern void fpu__init_system(struct cpuinfo_x86 *c);
44 extern void fpu__init_check_bugs(void);
45 extern void fpu__resume_cpu(void);
46
47 /*
48  * Debugging facility:
49  */
50 #ifdef CONFIG_X86_DEBUG_FPU
51 # define WARN_ON_FPU(x) WARN_ON_ONCE(x)
52 #else
53 # define WARN_ON_FPU(x) ({ (void)(x); 0; })
54 #endif
55
56 /*
57  * FPU related CPU feature flag helper routines:
58  */
59 static __always_inline __pure bool use_xsaveopt(void)
60 {
61         return static_cpu_has(X86_FEATURE_XSAVEOPT);
62 }
63
64 static __always_inline __pure bool use_xsave(void)
65 {
66         return static_cpu_has(X86_FEATURE_XSAVE);
67 }
68
69 static __always_inline __pure bool use_fxsr(void)
70 {
71         return static_cpu_has(X86_FEATURE_FXSR);
72 }
73
74 /*
75  * fpstate handling functions:
76  */
77
78 extern union fpregs_state init_fpstate;
79
80 extern void fpstate_init(union fpregs_state *state);
81 #ifdef CONFIG_MATH_EMULATION
82 extern void fpstate_init_soft(struct swregs_state *soft);
83 #else
84 static inline void fpstate_init_soft(struct swregs_state *soft) {}
85 #endif
86 extern void save_fpregs_to_fpstate(struct fpu *fpu);
87
88 #define user_insn(insn, output, input...)                               \
89 ({                                                                      \
90         int err;                                                        \
91                                                                         \
92         might_fault();                                                  \
93                                                                         \
94         asm volatile(ASM_STAC "\n"                                      \
95                      "1:" #insn "\n\t"                                  \
96                      "2: " ASM_CLAC "\n"                                \
97                      ".section .fixup,\"ax\"\n"                         \
98                      "3:  movl $-1,%[err]\n"                            \
99                      "    jmp  2b\n"                                    \
100                      ".previous\n"                                      \
101                      _ASM_EXTABLE(1b, 3b)                               \
102                      : [err] "=r" (err), output                         \
103                      : "0"(0), input);                                  \
104         err;                                                            \
105 })
106
107 #define kernel_insn_err(insn, output, input...)                         \
108 ({                                                                      \
109         int err;                                                        \
110         asm volatile("1:" #insn "\n\t"                                  \
111                      "2:\n"                                             \
112                      ".section .fixup,\"ax\"\n"                         \
113                      "3:  movl $-1,%[err]\n"                            \
114                      "    jmp  2b\n"                                    \
115                      ".previous\n"                                      \
116                      _ASM_EXTABLE(1b, 3b)                               \
117                      : [err] "=r" (err), output                         \
118                      : "0"(0), input);                                  \
119         err;                                                            \
120 })
121
122 #define kernel_insn(insn, output, input...)                             \
123         asm volatile("1:" #insn "\n\t"                                  \
124                      "2:\n"                                             \
125                      _ASM_EXTABLE_HANDLE(1b, 2b, ex_handler_fprestore)  \
126                      : output : input)
127
128 static inline int fnsave_to_user_sigframe(struct fregs_state __user *fx)
129 {
130         return user_insn(fnsave %[fx]; fwait,  [fx] "=m" (*fx), "m" (*fx));
131 }
132
133 static inline int fxsave_to_user_sigframe(struct fxregs_state __user *fx)
134 {
135         if (IS_ENABLED(CONFIG_X86_32))
136                 return user_insn(fxsave %[fx], [fx] "=m" (*fx), "m" (*fx));
137         else
138                 return user_insn(fxsaveq %[fx], [fx] "=m" (*fx), "m" (*fx));
139
140 }
141
142 static inline void fxrstor(struct fxregs_state *fx)
143 {
144         if (IS_ENABLED(CONFIG_X86_32))
145                 kernel_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
146         else
147                 kernel_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
148 }
149
150 static inline int fxrstor_safe(struct fxregs_state *fx)
151 {
152         if (IS_ENABLED(CONFIG_X86_32))
153                 return kernel_insn_err(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
154         else
155                 return kernel_insn_err(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
156 }
157
158 static inline int fxrstor_from_user_sigframe(struct fxregs_state __user *fx)
159 {
160         if (IS_ENABLED(CONFIG_X86_32))
161                 return user_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
162         else
163                 return user_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
164 }
165
166 static inline void frstor(struct fregs_state *fx)
167 {
168         kernel_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
169 }
170
171 static inline int frstor_safe(struct fregs_state *fx)
172 {
173         return kernel_insn_err(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
174 }
175
176 static inline int frstor_from_user_sigframe(struct fregs_state __user *fx)
177 {
178         return user_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
179 }
180
181 static inline void fxsave(struct fxregs_state *fx)
182 {
183         if (IS_ENABLED(CONFIG_X86_32))
184                 asm volatile( "fxsave %[fx]" : [fx] "=m" (*fx));
185         else
186                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (*fx));
187 }
188
189 /* These macros all use (%edi)/(%rdi) as the single memory argument. */
190 #define XSAVE           ".byte " REX_PREFIX "0x0f,0xae,0x27"
191 #define XSAVEOPT        ".byte " REX_PREFIX "0x0f,0xae,0x37"
192 #define XSAVES          ".byte " REX_PREFIX "0x0f,0xc7,0x2f"
193 #define XRSTOR          ".byte " REX_PREFIX "0x0f,0xae,0x2f"
194 #define XRSTORS         ".byte " REX_PREFIX "0x0f,0xc7,0x1f"
195
196 #define XSTATE_OP(op, st, lmask, hmask, err)                            \
197         asm volatile("1:" op "\n\t"                                     \
198                      "xor %[err], %[err]\n"                             \
199                      "2:\n\t"                                           \
200                      ".pushsection .fixup,\"ax\"\n\t"                   \
201                      "3: movl $-2,%[err]\n\t"                           \
202                      "jmp 2b\n\t"                                       \
203                      ".popsection\n\t"                                  \
204                      _ASM_EXTABLE(1b, 3b)                               \
205                      : [err] "=r" (err)                                 \
206                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
207                      : "memory")
208
209 /*
210  * If XSAVES is enabled, it replaces XSAVEOPT because it supports a compact
211  * format and supervisor states in addition to modified optimization in
212  * XSAVEOPT.
213  *
214  * Otherwise, if XSAVEOPT is enabled, XSAVEOPT replaces XSAVE because XSAVEOPT
215  * supports modified optimization which is not supported by XSAVE.
216  *
217  * We use XSAVE as a fallback.
218  *
219  * The 661 label is defined in the ALTERNATIVE* macros as the address of the
220  * original instruction which gets replaced. We need to use it here as the
221  * address of the instruction where we might get an exception at.
222  */
223 #define XSTATE_XSAVE(st, lmask, hmask, err)                             \
224         asm volatile(ALTERNATIVE_2(XSAVE,                               \
225                                    XSAVEOPT, X86_FEATURE_XSAVEOPT,      \
226                                    XSAVES,   X86_FEATURE_XSAVES)        \
227                      "\n"                                               \
228                      "xor %[err], %[err]\n"                             \
229                      "3:\n"                                             \
230                      ".pushsection .fixup,\"ax\"\n"                     \
231                      "4: movl $-2, %[err]\n"                            \
232                      "jmp 3b\n"                                         \
233                      ".popsection\n"                                    \
234                      _ASM_EXTABLE(661b, 4b)                             \
235                      : [err] "=r" (err)                                 \
236                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
237                      : "memory")
238
239 /*
240  * Use XRSTORS to restore context if it is enabled. XRSTORS supports compact
241  * XSAVE area format.
242  */
243 #define XSTATE_XRESTORE(st, lmask, hmask)                               \
244         asm volatile(ALTERNATIVE(XRSTOR,                                \
245                                  XRSTORS, X86_FEATURE_XSAVES)           \
246                      "\n"                                               \
247                      "3:\n"                                             \
248                      _ASM_EXTABLE_HANDLE(661b, 3b, ex_handler_fprestore)\
249                      :                                                  \
250                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
251                      : "memory")
252
253 /*
254  * This function is called only during boot time when x86 caps are not set
255  * up and alternative can not be used yet.
256  */
257 static inline void os_xrstor_booting(struct xregs_state *xstate)
258 {
259         u64 mask = -1;
260         u32 lmask = mask;
261         u32 hmask = mask >> 32;
262         int err;
263
264         WARN_ON(system_state != SYSTEM_BOOTING);
265
266         if (boot_cpu_has(X86_FEATURE_XSAVES))
267                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
268         else
269                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
270
271         /*
272          * We should never fault when copying from a kernel buffer, and the FPU
273          * state we set at boot time should be valid.
274          */
275         WARN_ON_FPU(err);
276 }
277
278 /*
279  * Save processor xstate to xsave area.
280  *
281  * Uses either XSAVE or XSAVEOPT or XSAVES depending on the CPU features
282  * and command line options. The choice is permanent until the next reboot.
283  */
284 static inline void os_xsave(struct xregs_state *xstate)
285 {
286         u64 mask = xfeatures_mask_all;
287         u32 lmask = mask;
288         u32 hmask = mask >> 32;
289         int err;
290
291         WARN_ON_FPU(!alternatives_patched);
292
293         XSTATE_XSAVE(xstate, lmask, hmask, err);
294
295         /* We should never fault when copying to a kernel buffer: */
296         WARN_ON_FPU(err);
297 }
298
299 /*
300  * Restore processor xstate from xsave area.
301  *
302  * Uses XRSTORS when XSAVES is used, XRSTOR otherwise.
303  */
304 static inline void os_xrstor(struct xregs_state *xstate, u64 mask)
305 {
306         u32 lmask = mask;
307         u32 hmask = mask >> 32;
308
309         XSTATE_XRESTORE(xstate, lmask, hmask);
310 }
311
312 /*
313  * Save xstate to user space xsave area.
314  *
315  * We don't use modified optimization because xrstor/xrstors might track
316  * a different application.
317  *
318  * We don't use compacted format xsave area for
319  * backward compatibility for old applications which don't understand
320  * compacted format of xsave area.
321  */
322 static inline int xsave_to_user_sigframe(struct xregs_state __user *buf)
323 {
324         u64 mask = xfeatures_mask_user();
325         u32 lmask = mask;
326         u32 hmask = mask >> 32;
327         int err;
328
329         /*
330          * Clear the xsave header first, so that reserved fields are
331          * initialized to zero.
332          */
333         err = __clear_user(&buf->header, sizeof(buf->header));
334         if (unlikely(err))
335                 return -EFAULT;
336
337         stac();
338         XSTATE_OP(XSAVE, buf, lmask, hmask, err);
339         clac();
340
341         return err;
342 }
343
344 /*
345  * Restore xstate from user space xsave area.
346  */
347 static inline int xrstor_from_user_sigframe(struct xregs_state __user *buf, u64 mask)
348 {
349         struct xregs_state *xstate = ((__force struct xregs_state *)buf);
350         u32 lmask = mask;
351         u32 hmask = mask >> 32;
352         int err;
353
354         stac();
355         XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
356         clac();
357
358         return err;
359 }
360
361 /*
362  * Restore xstate from kernel space xsave area, return an error code instead of
363  * an exception.
364  */
365 static inline int os_xrstor_safe(struct xregs_state *xstate, u64 mask)
366 {
367         u32 lmask = mask;
368         u32 hmask = mask >> 32;
369         int err;
370
371         if (cpu_feature_enabled(X86_FEATURE_XSAVES))
372                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
373         else
374                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
375
376         return err;
377 }
378
379 static inline void __restore_fpregs_from_fpstate(union fpregs_state *fpstate, u64 mask)
380 {
381         if (use_xsave()) {
382                 os_xrstor(&fpstate->xsave, mask);
383         } else {
384                 if (use_fxsr())
385                         fxrstor(&fpstate->fxsave);
386                 else
387                         frstor(&fpstate->fsave);
388         }
389 }
390
391 static inline void restore_fpregs_from_fpstate(union fpregs_state *fpstate)
392 {
393         /*
394          * AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is
395          * pending. Clear the x87 state here by setting it to fixed values.
396          * "m" is a random variable that should be in L1.
397          */
398         if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
399                 asm volatile(
400                         "fnclex\n\t"
401                         "emms\n\t"
402                         "fildl %P[addr]"        /* set F?P to defined value */
403                         : : [addr] "m" (fpstate));
404         }
405
406         __restore_fpregs_from_fpstate(fpstate, -1);
407 }
408
409 extern int copy_fpstate_to_sigframe(void __user *buf, void __user *fp, int size);
410
411 /*
412  * FPU context switch related helper methods:
413  */
414
415 DECLARE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
416
417 /*
418  * The in-register FPU state for an FPU context on a CPU is assumed to be
419  * valid if the fpu->last_cpu matches the CPU, and the fpu_fpregs_owner_ctx
420  * matches the FPU.
421  *
422  * If the FPU register state is valid, the kernel can skip restoring the
423  * FPU state from memory.
424  *
425  * Any code that clobbers the FPU registers or updates the in-memory
426  * FPU state for a task MUST let the rest of the kernel know that the
427  * FPU registers are no longer valid for this task.
428  *
429  * Either one of these invalidation functions is enough. Invalidate
430  * a resource you control: CPU if using the CPU for something else
431  * (with preemption disabled), FPU for the current task, or a task that
432  * is prevented from running by the current task.
433  */
434 static inline void __cpu_invalidate_fpregs_state(void)
435 {
436         __this_cpu_write(fpu_fpregs_owner_ctx, NULL);
437 }
438
439 static inline void __fpu_invalidate_fpregs_state(struct fpu *fpu)
440 {
441         fpu->last_cpu = -1;
442 }
443
444 static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)
445 {
446         return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;
447 }
448
449 /*
450  * These generally need preemption protection to work,
451  * do try to avoid using these on their own:
452  */
453 static inline void fpregs_deactivate(struct fpu *fpu)
454 {
455         this_cpu_write(fpu_fpregs_owner_ctx, NULL);
456         trace_x86_fpu_regs_deactivated(fpu);
457 }
458
459 static inline void fpregs_activate(struct fpu *fpu)
460 {
461         this_cpu_write(fpu_fpregs_owner_ctx, fpu);
462         trace_x86_fpu_regs_activated(fpu);
463 }
464
465 /*
466  * Internal helper, do not use directly. Use switch_fpu_return() instead.
467  */
468 static inline void __fpregs_load_activate(void)
469 {
470         struct fpu *fpu = &current->thread.fpu;
471         int cpu = smp_processor_id();
472
473         if (WARN_ON_ONCE(current->flags & PF_KTHREAD))
474                 return;
475
476         if (!fpregs_state_valid(fpu, cpu)) {
477                 restore_fpregs_from_fpstate(&fpu->state);
478                 fpregs_activate(fpu);
479                 fpu->last_cpu = cpu;
480         }
481         clear_thread_flag(TIF_NEED_FPU_LOAD);
482 }
483
484 /*
485  * FPU state switching for scheduling.
486  *
487  * This is a two-stage process:
488  *
489  *  - switch_fpu_prepare() saves the old state.
490  *    This is done within the context of the old process.
491  *
492  *  - switch_fpu_finish() sets TIF_NEED_FPU_LOAD; the floating point state
493  *    will get loaded on return to userspace, or when the kernel needs it.
494  *
495  * If TIF_NEED_FPU_LOAD is cleared then the CPU's FPU registers
496  * are saved in the current thread's FPU register state.
497  *
498  * If TIF_NEED_FPU_LOAD is set then CPU's FPU registers may not
499  * hold current()'s FPU registers. It is required to load the
500  * registers before returning to userland or using the content
501  * otherwise.
502  *
503  * The FPU context is only stored/restored for a user task and
504  * PF_KTHREAD is used to distinguish between kernel and user threads.
505  */
506 static inline void switch_fpu_prepare(struct fpu *old_fpu, int cpu)
507 {
508         if (static_cpu_has(X86_FEATURE_FPU) && !(current->flags & PF_KTHREAD)) {
509                 save_fpregs_to_fpstate(old_fpu);
510                 /*
511                  * The save operation preserved register state, so the
512                  * fpu_fpregs_owner_ctx is still @old_fpu. Store the
513                  * current CPU number in @old_fpu, so the next return
514                  * to user space can avoid the FPU register restore
515                  * when is returns on the same CPU and still owns the
516                  * context.
517                  */
518                 old_fpu->last_cpu = cpu;
519
520                 trace_x86_fpu_regs_deactivated(old_fpu);
521         }
522 }
523
524 /*
525  * Misc helper functions:
526  */
527
528 /*
529  * Load PKRU from the FPU context if available. Delay loading of the
530  * complete FPU state until the return to userland.
531  */
532 static inline void switch_fpu_finish(struct fpu *new_fpu)
533 {
534         u32 pkru_val = init_pkru_value;
535         struct pkru_state *pk;
536
537         if (!static_cpu_has(X86_FEATURE_FPU))
538                 return;
539
540         set_thread_flag(TIF_NEED_FPU_LOAD);
541
542         if (!cpu_feature_enabled(X86_FEATURE_OSPKE))
543                 return;
544
545         /*
546          * PKRU state is switched eagerly because it needs to be valid before we
547          * return to userland e.g. for a copy_to_user() operation.
548          */
549         if (!(current->flags & PF_KTHREAD)) {
550                 /*
551                  * If the PKRU bit in xsave.header.xfeatures is not set,
552                  * then the PKRU component was in init state, which means
553                  * XRSTOR will set PKRU to 0. If the bit is not set then
554                  * get_xsave_addr() will return NULL because the PKRU value
555                  * in memory is not valid. This means pkru_val has to be
556                  * set to 0 and not to init_pkru_value.
557                  */
558                 pk = get_xsave_addr(&new_fpu->state.xsave, XFEATURE_PKRU);
559                 pkru_val = pk ? pk->pkru : 0;
560         }
561         __write_pkru(pkru_val);
562 }
563
564 #endif /* _ASM_X86_FPU_INTERNAL_H */