GNU Linux-libre 5.10.217-gnu1
[releases.git] / arch / x86 / kernel / fpu / core.c
1 // SPDX-License-Identifier: GPL-2.0-only
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  */
9 #include <asm/fpu/internal.h>
10 #include <asm/fpu/regset.h>
11 #include <asm/fpu/signal.h>
12 #include <asm/fpu/types.h>
13 #include <asm/traps.h>
14 #include <asm/irq_regs.h>
15
16 #include <linux/hardirq.h>
17 #include <linux/pkeys.h>
18
19 #define CREATE_TRACE_POINTS
20 #include <asm/trace/fpu.h>
21
22 /*
23  * Represents the initial FPU state. It's mostly (but not completely) zeroes,
24  * depending on the FPU hardware format:
25  */
26 union fpregs_state init_fpstate __read_mostly;
27
28 /* Track in-kernel FPU usage */
29 static DEFINE_PER_CPU(bool, in_kernel_fpu);
30
31 /*
32  * Track which context is using the FPU on the CPU:
33  */
34 DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
35
36 /*
37  * Can we use the FPU in kernel mode with the
38  * whole "kernel_fpu_begin/end()" sequence?
39  */
40 bool irq_fpu_usable(void)
41 {
42         if (WARN_ON_ONCE(in_nmi()))
43                 return false;
44
45         /* In kernel FPU usage already active? */
46         if (this_cpu_read(in_kernel_fpu))
47                 return false;
48
49         /*
50          * When not in NMI or hard interrupt context, FPU can be used in:
51          *
52          * - Task context except from within fpregs_lock()'ed critical
53          *   regions.
54          *
55          * - Soft interrupt processing context which cannot happen
56          *   while in a fpregs_lock()'ed critical region.
57          */
58         if (!in_irq())
59                 return true;
60
61         /*
62          * In hard interrupt context it's safe when soft interrupts
63          * are enabled, which means the interrupt did not hit in
64          * a fpregs_lock()'ed critical region.
65          */
66         return !softirq_count();
67 }
68 EXPORT_SYMBOL(irq_fpu_usable);
69
70 /*
71  * These must be called with preempt disabled. Returns
72  * 'true' if the FPU state is still intact and we can
73  * keep registers active.
74  *
75  * The legacy FNSAVE instruction cleared all FPU state
76  * unconditionally, so registers are essentially destroyed.
77  * Modern FPU state can be kept in registers, if there are
78  * no pending FP exceptions.
79  */
80 int copy_fpregs_to_fpstate(struct fpu *fpu)
81 {
82         if (likely(use_xsave())) {
83                 copy_xregs_to_kernel(&fpu->state.xsave);
84
85                 /*
86                  * AVX512 state is tracked here because its use is
87                  * known to slow the max clock speed of the core.
88                  */
89                 if (fpu->state.xsave.header.xfeatures & XFEATURE_MASK_AVX512)
90                         fpu->avx512_timestamp = jiffies;
91                 return 1;
92         }
93
94         if (likely(use_fxsr())) {
95                 copy_fxregs_to_kernel(fpu);
96                 return 1;
97         }
98
99         /*
100          * Legacy FPU register saving, FNSAVE always clears FPU registers,
101          * so we have to mark them inactive:
102          */
103         asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->state.fsave));
104
105         return 0;
106 }
107 EXPORT_SYMBOL(copy_fpregs_to_fpstate);
108
109 void kernel_fpu_begin_mask(unsigned int kfpu_mask)
110 {
111         preempt_disable();
112
113         WARN_ON_FPU(!irq_fpu_usable());
114         WARN_ON_FPU(this_cpu_read(in_kernel_fpu));
115
116         this_cpu_write(in_kernel_fpu, true);
117
118         if (!(current->flags & PF_KTHREAD) &&
119             !test_thread_flag(TIF_NEED_FPU_LOAD)) {
120                 set_thread_flag(TIF_NEED_FPU_LOAD);
121                 /*
122                  * Ignore return value -- we don't care if reg state
123                  * is clobbered.
124                  */
125                 copy_fpregs_to_fpstate(&current->thread.fpu);
126         }
127         __cpu_invalidate_fpregs_state();
128
129         /* Put sane initial values into the control registers. */
130         if (likely(kfpu_mask & KFPU_MXCSR) && boot_cpu_has(X86_FEATURE_XMM))
131                 ldmxcsr(MXCSR_DEFAULT);
132
133         if (unlikely(kfpu_mask & KFPU_387) && boot_cpu_has(X86_FEATURE_FPU))
134                 asm volatile ("fninit");
135 }
136 EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);
137
138 void kernel_fpu_end(void)
139 {
140         WARN_ON_FPU(!this_cpu_read(in_kernel_fpu));
141
142         this_cpu_write(in_kernel_fpu, false);
143         preempt_enable();
144 }
145 EXPORT_SYMBOL_GPL(kernel_fpu_end);
146
147 /*
148  * Save the FPU state (mark it for reload if necessary):
149  *
150  * This only ever gets called for the current task.
151  */
152 void fpu__save(struct fpu *fpu)
153 {
154         WARN_ON_FPU(fpu != &current->thread.fpu);
155
156         fpregs_lock();
157         trace_x86_fpu_before_save(fpu);
158
159         if (!test_thread_flag(TIF_NEED_FPU_LOAD)) {
160                 if (!copy_fpregs_to_fpstate(fpu)) {
161                         copy_kernel_to_fpregs(&fpu->state);
162                 }
163         }
164
165         trace_x86_fpu_after_save(fpu);
166         fpregs_unlock();
167 }
168
169 /*
170  * Legacy x87 fpstate state init:
171  */
172 static inline void fpstate_init_fstate(struct fregs_state *fp)
173 {
174         fp->cwd = 0xffff037fu;
175         fp->swd = 0xffff0000u;
176         fp->twd = 0xffffffffu;
177         fp->fos = 0xffff0000u;
178 }
179
180 void fpstate_init(union fpregs_state *state)
181 {
182         if (!static_cpu_has(X86_FEATURE_FPU)) {
183                 fpstate_init_soft(&state->soft);
184                 return;
185         }
186
187         memset(state, 0, fpu_kernel_xstate_size);
188
189         if (static_cpu_has(X86_FEATURE_XSAVES))
190                 fpstate_init_xstate(&state->xsave);
191         if (static_cpu_has(X86_FEATURE_FXSR))
192                 fpstate_init_fxstate(&state->fxsave);
193         else
194                 fpstate_init_fstate(&state->fsave);
195 }
196 EXPORT_SYMBOL_GPL(fpstate_init);
197
198 int fpu__copy(struct task_struct *dst, struct task_struct *src)
199 {
200         struct fpu *dst_fpu = &dst->thread.fpu;
201         struct fpu *src_fpu = &src->thread.fpu;
202
203         dst_fpu->last_cpu = -1;
204
205         if (!static_cpu_has(X86_FEATURE_FPU))
206                 return 0;
207
208         WARN_ON_FPU(src_fpu != &current->thread.fpu);
209
210         /*
211          * Don't let 'init optimized' areas of the XSAVE area
212          * leak into the child task:
213          */
214         memset(&dst_fpu->state.xsave, 0, fpu_kernel_xstate_size);
215
216         /*
217          * If the FPU registers are not current just memcpy() the state.
218          * Otherwise save current FPU registers directly into the child's FPU
219          * context, without any memory-to-memory copying.
220          *
221          * ( The function 'fails' in the FNSAVE case, which destroys
222          *   register contents so we have to load them back. )
223          */
224         fpregs_lock();
225         if (test_thread_flag(TIF_NEED_FPU_LOAD))
226                 memcpy(&dst_fpu->state, &src_fpu->state, fpu_kernel_xstate_size);
227
228         else if (!copy_fpregs_to_fpstate(dst_fpu))
229                 copy_kernel_to_fpregs(&dst_fpu->state);
230
231         fpregs_unlock();
232
233         set_tsk_thread_flag(dst, TIF_NEED_FPU_LOAD);
234
235         trace_x86_fpu_copy_src(src_fpu);
236         trace_x86_fpu_copy_dst(dst_fpu);
237
238         return 0;
239 }
240
241 /*
242  * Activate the current task's in-memory FPU context,
243  * if it has not been used before:
244  */
245 static void fpu__initialize(struct fpu *fpu)
246 {
247         WARN_ON_FPU(fpu != &current->thread.fpu);
248
249         set_thread_flag(TIF_NEED_FPU_LOAD);
250         fpstate_init(&fpu->state);
251         trace_x86_fpu_init_state(fpu);
252 }
253
254 /*
255  * This function must be called before we read a task's fpstate.
256  *
257  * There's two cases where this gets called:
258  *
259  * - for the current task (when coredumping), in which case we have
260  *   to save the latest FPU registers into the fpstate,
261  *
262  * - or it's called for stopped tasks (ptrace), in which case the
263  *   registers were already saved by the context-switch code when
264  *   the task scheduled out.
265  *
266  * If the task has used the FPU before then save it.
267  */
268 void fpu__prepare_read(struct fpu *fpu)
269 {
270         if (fpu == &current->thread.fpu)
271                 fpu__save(fpu);
272 }
273
274 /*
275  * This function must be called before we write a task's fpstate.
276  *
277  * Invalidate any cached FPU registers.
278  *
279  * After this function call, after registers in the fpstate are
280  * modified and the child task has woken up, the child task will
281  * restore the modified FPU state from the modified context. If we
282  * didn't clear its cached status here then the cached in-registers
283  * state pending on its former CPU could be restored, corrupting
284  * the modifications.
285  */
286 void fpu__prepare_write(struct fpu *fpu)
287 {
288         /*
289          * Only stopped child tasks can be used to modify the FPU
290          * state in the fpstate buffer:
291          */
292         WARN_ON_FPU(fpu == &current->thread.fpu);
293
294         /* Invalidate any cached state: */
295         __fpu_invalidate_fpregs_state(fpu);
296 }
297
298 /*
299  * Drops current FPU state: deactivates the fpregs and
300  * the fpstate. NOTE: it still leaves previous contents
301  * in the fpregs in the eager-FPU case.
302  *
303  * This function can be used in cases where we know that
304  * a state-restore is coming: either an explicit one,
305  * or a reschedule.
306  */
307 void fpu__drop(struct fpu *fpu)
308 {
309         preempt_disable();
310
311         if (fpu == &current->thread.fpu) {
312                 /* Ignore delayed exceptions from user space */
313                 asm volatile("1: fwait\n"
314                              "2:\n"
315                              _ASM_EXTABLE(1b, 2b));
316                 fpregs_deactivate(fpu);
317         }
318
319         trace_x86_fpu_dropped(fpu);
320
321         preempt_enable();
322 }
323
324 /*
325  * Clear FPU registers by setting them up from the init fpstate.
326  * Caller must do fpregs_[un]lock() around it.
327  */
328 static inline void copy_init_fpstate_to_fpregs(u64 features_mask)
329 {
330         if (use_xsave())
331                 copy_kernel_to_xregs(&init_fpstate.xsave, features_mask);
332         else if (static_cpu_has(X86_FEATURE_FXSR))
333                 copy_kernel_to_fxregs(&init_fpstate.fxsave);
334         else
335                 copy_kernel_to_fregs(&init_fpstate.fsave);
336
337         if (boot_cpu_has(X86_FEATURE_OSPKE))
338                 copy_init_pkru_to_fpregs();
339 }
340
341 /*
342  * Clear the FPU state back to init state.
343  *
344  * Called by sys_execve(), by the signal handler code and by various
345  * error paths.
346  */
347 static void fpu__clear(struct fpu *fpu, bool user_only)
348 {
349         WARN_ON_FPU(fpu != &current->thread.fpu);
350
351         if (!static_cpu_has(X86_FEATURE_FPU)) {
352                 fpu__drop(fpu);
353                 fpu__initialize(fpu);
354                 return;
355         }
356
357         fpregs_lock();
358
359         if (user_only) {
360                 if (!fpregs_state_valid(fpu, smp_processor_id()) &&
361                     xfeatures_mask_supervisor())
362                         copy_kernel_to_xregs(&fpu->state.xsave,
363                                              xfeatures_mask_supervisor());
364                 copy_init_fpstate_to_fpregs(xfeatures_mask_user());
365         } else {
366                 copy_init_fpstate_to_fpregs(xfeatures_mask_all);
367         }
368
369         fpregs_mark_activate();
370         fpregs_unlock();
371 }
372
373 void fpu__clear_user_states(struct fpu *fpu)
374 {
375         fpu__clear(fpu, true);
376 }
377
378 void fpu__clear_all(struct fpu *fpu)
379 {
380         fpu__clear(fpu, false);
381 }
382
383 /*
384  * Load FPU context before returning to userspace.
385  */
386 void switch_fpu_return(void)
387 {
388         if (!static_cpu_has(X86_FEATURE_FPU))
389                 return;
390
391         __fpregs_load_activate();
392 }
393 EXPORT_SYMBOL_GPL(switch_fpu_return);
394
395 #ifdef CONFIG_X86_DEBUG_FPU
396 /*
397  * If current FPU state according to its tracking (loaded FPU context on this
398  * CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is
399  * loaded on return to userland.
400  */
401 void fpregs_assert_state_consistent(void)
402 {
403         struct fpu *fpu = &current->thread.fpu;
404
405         if (test_thread_flag(TIF_NEED_FPU_LOAD))
406                 return;
407
408         WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));
409 }
410 EXPORT_SYMBOL_GPL(fpregs_assert_state_consistent);
411 #endif
412
413 void fpregs_mark_activate(void)
414 {
415         struct fpu *fpu = &current->thread.fpu;
416
417         fpregs_activate(fpu);
418         fpu->last_cpu = smp_processor_id();
419         clear_thread_flag(TIF_NEED_FPU_LOAD);
420 }
421 EXPORT_SYMBOL_GPL(fpregs_mark_activate);
422
423 /*
424  * x87 math exception handling:
425  */
426
427 int fpu__exception_code(struct fpu *fpu, int trap_nr)
428 {
429         int err;
430
431         if (trap_nr == X86_TRAP_MF) {
432                 unsigned short cwd, swd;
433                 /*
434                  * (~cwd & swd) will mask out exceptions that are not set to unmasked
435                  * status.  0x3f is the exception bits in these regs, 0x200 is the
436                  * C1 reg you need in case of a stack fault, 0x040 is the stack
437                  * fault bit.  We should only be taking one exception at a time,
438                  * so if this combination doesn't produce any single exception,
439                  * then we have a bad program that isn't synchronizing its FPU usage
440                  * and it will suffer the consequences since we won't be able to
441                  * fully reproduce the context of the exception.
442                  */
443                 if (boot_cpu_has(X86_FEATURE_FXSR)) {
444                         cwd = fpu->state.fxsave.cwd;
445                         swd = fpu->state.fxsave.swd;
446                 } else {
447                         cwd = (unsigned short)fpu->state.fsave.cwd;
448                         swd = (unsigned short)fpu->state.fsave.swd;
449                 }
450
451                 err = swd & ~cwd;
452         } else {
453                 /*
454                  * The SIMD FPU exceptions are handled a little differently, as there
455                  * is only a single status/control register.  Thus, to determine which
456                  * unmasked exception was caught we must mask the exception mask bits
457                  * at 0x1f80, and then use these to mask the exception bits at 0x3f.
458                  */
459                 unsigned short mxcsr = MXCSR_DEFAULT;
460
461                 if (boot_cpu_has(X86_FEATURE_XMM))
462                         mxcsr = fpu->state.fxsave.mxcsr;
463
464                 err = ~(mxcsr >> 7) & mxcsr;
465         }
466
467         if (err & 0x001) {      /* Invalid op */
468                 /*
469                  * swd & 0x240 == 0x040: Stack Underflow
470                  * swd & 0x240 == 0x240: Stack Overflow
471                  * User must clear the SF bit (0x40) if set
472                  */
473                 return FPE_FLTINV;
474         } else if (err & 0x004) { /* Divide by Zero */
475                 return FPE_FLTDIV;
476         } else if (err & 0x008) { /* Overflow */
477                 return FPE_FLTOVF;
478         } else if (err & 0x012) { /* Denormal, Underflow */
479                 return FPE_FLTUND;
480         } else if (err & 0x020) { /* Precision */
481                 return FPE_FLTRES;
482         }
483
484         /*
485          * If we're using IRQ 13, or supposedly even some trap
486          * X86_TRAP_MF implementations, it's possible
487          * we get a spurious trap, which is not an error.
488          */
489         return 0;
490 }