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