4c669f3b54b4fc7c06fabea95e10d2829ebf2de2
[linux-2.6-microblaze.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__prepare_write(struct fpu *fpu);
30 extern void fpu__save(struct fpu *fpu);
31 extern int  fpu__restore_sig(void __user *buf, int ia32_frame);
32 extern void fpu__drop(struct fpu *fpu);
33 extern int  fpu__copy(struct task_struct *dst, struct task_struct *src);
34 extern void fpu__clear_user_states(struct fpu *fpu);
35 extern void fpu__clear_all(struct fpu *fpu);
36 extern int  fpu__exception_code(struct fpu *fpu, int trap_nr);
37
38 /*
39  * Boot time FPU initialization functions:
40  */
41 extern void fpu__init_cpu(void);
42 extern void fpu__init_system_xstate(void);
43 extern void fpu__init_cpu_xstate(void);
44 extern void fpu__init_system(struct cpuinfo_x86 *c);
45 extern void fpu__init_check_bugs(void);
46 extern void fpu__resume_cpu(void);
47
48 /*
49  * Debugging facility:
50  */
51 #ifdef CONFIG_X86_DEBUG_FPU
52 # define WARN_ON_FPU(x) WARN_ON_ONCE(x)
53 #else
54 # define WARN_ON_FPU(x) ({ (void)(x); 0; })
55 #endif
56
57 /*
58  * FPU related CPU feature flag helper routines:
59  */
60 static __always_inline __pure bool use_xsaveopt(void)
61 {
62         return static_cpu_has(X86_FEATURE_XSAVEOPT);
63 }
64
65 static __always_inline __pure bool use_xsave(void)
66 {
67         return static_cpu_has(X86_FEATURE_XSAVE);
68 }
69
70 static __always_inline __pure bool use_fxsr(void)
71 {
72         return static_cpu_has(X86_FEATURE_FXSR);
73 }
74
75 /*
76  * fpstate handling functions:
77  */
78
79 extern union fpregs_state init_fpstate;
80
81 extern void fpstate_init(union fpregs_state *state);
82 #ifdef CONFIG_MATH_EMULATION
83 extern void fpstate_init_soft(struct swregs_state *soft);
84 #else
85 static inline void fpstate_init_soft(struct swregs_state *soft) {}
86 #endif
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 copy_fregs_to_user(struct fregs_state __user *fx)
129 {
130         return user_insn(fnsave %[fx]; fwait,  [fx] "=m" (*fx), "m" (*fx));
131 }
132
133 static inline int copy_fxregs_to_user(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 copy_kernel_to_fxregs(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 copy_kernel_to_fxregs_err(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 copy_user_to_fxregs(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 copy_kernel_to_fregs(struct fregs_state *fx)
167 {
168         kernel_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
169 }
170
171 static inline int copy_kernel_to_fregs_err(struct fregs_state *fx)
172 {
173         return kernel_insn_err(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
174 }
175
176 static inline int copy_user_to_fregs(struct fregs_state __user *fx)
177 {
178         return user_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
179 }
180
181 static inline void copy_fxregs_to_kernel(struct fpu *fpu)
182 {
183         if (IS_ENABLED(CONFIG_X86_32))
184                 asm volatile( "fxsave %[fx]" : [fx] "=m" (fpu->state.fxsave));
185         else
186                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (fpu->state.fxsave));
187 }
188
189 static inline void fxsave(struct fxregs_state *fx)
190 {
191         if (IS_ENABLED(CONFIG_X86_32))
192                 asm volatile( "fxsave %[fx]" : [fx] "=m" (*fx));
193         else
194                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (*fx));
195 }
196
197 /* These macros all use (%edi)/(%rdi) as the single memory argument. */
198 #define XSAVE           ".byte " REX_PREFIX "0x0f,0xae,0x27"
199 #define XSAVEOPT        ".byte " REX_PREFIX "0x0f,0xae,0x37"
200 #define XSAVES          ".byte " REX_PREFIX "0x0f,0xc7,0x2f"
201 #define XRSTOR          ".byte " REX_PREFIX "0x0f,0xae,0x2f"
202 #define XRSTORS         ".byte " REX_PREFIX "0x0f,0xc7,0x1f"
203
204 #define XSTATE_OP(op, st, lmask, hmask, err)                            \
205         asm volatile("1:" op "\n\t"                                     \
206                      "xor %[err], %[err]\n"                             \
207                      "2:\n\t"                                           \
208                      ".pushsection .fixup,\"ax\"\n\t"                   \
209                      "3: movl $-2,%[err]\n\t"                           \
210                      "jmp 2b\n\t"                                       \
211                      ".popsection\n\t"                                  \
212                      _ASM_EXTABLE(1b, 3b)                               \
213                      : [err] "=r" (err)                                 \
214                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
215                      : "memory")
216
217 /*
218  * If XSAVES is enabled, it replaces XSAVEOPT because it supports a compact
219  * format and supervisor states in addition to modified optimization in
220  * XSAVEOPT.
221  *
222  * Otherwise, if XSAVEOPT is enabled, XSAVEOPT replaces XSAVE because XSAVEOPT
223  * supports modified optimization which is not supported by XSAVE.
224  *
225  * We use XSAVE as a fallback.
226  *
227  * The 661 label is defined in the ALTERNATIVE* macros as the address of the
228  * original instruction which gets replaced. We need to use it here as the
229  * address of the instruction where we might get an exception at.
230  */
231 #define XSTATE_XSAVE(st, lmask, hmask, err)                             \
232         asm volatile(ALTERNATIVE_2(XSAVE,                               \
233                                    XSAVEOPT, X86_FEATURE_XSAVEOPT,      \
234                                    XSAVES,   X86_FEATURE_XSAVES)        \
235                      "\n"                                               \
236                      "xor %[err], %[err]\n"                             \
237                      "3:\n"                                             \
238                      ".pushsection .fixup,\"ax\"\n"                     \
239                      "4: movl $-2, %[err]\n"                            \
240                      "jmp 3b\n"                                         \
241                      ".popsection\n"                                    \
242                      _ASM_EXTABLE(661b, 4b)                             \
243                      : [err] "=r" (err)                                 \
244                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
245                      : "memory")
246
247 /*
248  * Use XRSTORS to restore context if it is enabled. XRSTORS supports compact
249  * XSAVE area format.
250  */
251 #define XSTATE_XRESTORE(st, lmask, hmask)                               \
252         asm volatile(ALTERNATIVE(XRSTOR,                                \
253                                  XRSTORS, X86_FEATURE_XSAVES)           \
254                      "\n"                                               \
255                      "3:\n"                                             \
256                      _ASM_EXTABLE_HANDLE(661b, 3b, ex_handler_fprestore)\
257                      :                                                  \
258                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
259                      : "memory")
260
261 /*
262  * This function is called only during boot time when x86 caps are not set
263  * up and alternative can not be used yet.
264  */
265 static inline void copy_kernel_to_xregs_booting(struct xregs_state *xstate)
266 {
267         u64 mask = -1;
268         u32 lmask = mask;
269         u32 hmask = mask >> 32;
270         int err;
271
272         WARN_ON(system_state != SYSTEM_BOOTING);
273
274         if (boot_cpu_has(X86_FEATURE_XSAVES))
275                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
276         else
277                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
278
279         /*
280          * We should never fault when copying from a kernel buffer, and the FPU
281          * state we set at boot time should be valid.
282          */
283         WARN_ON_FPU(err);
284 }
285
286 /*
287  * Save processor xstate to xsave area.
288  */
289 static inline void copy_xregs_to_kernel(struct xregs_state *xstate)
290 {
291         u64 mask = xfeatures_mask_all;
292         u32 lmask = mask;
293         u32 hmask = mask >> 32;
294         int err;
295
296         WARN_ON_FPU(!alternatives_patched);
297
298         XSTATE_XSAVE(xstate, lmask, hmask, err);
299
300         /* We should never fault when copying to a kernel buffer: */
301         WARN_ON_FPU(err);
302 }
303
304 /*
305  * Restore processor xstate from xsave area.
306  */
307 static inline void copy_kernel_to_xregs(struct xregs_state *xstate, u64 mask)
308 {
309         u32 lmask = mask;
310         u32 hmask = mask >> 32;
311
312         XSTATE_XRESTORE(xstate, lmask, hmask);
313 }
314
315 /*
316  * Save xstate to user space xsave area.
317  *
318  * We don't use modified optimization because xrstor/xrstors might track
319  * a different application.
320  *
321  * We don't use compacted format xsave area for
322  * backward compatibility for old applications which don't understand
323  * compacted format of xsave area.
324  */
325 static inline int copy_xregs_to_user(struct xregs_state __user *buf)
326 {
327         u64 mask = xfeatures_mask_user();
328         u32 lmask = mask;
329         u32 hmask = mask >> 32;
330         int err;
331
332         /*
333          * Clear the xsave header first, so that reserved fields are
334          * initialized to zero.
335          */
336         err = __clear_user(&buf->header, sizeof(buf->header));
337         if (unlikely(err))
338                 return -EFAULT;
339
340         stac();
341         XSTATE_OP(XSAVE, buf, lmask, hmask, err);
342         clac();
343
344         return err;
345 }
346
347 /*
348  * Restore xstate from user space xsave area.
349  */
350 static inline int copy_user_to_xregs(struct xregs_state __user *buf, u64 mask)
351 {
352         struct xregs_state *xstate = ((__force struct xregs_state *)buf);
353         u32 lmask = mask;
354         u32 hmask = mask >> 32;
355         int err;
356
357         stac();
358         XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
359         clac();
360
361         return err;
362 }
363
364 /*
365  * Restore xstate from kernel space xsave area, return an error code instead of
366  * an exception.
367  */
368 static inline int copy_kernel_to_xregs_err(struct xregs_state *xstate, u64 mask)
369 {
370         u32 lmask = mask;
371         u32 hmask = mask >> 32;
372         int err;
373
374         if (static_cpu_has(X86_FEATURE_XSAVES))
375                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
376         else
377                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
378
379         return err;
380 }
381
382 extern int copy_fpregs_to_fpstate(struct fpu *fpu);
383
384 static inline void __copy_kernel_to_fpregs(union fpregs_state *fpstate, u64 mask)
385 {
386         if (use_xsave()) {
387                 copy_kernel_to_xregs(&fpstate->xsave, mask);
388         } else {
389                 if (use_fxsr())
390                         copy_kernel_to_fxregs(&fpstate->fxsave);
391                 else
392                         copy_kernel_to_fregs(&fpstate->fsave);
393         }
394 }
395
396 static inline void copy_kernel_to_fpregs(union fpregs_state *fpstate)
397 {
398         /*
399          * AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is
400          * pending. Clear the x87 state here by setting it to fixed values.
401          * "m" is a random variable that should be in L1.
402          */
403         if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
404                 asm volatile(
405                         "fnclex\n\t"
406                         "emms\n\t"
407                         "fildl %P[addr]"        /* set F?P to defined value */
408                         : : [addr] "m" (fpstate));
409         }
410
411         __copy_kernel_to_fpregs(fpstate, -1);
412 }
413
414 extern int copy_fpstate_to_sigframe(void __user *buf, void __user *fp, int size);
415
416 /*
417  * FPU context switch related helper methods:
418  */
419
420 DECLARE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
421
422 /*
423  * The in-register FPU state for an FPU context on a CPU is assumed to be
424  * valid if the fpu->last_cpu matches the CPU, and the fpu_fpregs_owner_ctx
425  * matches the FPU.
426  *
427  * If the FPU register state is valid, the kernel can skip restoring the
428  * FPU state from memory.
429  *
430  * Any code that clobbers the FPU registers or updates the in-memory
431  * FPU state for a task MUST let the rest of the kernel know that the
432  * FPU registers are no longer valid for this task.
433  *
434  * Either one of these invalidation functions is enough. Invalidate
435  * a resource you control: CPU if using the CPU for something else
436  * (with preemption disabled), FPU for the current task, or a task that
437  * is prevented from running by the current task.
438  */
439 static inline void __cpu_invalidate_fpregs_state(void)
440 {
441         __this_cpu_write(fpu_fpregs_owner_ctx, NULL);
442 }
443
444 static inline void __fpu_invalidate_fpregs_state(struct fpu *fpu)
445 {
446         fpu->last_cpu = -1;
447 }
448
449 static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)
450 {
451         return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;
452 }
453
454 /*
455  * These generally need preemption protection to work,
456  * do try to avoid using these on their own:
457  */
458 static inline void fpregs_deactivate(struct fpu *fpu)
459 {
460         this_cpu_write(fpu_fpregs_owner_ctx, NULL);
461         trace_x86_fpu_regs_deactivated(fpu);
462 }
463
464 static inline void fpregs_activate(struct fpu *fpu)
465 {
466         this_cpu_write(fpu_fpregs_owner_ctx, fpu);
467         trace_x86_fpu_regs_activated(fpu);
468 }
469
470 /*
471  * Internal helper, do not use directly. Use switch_fpu_return() instead.
472  */
473 static inline void __fpregs_load_activate(void)
474 {
475         struct fpu *fpu = &current->thread.fpu;
476         int cpu = smp_processor_id();
477
478         if (WARN_ON_ONCE(current->flags & PF_KTHREAD))
479                 return;
480
481         if (!fpregs_state_valid(fpu, cpu)) {
482                 copy_kernel_to_fpregs(&fpu->state);
483                 fpregs_activate(fpu);
484                 fpu->last_cpu = cpu;
485         }
486         clear_thread_flag(TIF_NEED_FPU_LOAD);
487 }
488
489 /*
490  * FPU state switching for scheduling.
491  *
492  * This is a two-stage process:
493  *
494  *  - switch_fpu_prepare() saves the old state.
495  *    This is done within the context of the old process.
496  *
497  *  - switch_fpu_finish() sets TIF_NEED_FPU_LOAD; the floating point state
498  *    will get loaded on return to userspace, or when the kernel needs it.
499  *
500  * If TIF_NEED_FPU_LOAD is cleared then the CPU's FPU registers
501  * are saved in the current thread's FPU register state.
502  *
503  * If TIF_NEED_FPU_LOAD is set then CPU's FPU registers may not
504  * hold current()'s FPU registers. It is required to load the
505  * registers before returning to userland or using the content
506  * otherwise.
507  *
508  * The FPU context is only stored/restored for a user task and
509  * PF_KTHREAD is used to distinguish between kernel and user threads.
510  */
511 static inline void switch_fpu_prepare(struct fpu *old_fpu, int cpu)
512 {
513         if (static_cpu_has(X86_FEATURE_FPU) && !(current->flags & PF_KTHREAD)) {
514                 if (!copy_fpregs_to_fpstate(old_fpu))
515                         old_fpu->last_cpu = -1;
516                 else
517                         old_fpu->last_cpu = cpu;
518
519                 /* But leave fpu_fpregs_owner_ctx! */
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 */