58f20821662f890db80d5afdb205c0235a6f9114
[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_read(struct fpu *fpu);
30 extern void fpu__prepare_write(struct fpu *fpu);
31 extern void fpu__save(struct fpu *fpu);
32 extern int  fpu__restore_sig(void __user *buf, int ia32_frame);
33 extern void fpu__drop(struct fpu *fpu);
34 extern int  fpu__copy(struct task_struct *dst, struct task_struct *src);
35 extern void fpu__clear_user_states(struct fpu *fpu);
36 extern void fpu__clear_all(struct fpu *fpu);
37 extern int  fpu__exception_code(struct fpu *fpu, int trap_nr);
38
39 /*
40  * Boot time FPU initialization functions:
41  */
42 extern void fpu__init_cpu(void);
43 extern void fpu__init_system_xstate(void);
44 extern void fpu__init_cpu_xstate(void);
45 extern void fpu__init_system(struct cpuinfo_x86 *c);
46 extern void fpu__init_check_bugs(void);
47 extern void fpu__resume_cpu(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_all;
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 static inline void fxsave(struct fxregs_state *fx)
207 {
208         if (IS_ENABLED(CONFIG_X86_32))
209                 asm volatile( "fxsave %[fx]" : [fx] "=m" (*fx));
210         else
211                 asm volatile("fxsaveq %[fx]" : [fx] "=m" (*fx));
212 }
213
214 /* These macros all use (%edi)/(%rdi) as the single memory argument. */
215 #define XSAVE           ".byte " REX_PREFIX "0x0f,0xae,0x27"
216 #define XSAVEOPT        ".byte " REX_PREFIX "0x0f,0xae,0x37"
217 #define XSAVES          ".byte " REX_PREFIX "0x0f,0xc7,0x2f"
218 #define XRSTOR          ".byte " REX_PREFIX "0x0f,0xae,0x2f"
219 #define XRSTORS         ".byte " REX_PREFIX "0x0f,0xc7,0x1f"
220
221 #define XSTATE_OP(op, st, lmask, hmask, err)                            \
222         asm volatile("1:" op "\n\t"                                     \
223                      "xor %[err], %[err]\n"                             \
224                      "2:\n\t"                                           \
225                      ".pushsection .fixup,\"ax\"\n\t"                   \
226                      "3: movl $-2,%[err]\n\t"                           \
227                      "jmp 2b\n\t"                                       \
228                      ".popsection\n\t"                                  \
229                      _ASM_EXTABLE(1b, 3b)                               \
230                      : [err] "=r" (err)                                 \
231                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
232                      : "memory")
233
234 /*
235  * If XSAVES is enabled, it replaces XSAVEOPT because it supports a compact
236  * format and supervisor states in addition to modified optimization in
237  * XSAVEOPT.
238  *
239  * Otherwise, if XSAVEOPT is enabled, XSAVEOPT replaces XSAVE because XSAVEOPT
240  * supports modified optimization which is not supported by XSAVE.
241  *
242  * We use XSAVE as a fallback.
243  *
244  * The 661 label is defined in the ALTERNATIVE* macros as the address of the
245  * original instruction which gets replaced. We need to use it here as the
246  * address of the instruction where we might get an exception at.
247  */
248 #define XSTATE_XSAVE(st, lmask, hmask, err)                             \
249         asm volatile(ALTERNATIVE_2(XSAVE,                               \
250                                    XSAVEOPT, X86_FEATURE_XSAVEOPT,      \
251                                    XSAVES,   X86_FEATURE_XSAVES)        \
252                      "\n"                                               \
253                      "xor %[err], %[err]\n"                             \
254                      "3:\n"                                             \
255                      ".pushsection .fixup,\"ax\"\n"                     \
256                      "4: movl $-2, %[err]\n"                            \
257                      "jmp 3b\n"                                         \
258                      ".popsection\n"                                    \
259                      _ASM_EXTABLE(661b, 4b)                             \
260                      : [err] "=r" (err)                                 \
261                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
262                      : "memory")
263
264 /*
265  * Use XRSTORS to restore context if it is enabled. XRSTORS supports compact
266  * XSAVE area format.
267  */
268 #define XSTATE_XRESTORE(st, lmask, hmask)                               \
269         asm volatile(ALTERNATIVE(XRSTOR,                                \
270                                  XRSTORS, X86_FEATURE_XSAVES)           \
271                      "\n"                                               \
272                      "3:\n"                                             \
273                      _ASM_EXTABLE_HANDLE(661b, 3b, ex_handler_fprestore)\
274                      :                                                  \
275                      : "D" (st), "m" (*st), "a" (lmask), "d" (hmask)    \
276                      : "memory")
277
278 /*
279  * This function is called only during boot time when x86 caps are not set
280  * up and alternative can not be used yet.
281  */
282 static inline void copy_kernel_to_xregs_booting(struct xregs_state *xstate)
283 {
284         u64 mask = -1;
285         u32 lmask = mask;
286         u32 hmask = mask >> 32;
287         int err;
288
289         WARN_ON(system_state != SYSTEM_BOOTING);
290
291         if (boot_cpu_has(X86_FEATURE_XSAVES))
292                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
293         else
294                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
295
296         /*
297          * We should never fault when copying from a kernel buffer, and the FPU
298          * state we set at boot time should be valid.
299          */
300         WARN_ON_FPU(err);
301 }
302
303 /*
304  * Save processor xstate to xsave area.
305  */
306 static inline void copy_xregs_to_kernel(struct xregs_state *xstate)
307 {
308         u64 mask = xfeatures_mask_all;
309         u32 lmask = mask;
310         u32 hmask = mask >> 32;
311         int err;
312
313         WARN_ON_FPU(!alternatives_patched);
314
315         XSTATE_XSAVE(xstate, lmask, hmask, err);
316
317         /* We should never fault when copying to a kernel buffer: */
318         WARN_ON_FPU(err);
319 }
320
321 /*
322  * Restore processor xstate from xsave area.
323  */
324 static inline void copy_kernel_to_xregs(struct xregs_state *xstate, u64 mask)
325 {
326         u32 lmask = mask;
327         u32 hmask = mask >> 32;
328
329         XSTATE_XRESTORE(xstate, lmask, hmask);
330 }
331
332 /*
333  * Save xstate to user space xsave area.
334  *
335  * We don't use modified optimization because xrstor/xrstors might track
336  * a different application.
337  *
338  * We don't use compacted format xsave area for
339  * backward compatibility for old applications which don't understand
340  * compacted format of xsave area.
341  */
342 static inline int copy_xregs_to_user(struct xregs_state __user *buf)
343 {
344         u64 mask = xfeatures_mask_user();
345         u32 lmask = mask;
346         u32 hmask = mask >> 32;
347         int err;
348
349         /*
350          * Clear the xsave header first, so that reserved fields are
351          * initialized to zero.
352          */
353         err = __clear_user(&buf->header, sizeof(buf->header));
354         if (unlikely(err))
355                 return -EFAULT;
356
357         stac();
358         XSTATE_OP(XSAVE, buf, lmask, hmask, err);
359         clac();
360
361         return err;
362 }
363
364 /*
365  * Restore xstate from user space xsave area.
366  */
367 static inline int copy_user_to_xregs(struct xregs_state __user *buf, u64 mask)
368 {
369         struct xregs_state *xstate = ((__force struct xregs_state *)buf);
370         u32 lmask = mask;
371         u32 hmask = mask >> 32;
372         int err;
373
374         stac();
375         XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
376         clac();
377
378         return err;
379 }
380
381 /*
382  * Restore xstate from kernel space xsave area, return an error code instead of
383  * an exception.
384  */
385 static inline int copy_kernel_to_xregs_err(struct xregs_state *xstate, u64 mask)
386 {
387         u32 lmask = mask;
388         u32 hmask = mask >> 32;
389         int err;
390
391         if (static_cpu_has(X86_FEATURE_XSAVES))
392                 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
393         else
394                 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
395
396         return err;
397 }
398
399 extern int copy_fpregs_to_fpstate(struct fpu *fpu);
400
401 static inline void __copy_kernel_to_fpregs(union fpregs_state *fpstate, u64 mask)
402 {
403         if (use_xsave()) {
404                 copy_kernel_to_xregs(&fpstate->xsave, mask);
405         } else {
406                 if (use_fxsr())
407                         copy_kernel_to_fxregs(&fpstate->fxsave);
408                 else
409                         copy_kernel_to_fregs(&fpstate->fsave);
410         }
411 }
412
413 static inline void copy_kernel_to_fpregs(union fpregs_state *fpstate)
414 {
415         /*
416          * AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is
417          * pending. Clear the x87 state here by setting it to fixed values.
418          * "m" is a random variable that should be in L1.
419          */
420         if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
421                 asm volatile(
422                         "fnclex\n\t"
423                         "emms\n\t"
424                         "fildl %P[addr]"        /* set F?P to defined value */
425                         : : [addr] "m" (fpstate));
426         }
427
428         __copy_kernel_to_fpregs(fpstate, -1);
429 }
430
431 extern int copy_fpstate_to_sigframe(void __user *buf, void __user *fp, int size);
432
433 /*
434  * FPU context switch related helper methods:
435  */
436
437 DECLARE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
438
439 /*
440  * The in-register FPU state for an FPU context on a CPU is assumed to be
441  * valid if the fpu->last_cpu matches the CPU, and the fpu_fpregs_owner_ctx
442  * matches the FPU.
443  *
444  * If the FPU register state is valid, the kernel can skip restoring the
445  * FPU state from memory.
446  *
447  * Any code that clobbers the FPU registers or updates the in-memory
448  * FPU state for a task MUST let the rest of the kernel know that the
449  * FPU registers are no longer valid for this task.
450  *
451  * Either one of these invalidation functions is enough. Invalidate
452  * a resource you control: CPU if using the CPU for something else
453  * (with preemption disabled), FPU for the current task, or a task that
454  * is prevented from running by the current task.
455  */
456 static inline void __cpu_invalidate_fpregs_state(void)
457 {
458         __this_cpu_write(fpu_fpregs_owner_ctx, NULL);
459 }
460
461 static inline void __fpu_invalidate_fpregs_state(struct fpu *fpu)
462 {
463         fpu->last_cpu = -1;
464 }
465
466 static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)
467 {
468         return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;
469 }
470
471 /*
472  * These generally need preemption protection to work,
473  * do try to avoid using these on their own:
474  */
475 static inline void fpregs_deactivate(struct fpu *fpu)
476 {
477         this_cpu_write(fpu_fpregs_owner_ctx, NULL);
478         trace_x86_fpu_regs_deactivated(fpu);
479 }
480
481 static inline void fpregs_activate(struct fpu *fpu)
482 {
483         this_cpu_write(fpu_fpregs_owner_ctx, fpu);
484         trace_x86_fpu_regs_activated(fpu);
485 }
486
487 /*
488  * Internal helper, do not use directly. Use switch_fpu_return() instead.
489  */
490 static inline void __fpregs_load_activate(void)
491 {
492         struct fpu *fpu = &current->thread.fpu;
493         int cpu = smp_processor_id();
494
495         if (WARN_ON_ONCE(current->flags & PF_KTHREAD))
496                 return;
497
498         if (!fpregs_state_valid(fpu, cpu)) {
499                 copy_kernel_to_fpregs(&fpu->state);
500                 fpregs_activate(fpu);
501                 fpu->last_cpu = cpu;
502         }
503         clear_thread_flag(TIF_NEED_FPU_LOAD);
504 }
505
506 /*
507  * FPU state switching for scheduling.
508  *
509  * This is a two-stage process:
510  *
511  *  - switch_fpu_prepare() saves the old state.
512  *    This is done within the context of the old process.
513  *
514  *  - switch_fpu_finish() sets TIF_NEED_FPU_LOAD; the floating point state
515  *    will get loaded on return to userspace, or when the kernel needs it.
516  *
517  * If TIF_NEED_FPU_LOAD is cleared then the CPU's FPU registers
518  * are saved in the current thread's FPU register state.
519  *
520  * If TIF_NEED_FPU_LOAD is set then CPU's FPU registers may not
521  * hold current()'s FPU registers. It is required to load the
522  * registers before returning to userland or using the content
523  * otherwise.
524  *
525  * The FPU context is only stored/restored for a user task and
526  * PF_KTHREAD is used to distinguish between kernel and user threads.
527  */
528 static inline void switch_fpu_prepare(struct fpu *old_fpu, int cpu)
529 {
530         if (static_cpu_has(X86_FEATURE_FPU) && !(current->flags & PF_KTHREAD)) {
531                 if (!copy_fpregs_to_fpstate(old_fpu))
532                         old_fpu->last_cpu = -1;
533                 else
534                         old_fpu->last_cpu = cpu;
535
536                 /* But leave fpu_fpregs_owner_ctx! */
537                 trace_x86_fpu_regs_deactivated(old_fpu);
538         }
539 }
540
541 /*
542  * Misc helper functions:
543  */
544
545 /*
546  * Load PKRU from the FPU context if available. Delay loading of the
547  * complete FPU state until the return to userland.
548  */
549 static inline void switch_fpu_finish(struct fpu *new_fpu)
550 {
551         u32 pkru_val = init_pkru_value;
552         struct pkru_state *pk;
553
554         if (!static_cpu_has(X86_FEATURE_FPU))
555                 return;
556
557         set_thread_flag(TIF_NEED_FPU_LOAD);
558
559         if (!cpu_feature_enabled(X86_FEATURE_OSPKE))
560                 return;
561
562         /*
563          * PKRU state is switched eagerly because it needs to be valid before we
564          * return to userland e.g. for a copy_to_user() operation.
565          */
566         if (!(current->flags & PF_KTHREAD)) {
567                 /*
568                  * If the PKRU bit in xsave.header.xfeatures is not set,
569                  * then the PKRU component was in init state, which means
570                  * XRSTOR will set PKRU to 0. If the bit is not set then
571                  * get_xsave_addr() will return NULL because the PKRU value
572                  * in memory is not valid. This means pkru_val has to be
573                  * set to 0 and not to init_pkru_value.
574                  */
575                 pk = get_xsave_addr(&new_fpu->state.xsave, XFEATURE_PKRU);
576                 pkru_val = pk ? pk->pkru : 0;
577         }
578         __write_pkru(pkru_val);
579 }
580
581 #endif /* _ASM_X86_FPU_INTERNAL_H */