x86/fpu: Restore from kernel memory on the 64-bit path too
[linux-2.6-block.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/cpufeature.h>
23 #include <asm/trace/fpu.h>
24
25 /*
26  * High level FPU state handling functions:
27  */
28 extern void fpu__prepare_read(struct fpu *fpu);
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 fpu *dst_fpu, struct fpu *src_fpu);
34 extern void fpu__clear(struct fpu *fpu);
35 extern int  fpu__exception_code(struct fpu *fpu, int trap_nr);
36 extern int  dump_fpu(struct pt_regs *ptregs, struct user_i387_struct *fpstate);
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 extern u64 fpu__get_supported_xfeatures_mask(void);
48
49 /*
50  * Debugging facility:
51  */
52 #ifdef CONFIG_X86_DEBUG_FPU
53 # define WARN_ON_FPU(x) WARN_ON_ONCE(x)
54 #else
55 # define WARN_ON_FPU(x) ({ (void)(x); 0; })
56 #endif
57
58 /*
59  * FPU related CPU feature flag helper routines:
60  */
61 static __always_inline __pure bool use_xsaveopt(void)
62 {
63         return static_cpu_has(X86_FEATURE_XSAVEOPT);
64 }
65
66 static __always_inline __pure bool use_xsave(void)
67 {
68         return static_cpu_has(X86_FEATURE_XSAVE);
69 }
70
71 static __always_inline __pure bool use_fxsr(void)
72 {
73         return static_cpu_has(X86_FEATURE_FXSR);
74 }
75
76 /*
77  * fpstate handling functions:
78  */
79
80 extern union fpregs_state init_fpstate;
81
82 extern void fpstate_init(union fpregs_state *state);
83 #ifdef CONFIG_MATH_EMULATION
84 extern void fpstate_init_soft(struct swregs_state *soft);
85 #else
86 static inline void fpstate_init_soft(struct swregs_state *soft) {}
87 #endif
88
89 static inline void fpstate_init_xstate(struct xregs_state *xsave)
90 {
91         /*
92          * XRSTORS requires these bits set in xcomp_bv, or it will
93          * trigger #GP:
94          */
95         xsave->header.xcomp_bv = XCOMP_BV_COMPACTED_FORMAT | xfeatures_mask;
96 }
97
98 static inline void fpstate_init_fxstate(struct fxregs_state *fx)
99 {
100         fx->cwd = 0x37f;
101         fx->mxcsr = MXCSR_DEFAULT;
102 }
103 extern void fpstate_sanitize_xstate(struct fpu *fpu);
104
105 #define user_insn(insn, output, input...)                               \
106 ({                                                                      \
107         int err;                                                        \
108                                                                         \
109         might_fault();                                                  \
110                                                                         \
111         asm volatile(ASM_STAC "\n"                                      \
112                      "1:" #insn "\n\t"                                  \
113                      "2: " ASM_CLAC "\n"                                \
114                      ".section .fixup,\"ax\"\n"                         \
115                      "3:  movl $-1,%[err]\n"                            \
116                      "    jmp  2b\n"                                    \
117                      ".previous\n"                                      \
118                      _ASM_EXTABLE(1b, 3b)                               \
119                      : [err] "=r" (err), output                         \
120                      : "0"(0), input);                                  \
121         err;                                                            \
122 })
123
124 #define kernel_insn_err(insn, output, input...)                         \
125 ({                                                                      \
126         int err;                                                        \
127         asm volatile("1:" #insn "\n\t"                                  \
128                      "2:\n"                                             \
129                      ".section .fixup,\"ax\"\n"                         \
130                      "3:  movl $-1,%[err]\n"                            \
131                      "    jmp  2b\n"                                    \
132                      ".previous\n"                                      \
133                      _ASM_EXTABLE(1b, 3b)                               \
134                      : [err] "=r" (err), output                         \
135                      : "0"(0), input);                                  \
136         err;                                                            \
137 })
138
139 #define kernel_insn(insn, output, input...)                             \
140         asm volatile("1:" #insn "\n\t"                                  \
141                      "2:\n"                                             \
142                      _ASM_EXTABLE_HANDLE(1b, 2b, ex_handler_fprestore)  \
143                      : output : input)
144
145 static inline int copy_fregs_to_user(struct fregs_state __user *fx)
146 {
147         return user_insn(fnsave %[fx]; fwait,  [fx] "=m" (*fx), "m" (*fx));
148 }
149
150 static inline int copy_fxregs_to_user(struct fxregs_state __user *fx)
151 {
152         if (IS_ENABLED(CONFIG_X86_32))
153                 return user_insn(fxsave %[fx], [fx] "=m" (*fx), "m" (*fx));
154         else
155                 return user_insn(fxsaveq %[fx], [fx] "=m" (*fx), "m" (*fx));
156
157 }
158
159 static inline void copy_kernel_to_fxregs(struct fxregs_state *fx)
160 {
161         if (IS_ENABLED(CONFIG_X86_32))
162                 kernel_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
163         else
164                 kernel_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
165 }
166
167 static inline int copy_kernel_to_fxregs_err(struct fxregs_state *fx)
168 {
169         if (IS_ENABLED(CONFIG_X86_32))
170                 return kernel_insn_err(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
171         else
172                 return kernel_insn_err(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
173 }
174
175 static inline int copy_user_to_fxregs(struct fxregs_state __user *fx)
176 {
177         if (IS_ENABLED(CONFIG_X86_32))
178                 return user_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
179         else
180                 return user_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
181 }
182
183 static inline void copy_kernel_to_fregs(struct fregs_state *fx)
184 {
185         kernel_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
186 }
187
188 static inline int copy_kernel_to_fregs_err(struct fregs_state *fx)
189 {
190         return kernel_insn_err(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
191 }
192
193 static inline int copy_user_to_fregs(struct fregs_state __user *fx)
194 {
195         return user_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
196 }
197
198 static inline void copy_fxregs_to_kernel(struct fpu *fpu)
199 {
200         if (IS_ENABLED(CONFIG_X86_32))
201                 asm volatile( "fxsave %[fx]" : [fx] "=m" (fpu->state.fxsave));
202         else
203                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (fpu->state.fxsave));
204 }
205
206 /* These macros all use (%edi)/(%rdi) as the single memory argument. */
207 #define XSAVE           ".byte " REX_PREFIX "0x0f,0xae,0x27"
208 #define XSAVEOPT        ".byte " REX_PREFIX "0x0f,0xae,0x37"
209 #define XSAVES          ".byte " REX_PREFIX "0x0f,0xc7,0x2f"
210 #define XRSTOR          ".byte " REX_PREFIX "0x0f,0xae,0x2f"
211 #define XRSTORS         ".byte " REX_PREFIX "0x0f,0xc7,0x1f"
212
213 #define XSTATE_OP(op, st, lmask, hmask, err)                            \
214         asm volatile("1:" op "\n\t"                                     \
215                      "xor %[err], %[err]\n"                             \
216                      "2:\n\t"                                           \
217                      ".pushsection .fixup,\"ax\"\n\t"                   \
218                      "3: movl $-2,%[err]\n\t"                           \
219                      "jmp 2b\n\t"                                       \
220                      ".popsection\n\t"                                  \
221                      _ASM_EXTABLE(1b, 3b)                               \
222                      : [err] "=r" (err)                                 \
223                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
224                      : "memory")
225
226 /*
227  * If XSAVES is enabled, it replaces XSAVEOPT because it supports a compact
228  * format and supervisor states in addition to modified optimization in
229  * XSAVEOPT.
230  *
231  * Otherwise, if XSAVEOPT is enabled, XSAVEOPT replaces XSAVE because XSAVEOPT
232  * supports modified optimization which is not supported by XSAVE.
233  *
234  * We use XSAVE as a fallback.
235  *
236  * The 661 label is defined in the ALTERNATIVE* macros as the address of the
237  * original instruction which gets replaced. We need to use it here as the
238  * address of the instruction where we might get an exception at.
239  */
240 #define XSTATE_XSAVE(st, lmask, hmask, err)                             \
241         asm volatile(ALTERNATIVE_2(XSAVE,                               \
242                                    XSAVEOPT, X86_FEATURE_XSAVEOPT,      \
243                                    XSAVES,   X86_FEATURE_XSAVES)        \
244                      "\n"                                               \
245                      "xor %[err], %[err]\n"                             \
246                      "3:\n"                                             \
247                      ".pushsection .fixup,\"ax\"\n"                     \
248                      "4: movl $-2, %[err]\n"                            \
249                      "jmp 3b\n"                                         \
250                      ".popsection\n"                                    \
251                      _ASM_EXTABLE(661b, 4b)                             \
252                      : [err] "=r" (err)                                 \
253                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
254                      : "memory")
255
256 /*
257  * Use XRSTORS to restore context if it is enabled. XRSTORS supports compact
258  * XSAVE area format.
259  */
260 #define XSTATE_XRESTORE(st, lmask, hmask)                               \
261         asm volatile(ALTERNATIVE(XRSTOR,                                \
262                                  XRSTORS, X86_FEATURE_XSAVES)           \
263                      "\n"                                               \
264                      "3:\n"                                             \
265                      _ASM_EXTABLE_HANDLE(661b, 3b, ex_handler_fprestore)\
266                      :                                                  \
267                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
268                      : "memory")
269
270 /*
271  * This function is called only during boot time when x86 caps are not set
272  * up and alternative can not be used yet.
273  */
274 static inline void copy_xregs_to_kernel_booting(struct xregs_state *xstate)
275 {
276         u64 mask = -1;
277         u32 lmask = mask;
278         u32 hmask = mask >> 32;
279         int err;
280
281         WARN_ON(system_state != SYSTEM_BOOTING);
282
283         if (static_cpu_has(X86_FEATURE_XSAVES))
284                 XSTATE_OP(XSAVES, xstate, lmask, hmask, err);
285         else
286                 XSTATE_OP(XSAVE, xstate, lmask, hmask, err);
287
288         /* We should never fault when copying to a kernel buffer: */
289         WARN_ON_FPU(err);
290 }
291
292 /*
293  * This function is called only during boot time when x86 caps are not set
294  * up and alternative can not be used yet.
295  */
296 static inline void copy_kernel_to_xregs_booting(struct xregs_state *xstate)
297 {
298         u64 mask = -1;
299         u32 lmask = mask;
300         u32 hmask = mask >> 32;
301         int err;
302
303         WARN_ON(system_state != SYSTEM_BOOTING);
304
305         if (static_cpu_has(X86_FEATURE_XSAVES))
306                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
307         else
308                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
309
310         /*
311          * We should never fault when copying from a kernel buffer, and the FPU
312          * state we set at boot time should be valid.
313          */
314         WARN_ON_FPU(err);
315 }
316
317 /*
318  * Save processor xstate to xsave area.
319  */
320 static inline void copy_xregs_to_kernel(struct xregs_state *xstate)
321 {
322         u64 mask = -1;
323         u32 lmask = mask;
324         u32 hmask = mask >> 32;
325         int err;
326
327         WARN_ON_FPU(!alternatives_patched);
328
329         XSTATE_XSAVE(xstate, lmask, hmask, err);
330
331         /* We should never fault when copying to a kernel buffer: */
332         WARN_ON_FPU(err);
333 }
334
335 /*
336  * Restore processor xstate from xsave area.
337  */
338 static inline void copy_kernel_to_xregs(struct xregs_state *xstate, u64 mask)
339 {
340         u32 lmask = mask;
341         u32 hmask = mask >> 32;
342
343         XSTATE_XRESTORE(xstate, lmask, hmask);
344 }
345
346 /*
347  * Save xstate to user space xsave area.
348  *
349  * We don't use modified optimization because xrstor/xrstors might track
350  * a different application.
351  *
352  * We don't use compacted format xsave area for
353  * backward compatibility for old applications which don't understand
354  * compacted format of xsave area.
355  */
356 static inline int copy_xregs_to_user(struct xregs_state __user *buf)
357 {
358         int err;
359
360         /*
361          * Clear the xsave header first, so that reserved fields are
362          * initialized to zero.
363          */
364         err = __clear_user(&buf->header, sizeof(buf->header));
365         if (unlikely(err))
366                 return -EFAULT;
367
368         stac();
369         XSTATE_OP(XSAVE, buf, -1, -1, err);
370         clac();
371
372         return err;
373 }
374
375 /*
376  * Restore xstate from user space xsave area.
377  */
378 static inline int copy_user_to_xregs(struct xregs_state __user *buf, u64 mask)
379 {
380         struct xregs_state *xstate = ((__force struct xregs_state *)buf);
381         u32 lmask = mask;
382         u32 hmask = mask >> 32;
383         int err;
384
385         stac();
386         XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
387         clac();
388
389         return err;
390 }
391
392 /*
393  * Restore xstate from kernel space xsave area, return an error code instead of
394  * an exception.
395  */
396 static inline int copy_kernel_to_xregs_err(struct xregs_state *xstate, u64 mask)
397 {
398         u32 lmask = mask;
399         u32 hmask = mask >> 32;
400         int err;
401
402         XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
403
404         return err;
405 }
406
407 /*
408  * These must be called with preempt disabled. Returns
409  * 'true' if the FPU state is still intact and we can
410  * keep registers active.
411  *
412  * The legacy FNSAVE instruction cleared all FPU state
413  * unconditionally, so registers are essentially destroyed.
414  * Modern FPU state can be kept in registers, if there are
415  * no pending FP exceptions.
416  */
417 static inline int copy_fpregs_to_fpstate(struct fpu *fpu)
418 {
419         if (likely(use_xsave())) {
420                 copy_xregs_to_kernel(&fpu->state.xsave);
421
422                 /*
423                  * AVX512 state is tracked here because its use is
424                  * known to slow the max clock speed of the core.
425                  */
426                 if (fpu->state.xsave.header.xfeatures & XFEATURE_MASK_AVX512)
427                         fpu->avx512_timestamp = jiffies;
428                 return 1;
429         }
430
431         if (likely(use_fxsr())) {
432                 copy_fxregs_to_kernel(fpu);
433                 return 1;
434         }
435
436         /*
437          * Legacy FPU register saving, FNSAVE always clears FPU registers,
438          * so we have to mark them inactive:
439          */
440         asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->state.fsave));
441
442         return 0;
443 }
444
445 static inline void __copy_kernel_to_fpregs(union fpregs_state *fpstate, u64 mask)
446 {
447         if (use_xsave()) {
448                 copy_kernel_to_xregs(&fpstate->xsave, mask);
449         } else {
450                 if (use_fxsr())
451                         copy_kernel_to_fxregs(&fpstate->fxsave);
452                 else
453                         copy_kernel_to_fregs(&fpstate->fsave);
454         }
455 }
456
457 static inline void copy_kernel_to_fpregs(union fpregs_state *fpstate)
458 {
459         /*
460          * AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is
461          * pending. Clear the x87 state here by setting it to fixed values.
462          * "m" is a random variable that should be in L1.
463          */
464         if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
465                 asm volatile(
466                         "fnclex\n\t"
467                         "emms\n\t"
468                         "fildl %P[addr]"        /* set F?P to defined value */
469                         : : [addr] "m" (fpstate));
470         }
471
472         __copy_kernel_to_fpregs(fpstate, -1);
473 }
474
475 extern int copy_fpstate_to_sigframe(void __user *buf, void __user *fp, int size);
476
477 /*
478  * FPU context switch related helper methods:
479  */
480
481 DECLARE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
482
483 /*
484  * The in-register FPU state for an FPU context on a CPU is assumed to be
485  * valid if the fpu->last_cpu matches the CPU, and the fpu_fpregs_owner_ctx
486  * matches the FPU.
487  *
488  * If the FPU register state is valid, the kernel can skip restoring the
489  * FPU state from memory.
490  *
491  * Any code that clobbers the FPU registers or updates the in-memory
492  * FPU state for a task MUST let the rest of the kernel know that the
493  * FPU registers are no longer valid for this task.
494  *
495  * Either one of these invalidation functions is enough. Invalidate
496  * a resource you control: CPU if using the CPU for something else
497  * (with preemption disabled), FPU for the current task, or a task that
498  * is prevented from running by the current task.
499  */
500 static inline void __cpu_invalidate_fpregs_state(void)
501 {
502         __this_cpu_write(fpu_fpregs_owner_ctx, NULL);
503 }
504
505 static inline void __fpu_invalidate_fpregs_state(struct fpu *fpu)
506 {
507         fpu->last_cpu = -1;
508 }
509
510 static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)
511 {
512         return fpu == this_cpu_read_stable(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;
513 }
514
515 /*
516  * These generally need preemption protection to work,
517  * do try to avoid using these on their own:
518  */
519 static inline void fpregs_deactivate(struct fpu *fpu)
520 {
521         this_cpu_write(fpu_fpregs_owner_ctx, NULL);
522         trace_x86_fpu_regs_deactivated(fpu);
523 }
524
525 static inline void fpregs_activate(struct fpu *fpu)
526 {
527         this_cpu_write(fpu_fpregs_owner_ctx, fpu);
528         trace_x86_fpu_regs_activated(fpu);
529 }
530
531 /*
532  * Internal helper, do not use directly. Use switch_fpu_return() instead.
533  */
534 static inline void __fpregs_load_activate(struct fpu *fpu, int cpu)
535 {
536         if (!fpregs_state_valid(fpu, cpu)) {
537                 if (current->mm)
538                         copy_kernel_to_fpregs(&fpu->state);
539                 fpregs_activate(fpu);
540         }
541 }
542
543 /*
544  * FPU state switching for scheduling.
545  *
546  * This is a two-stage process:
547  *
548  *  - switch_fpu_prepare() saves the old state.
549  *    This is done within the context of the old process.
550  *
551  *  - switch_fpu_finish() restores the new state as
552  *    necessary.
553  *
554  * If TIF_NEED_FPU_LOAD is cleared then the CPU's FPU registers
555  * are saved in the current thread's FPU register state.
556  *
557  * If TIF_NEED_FPU_LOAD is set then CPU's FPU registers may not
558  * hold current()'s FPU registers. It is required to load the
559  * registers before returning to userland or using the content
560  * otherwise.
561  *
562  * The FPU context is only stored/restored for a user task and
563  * ->mm is used to distinguish between kernel and user threads.
564  */
565 static inline void
566 switch_fpu_prepare(struct fpu *old_fpu, int cpu)
567 {
568         if (static_cpu_has(X86_FEATURE_FPU) && current->mm) {
569                 if (!copy_fpregs_to_fpstate(old_fpu))
570                         old_fpu->last_cpu = -1;
571                 else
572                         old_fpu->last_cpu = cpu;
573
574                 /* But leave fpu_fpregs_owner_ctx! */
575                 trace_x86_fpu_regs_deactivated(old_fpu);
576         }
577 }
578
579 /*
580  * Misc helper functions:
581  */
582
583 /*
584  * Set up the userspace FPU context for the new task, if the task
585  * has used the FPU.
586  */
587 static inline void switch_fpu_finish(struct fpu *new_fpu, int cpu)
588 {
589         u32 pkru_val = init_pkru_value;
590         struct pkru_state *pk;
591
592         if (!static_cpu_has(X86_FEATURE_FPU))
593                 return;
594
595         __fpregs_load_activate(new_fpu, cpu);
596
597         if (!cpu_feature_enabled(X86_FEATURE_OSPKE))
598                 return;
599
600         /*
601          * PKRU state is switched eagerly because it needs to be valid before we
602          * return to userland e.g. for a copy_to_user() operation.
603          */
604         if (current->mm) {
605                 pk = get_xsave_addr(&new_fpu->state.xsave, XFEATURE_PKRU);
606                 if (pk)
607                         pkru_val = pk->pkru;
608         }
609         __write_pkru(pkru_val);
610 }
611
612 /*
613  * MXCSR and XCR definitions:
614  */
615
616 extern unsigned int mxcsr_feature_mask;
617
618 #define XCR_XFEATURE_ENABLED_MASK       0x00000000
619
620 static inline u64 xgetbv(u32 index)
621 {
622         u32 eax, edx;
623
624         asm volatile(".byte 0x0f,0x01,0xd0" /* xgetbv */
625                      : "=a" (eax), "=d" (edx)
626                      : "c" (index));
627         return eax + ((u64)edx << 32);
628 }
629
630 static inline void xsetbv(u32 index, u64 value)
631 {
632         u32 eax = value;
633         u32 edx = value >> 32;
634
635         asm volatile(".byte 0x0f,0x01,0xd1" /* xsetbv */
636                      : : "a" (eax), "d" (edx), "c" (index));
637 }
638
639 #endif /* _ASM_X86_FPU_INTERNAL_H */