GNU Linux-libre 4.4.284-gnu1
[releases.git] / arch / x86 / include / asm / fpu / internal.h
1 /*
2  * Copyright (C) 1994 Linus Torvalds
3  *
4  * Pentium III FXSR, SSE support
5  * General FPU state handling cleanups
6  *      Gareth Hughes <gareth@valinux.com>, May 2000
7  * x86-64 work by Andi Kleen 2002
8  */
9
10 #ifndef _ASM_X86_FPU_INTERNAL_H
11 #define _ASM_X86_FPU_INTERNAL_H
12
13 #include <linux/compat.h>
14 #include <linux/sched.h>
15 #include <linux/slab.h>
16
17 #include <asm/user.h>
18 #include <asm/fpu/api.h>
19 #include <asm/fpu/xstate.h>
20 #include <asm/cpufeature.h>
21
22 /*
23  * High level FPU state handling functions:
24  */
25 extern void fpu__activate_curr(struct fpu *fpu);
26 extern void fpu__activate_fpstate_read(struct fpu *fpu);
27 extern void fpu__activate_fpstate_write(struct fpu *fpu);
28 extern void fpu__save(struct fpu *fpu);
29 extern void fpu__restore(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 fpu *dst_fpu, struct fpu *src_fpu);
33 extern void fpu__clear(struct fpu *fpu);
34 extern int  fpu__exception_code(struct fpu *fpu, int trap_nr);
35 extern int  dump_fpu(struct pt_regs *ptregs, struct user_i387_struct *fpstate);
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 extern u64 fpu__get_supported_xfeatures_mask(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 static inline void fpstate_init_fxstate(struct fxregs_state *fx)
88 {
89         fx->cwd = 0x37f;
90         fx->mxcsr = MXCSR_DEFAULT;
91 }
92 extern void fpstate_sanitize_xstate(struct fpu *fpu);
93
94 #define user_insn(insn, output, input...)                               \
95 ({                                                                      \
96         int err;                                                        \
97                                                                         \
98         might_fault();                                                  \
99                                                                         \
100         asm volatile(ASM_STAC "\n"                                      \
101                      "1:" #insn "\n\t"                                  \
102                      "2: " ASM_CLAC "\n"                                \
103                      ".section .fixup,\"ax\"\n"                         \
104                      "3:  movl $-1,%[err]\n"                            \
105                      "    jmp  2b\n"                                    \
106                      ".previous\n"                                      \
107                      _ASM_EXTABLE(1b, 3b)                               \
108                      : [err] "=r" (err), output                         \
109                      : "0"(0), input);                                  \
110         err;                                                            \
111 })
112
113 #define check_insn(insn, output, input...)                              \
114 ({                                                                      \
115         int err;                                                        \
116         asm volatile("1:" #insn "\n\t"                                  \
117                      "2:\n"                                             \
118                      ".section .fixup,\"ax\"\n"                         \
119                      "3:  movl $-1,%[err]\n"                            \
120                      "    jmp  2b\n"                                    \
121                      ".previous\n"                                      \
122                      _ASM_EXTABLE(1b, 3b)                               \
123                      : [err] "=r" (err), output                         \
124                      : "0"(0), input);                                  \
125         err;                                                            \
126 })
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 (config_enabled(CONFIG_X86_32))
136                 return user_insn(fxsave %[fx], [fx] "=m" (*fx), "m" (*fx));
137         else if (config_enabled(CONFIG_AS_FXSAVEQ))
138                 return user_insn(fxsaveq %[fx], [fx] "=m" (*fx), "m" (*fx));
139
140         /* See comment in copy_fxregs_to_kernel() below. */
141         return user_insn(rex64/fxsave (%[fx]), "=m" (*fx), [fx] "R" (fx));
142 }
143
144 static inline void copy_kernel_to_fxregs(struct fxregs_state *fx)
145 {
146         int err;
147
148         if (config_enabled(CONFIG_X86_32)) {
149                 err = check_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
150         } else {
151                 if (config_enabled(CONFIG_AS_FXSAVEQ)) {
152                         err = check_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
153                 } else {
154                         /* See comment in copy_fxregs_to_kernel() below. */
155                         err = check_insn(rex64/fxrstor (%[fx]), "=m" (*fx), [fx] "R" (fx), "m" (*fx));
156                 }
157         }
158         /* Copying from a kernel buffer to FPU registers should never fail: */
159         WARN_ON_FPU(err);
160 }
161
162 static inline int copy_user_to_fxregs(struct fxregs_state __user *fx)
163 {
164         if (config_enabled(CONFIG_X86_32))
165                 return user_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
166         else if (config_enabled(CONFIG_AS_FXSAVEQ))
167                 return user_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
168
169         /* See comment in copy_fxregs_to_kernel() below. */
170         return user_insn(rex64/fxrstor (%[fx]), "=m" (*fx), [fx] "R" (fx),
171                           "m" (*fx));
172 }
173
174 static inline void copy_kernel_to_fregs(struct fregs_state *fx)
175 {
176         int err = check_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
177
178         WARN_ON_FPU(err);
179 }
180
181 static inline int copy_user_to_fregs(struct fregs_state __user *fx)
182 {
183         return user_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
184 }
185
186 static inline void copy_fxregs_to_kernel(struct fpu *fpu)
187 {
188         if (config_enabled(CONFIG_X86_32))
189                 asm volatile( "fxsave %[fx]" : [fx] "=m" (fpu->state.fxsave));
190         else if (config_enabled(CONFIG_AS_FXSAVEQ))
191                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (fpu->state.fxsave));
192         else {
193                 /* Using "rex64; fxsave %0" is broken because, if the memory
194                  * operand uses any extended registers for addressing, a second
195                  * REX prefix will be generated (to the assembler, rex64
196                  * followed by semicolon is a separate instruction), and hence
197                  * the 64-bitness is lost.
198                  *
199                  * Using "fxsaveq %0" would be the ideal choice, but is only
200                  * supported starting with gas 2.16.
201                  *
202                  * Using, as a workaround, the properly prefixed form below
203                  * isn't accepted by any binutils version so far released,
204                  * complaining that the same type of prefix is used twice if
205                  * an extended register is needed for addressing (fix submitted
206                  * to mainline 2005-11-21).
207                  *
208                  *  asm volatile("rex64/fxsave %0" : "=m" (fpu->state.fxsave));
209                  *
210                  * This, however, we can work around by forcing the compiler to
211                  * select an addressing mode that doesn't require extended
212                  * registers.
213                  */
214                 asm volatile( "rex64/fxsave (%[fx])"
215                              : "=m" (fpu->state.fxsave)
216                              : [fx] "R" (&fpu->state.fxsave));
217         }
218 }
219
220 static inline void fxsave(struct fxregs_state *fx)
221 {
222         if (IS_ENABLED(CONFIG_X86_32))
223                 asm volatile( "fxsave %[fx]" : [fx] "=m" (*fx));
224         else
225                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (*fx));
226 }
227
228 /* These macros all use (%edi)/(%rdi) as the single memory argument. */
229 #define XSAVE           ".byte " REX_PREFIX "0x0f,0xae,0x27"
230 #define XSAVEOPT        ".byte " REX_PREFIX "0x0f,0xae,0x37"
231 #define XSAVES          ".byte " REX_PREFIX "0x0f,0xc7,0x2f"
232 #define XRSTOR          ".byte " REX_PREFIX "0x0f,0xae,0x2f"
233 #define XRSTORS         ".byte " REX_PREFIX "0x0f,0xc7,0x1f"
234
235 #define XSTATE_OP(op, st, lmask, hmask, err)                            \
236         asm volatile("1:" op "\n\t"                                     \
237                      "xor %[err], %[err]\n"                             \
238                      "2:\n\t"                                           \
239                      ".pushsection .fixup,\"ax\"\n\t"                   \
240                      "3: movl $-2,%[err]\n\t"                           \
241                      "jmp 2b\n\t"                                       \
242                      ".popsection\n\t"                                  \
243                      _ASM_EXTABLE(1b, 3b)                               \
244                      : [err] "=r" (err)                                 \
245                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
246                      : "memory")
247
248 /*
249  * If XSAVES is enabled, it replaces XSAVEOPT because it supports a compact
250  * format and supervisor states in addition to modified optimization in
251  * XSAVEOPT.
252  *
253  * Otherwise, if XSAVEOPT is enabled, XSAVEOPT replaces XSAVE because XSAVEOPT
254  * supports modified optimization which is not supported by XSAVE.
255  *
256  * We use XSAVE as a fallback.
257  *
258  * The 661 label is defined in the ALTERNATIVE* macros as the address of the
259  * original instruction which gets replaced. We need to use it here as the
260  * address of the instruction where we might get an exception at.
261  */
262 #define XSTATE_XSAVE(st, lmask, hmask, err)                             \
263         asm volatile(ALTERNATIVE_2(XSAVE,                               \
264                                    XSAVEOPT, X86_FEATURE_XSAVEOPT,      \
265                                    XSAVES,   X86_FEATURE_XSAVES)        \
266                      "\n"                                               \
267                      "xor %[err], %[err]\n"                             \
268                      "3:\n"                                             \
269                      ".pushsection .fixup,\"ax\"\n"                     \
270                      "4: movl $-2, %[err]\n"                            \
271                      "jmp 3b\n"                                         \
272                      ".popsection\n"                                    \
273                      _ASM_EXTABLE(661b, 4b)                             \
274                      : [err] "=r" (err)                                 \
275                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
276                      : "memory")
277
278 /*
279  * Use XRSTORS to restore context if it is enabled. XRSTORS supports compact
280  * XSAVE area format.
281  */
282 #define XSTATE_XRESTORE(st, lmask, hmask, err)                          \
283         asm volatile(ALTERNATIVE(XRSTOR,                                \
284                                  XRSTORS, X86_FEATURE_XSAVES)           \
285                      "\n"                                               \
286                      "xor %[err], %[err]\n"                             \
287                      "3:\n"                                             \
288                      ".pushsection .fixup,\"ax\"\n"                     \
289                      "4: movl $-2, %[err]\n"                            \
290                      "jmp 3b\n"                                         \
291                      ".popsection\n"                                    \
292                      _ASM_EXTABLE(661b, 4b)                             \
293                      : [err] "=r" (err)                                 \
294                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
295                      : "memory")
296
297 /*
298  * This function is called only during boot time when x86 caps are not set
299  * up and alternative can not be used yet.
300  */
301 static inline void copy_kernel_to_xregs_booting(struct xregs_state *xstate)
302 {
303         u64 mask = -1;
304         u32 lmask = mask;
305         u32 hmask = mask >> 32;
306         int err;
307
308         WARN_ON(system_state != SYSTEM_BOOTING);
309
310         if (static_cpu_has(X86_FEATURE_XSAVES))
311                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
312         else
313                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
314
315         /* We should never fault when copying from a kernel buffer: */
316         WARN_ON_FPU(err);
317 }
318
319 /*
320  * Save processor xstate to xsave area.
321  */
322 static inline void copy_xregs_to_kernel(struct xregs_state *xstate)
323 {
324         u64 mask = -1;
325         u32 lmask = mask;
326         u32 hmask = mask >> 32;
327         int err;
328
329         WARN_ON(!alternatives_patched);
330
331         XSTATE_XSAVE(xstate, lmask, hmask, err);
332
333         /* We should never fault when copying to a kernel buffer: */
334         WARN_ON_FPU(err);
335 }
336
337 /*
338  * Restore processor xstate from xsave area.
339  */
340 static inline void copy_kernel_to_xregs(struct xregs_state *xstate, u64 mask)
341 {
342         u32 lmask = mask;
343         u32 hmask = mask >> 32;
344         int err;
345
346         XSTATE_XRESTORE(xstate, lmask, hmask, err);
347
348         /* We should never fault when copying from a kernel buffer: */
349         WARN_ON_FPU(err);
350 }
351
352 /*
353  * Save xstate to user space xsave area.
354  *
355  * We don't use modified optimization because xrstor/xrstors might track
356  * a different application.
357  *
358  * We don't use compacted format xsave area for
359  * backward compatibility for old applications which don't understand
360  * compacted format of xsave area.
361  */
362 static inline int copy_xregs_to_user(struct xregs_state __user *buf)
363 {
364         int err;
365
366         /*
367          * Clear the xsave header first, so that reserved fields are
368          * initialized to zero.
369          */
370         err = __clear_user(&buf->header, sizeof(buf->header));
371         if (unlikely(err))
372                 return -EFAULT;
373
374         stac();
375         XSTATE_OP(XSAVE, buf, -1, -1, err);
376         clac();
377
378         return err;
379 }
380
381 /*
382  * Restore xstate from user space xsave area.
383  */
384 static inline int copy_user_to_xregs(struct xregs_state __user *buf, u64 mask)
385 {
386         struct xregs_state *xstate = ((__force struct xregs_state *)buf);
387         u32 lmask = mask;
388         u32 hmask = mask >> 32;
389         int err;
390
391         stac();
392         XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
393         clac();
394
395         return err;
396 }
397
398 /*
399  * These must be called with preempt disabled. Returns
400  * 'true' if the FPU state is still intact and we can
401  * keep registers active.
402  *
403  * The legacy FNSAVE instruction cleared all FPU state
404  * unconditionally, so registers are essentially destroyed.
405  * Modern FPU state can be kept in registers, if there are
406  * no pending FP exceptions.
407  */
408 static inline int copy_fpregs_to_fpstate(struct fpu *fpu)
409 {
410         if (likely(use_xsave())) {
411                 copy_xregs_to_kernel(&fpu->state.xsave);
412                 return 1;
413         }
414
415         if (likely(use_fxsr())) {
416                 copy_fxregs_to_kernel(fpu);
417                 return 1;
418         }
419
420         /*
421          * Legacy FPU register saving, FNSAVE always clears FPU registers,
422          * so we have to mark them inactive:
423          */
424         asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->state.fsave));
425
426         return 0;
427 }
428
429 static inline void __copy_kernel_to_fpregs(union fpregs_state *fpstate)
430 {
431         if (use_xsave()) {
432                 copy_kernel_to_xregs(&fpstate->xsave, -1);
433         } else {
434                 if (use_fxsr())
435                         copy_kernel_to_fxregs(&fpstate->fxsave);
436                 else
437                         copy_kernel_to_fregs(&fpstate->fsave);
438         }
439 }
440
441 static inline void copy_kernel_to_fpregs(union fpregs_state *fpstate)
442 {
443         /*
444          * AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is
445          * pending. Clear the x87 state here by setting it to fixed values.
446          * "m" is a random variable that should be in L1.
447          */
448         if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
449                 asm volatile(
450                         "fnclex\n\t"
451                         "emms\n\t"
452                         "fildl %P[addr]"        /* set F?P to defined value */
453                         : : [addr] "m" (fpstate));
454         }
455
456         __copy_kernel_to_fpregs(fpstate);
457 }
458
459 extern int copy_fpstate_to_sigframe(void __user *buf, void __user *fp, int size);
460
461 /*
462  * FPU context switch related helper methods:
463  */
464
465 DECLARE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
466
467 /*
468  * Must be run with preemption disabled: this clears the fpu_fpregs_owner_ctx,
469  * on this CPU.
470  *
471  * This will disable any lazy FPU state restore of the current FPU state,
472  * but if the current thread owns the FPU, it will still be saved by.
473  */
474 static inline void __cpu_disable_lazy_restore(unsigned int cpu)
475 {
476         per_cpu(fpu_fpregs_owner_ctx, cpu) = NULL;
477 }
478
479 static inline int fpu_want_lazy_restore(struct fpu *fpu, unsigned int cpu)
480 {
481         return fpu == this_cpu_read_stable(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;
482 }
483
484
485 static inline void __fpregs_deactivate(struct fpu *fpu)
486 {
487         WARN_ON_FPU(!fpu->fpregs_active);
488
489         fpu->fpregs_active = 0;
490         this_cpu_write(fpu_fpregs_owner_ctx, NULL);
491 }
492
493 static inline void __fpregs_activate(struct fpu *fpu)
494 {
495         WARN_ON_FPU(fpu->fpregs_active);
496
497         fpu->fpregs_active = 1;
498         this_cpu_write(fpu_fpregs_owner_ctx, fpu);
499 }
500
501 /*
502  * The question "does this thread have fpu access?"
503  * is slightly racy, since preemption could come in
504  * and revoke it immediately after the test.
505  *
506  * However, even in that very unlikely scenario,
507  * we can just assume we have FPU access - typically
508  * to save the FP state - we'll just take a #NM
509  * fault and get the FPU access back.
510  */
511 static inline int fpregs_active(void)
512 {
513         return current->thread.fpu.fpregs_active;
514 }
515
516 /*
517  * These generally need preemption protection to work,
518  * do try to avoid using these on their own.
519  */
520 static inline void fpregs_activate(struct fpu *fpu)
521 {
522         __fpregs_activate(fpu);
523 }
524
525 static inline void fpregs_deactivate(struct fpu *fpu)
526 {
527         __fpregs_deactivate(fpu);
528 }
529
530 /*
531  * FPU state switching for scheduling.
532  *
533  * This is a two-stage process:
534  *
535  *  - switch_fpu_prepare() saves the old state and
536  *    sets the new state of the CR0.TS bit. This is
537  *    done within the context of the old process.
538  *
539  *  - switch_fpu_finish() restores the new state as
540  *    necessary.
541  */
542 typedef struct { int preload; } fpu_switch_t;
543
544 static inline fpu_switch_t
545 switch_fpu_prepare(struct fpu *old_fpu, struct fpu *new_fpu, int cpu)
546 {
547         fpu_switch_t fpu;
548
549         /*
550          * If the task has used the math, pre-load the FPU on xsave processors
551          * or if the past 5 consecutive context-switches used math.
552          */
553         fpu.preload = static_cpu_has(X86_FEATURE_FPU) &&
554                       new_fpu->fpstate_active;
555
556         if (old_fpu->fpregs_active) {
557                 if (!copy_fpregs_to_fpstate(old_fpu))
558                         old_fpu->last_cpu = -1;
559                 else
560                         old_fpu->last_cpu = cpu;
561
562                 /* But leave fpu_fpregs_owner_ctx! */
563                 old_fpu->fpregs_active = 0;
564
565                 /* Don't change CR0.TS if we just switch! */
566                 if (fpu.preload) {
567                         __fpregs_activate(new_fpu);
568                         prefetch(&new_fpu->state);
569                 }
570         } else {
571                 old_fpu->last_cpu = -1;
572                 if (fpu.preload) {
573                         if (fpu_want_lazy_restore(new_fpu, cpu))
574                                 fpu.preload = 0;
575                         else
576                                 prefetch(&new_fpu->state);
577                         fpregs_activate(new_fpu);
578                 }
579         }
580         return fpu;
581 }
582
583 /*
584  * Misc helper functions:
585  */
586
587 /*
588  * By the time this gets called, we've already cleared CR0.TS and
589  * given the process the FPU if we are going to preload the FPU
590  * state - all we need to do is to conditionally restore the register
591  * state itself.
592  */
593 static inline void switch_fpu_finish(struct fpu *new_fpu, fpu_switch_t fpu_switch)
594 {
595         if (fpu_switch.preload)
596                 copy_kernel_to_fpregs(&new_fpu->state);
597 }
598
599 /*
600  * Needs to be preemption-safe.
601  *
602  * NOTE! user_fpu_begin() must be used only immediately before restoring
603  * the save state. It does not do any saving/restoring on its own. In
604  * lazy FPU mode, it is just an optimization to avoid a #NM exception,
605  * the task can lose the FPU right after preempt_enable().
606  */
607 static inline void user_fpu_begin(void)
608 {
609         struct fpu *fpu = &current->thread.fpu;
610
611         preempt_disable();
612         if (!fpregs_active())
613                 fpregs_activate(fpu);
614         preempt_enable();
615 }
616
617 /*
618  * MXCSR and XCR definitions:
619  */
620
621 extern unsigned int mxcsr_feature_mask;
622
623 #define XCR_XFEATURE_ENABLED_MASK       0x00000000
624
625 static inline u64 xgetbv(u32 index)
626 {
627         u32 eax, edx;
628
629         asm volatile(".byte 0x0f,0x01,0xd0" /* xgetbv */
630                      : "=a" (eax), "=d" (edx)
631                      : "c" (index));
632         return eax + ((u64)edx << 32);
633 }
634
635 static inline void xsetbv(u32 index, u64 value)
636 {
637         u32 eax = value;
638         u32 edx = value >> 32;
639
640         asm volatile(".byte 0x0f,0x01,0xd1" /* xsetbv */
641                      : : "a" (eax), "d" (edx), "c" (index));
642 }
643
644 #endif /* _ASM_X86_FPU_INTERNAL_H */