1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 1994 Linus Torvalds
5 * Pentium III FXSR, SSE support
6 * General FPU state handling cleanups
7 * Gareth Hughes <gareth@valinux.com>, May 2000
9 #include <asm/fpu/api.h>
10 #include <asm/fpu/regset.h>
11 #include <asm/fpu/sched.h>
12 #include <asm/fpu/signal.h>
13 #include <asm/fpu/types.h>
14 #include <asm/traps.h>
15 #include <asm/irq_regs.h>
17 #include <linux/hardirq.h>
18 #include <linux/pkeys.h>
19 #include <linux/vmalloc.h>
26 #define CREATE_TRACE_POINTS
27 #include <asm/trace/fpu.h>
30 DEFINE_STATIC_KEY_FALSE(__fpu_state_size_dynamic);
31 DEFINE_PER_CPU(u64, xfd_state);
34 /* The FPU state configuration data for kernel and user space */
35 struct fpu_state_config fpu_kernel_cfg __ro_after_init;
36 struct fpu_state_config fpu_user_cfg __ro_after_init;
39 * Represents the initial FPU state. It's mostly (but not completely) zeroes,
40 * depending on the FPU hardware format:
42 struct fpstate init_fpstate __ro_after_init;
45 * Track whether the kernel is using the FPU state
50 * - by IRQ context code to potentially use the FPU
53 * - to debug kernel_fpu_begin()/end() correctness
55 static DEFINE_PER_CPU(bool, in_kernel_fpu);
58 * Track which context is using the FPU on the CPU:
60 DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
62 static bool kernel_fpu_disabled(void)
64 return this_cpu_read(in_kernel_fpu);
67 static bool interrupted_kernel_fpu_idle(void)
69 return !kernel_fpu_disabled();
73 * Were we in user mode (or vm86 mode) when we were
76 * Doing kernel_fpu_begin/end() is ok if we are running
77 * in an interrupt context from user mode - we'll just
78 * save the FPU state as required.
80 static bool interrupted_user_mode(void)
82 struct pt_regs *regs = get_irq_regs();
83 return regs && user_mode(regs);
87 * Can we use the FPU in kernel mode with the
88 * whole "kernel_fpu_begin/end()" sequence?
90 * It's always ok in process context (ie "not interrupt")
91 * but it is sometimes ok even from an irq.
93 bool irq_fpu_usable(void)
95 return !in_interrupt() ||
96 interrupted_user_mode() ||
97 interrupted_kernel_fpu_idle();
99 EXPORT_SYMBOL(irq_fpu_usable);
102 * Track AVX512 state use because it is known to slow the max clock
105 static void update_avx_timestamp(struct fpu *fpu)
108 #define AVX512_TRACKING_MASK (XFEATURE_MASK_ZMM_Hi256 | XFEATURE_MASK_Hi16_ZMM)
110 if (fpu->fpstate->regs.xsave.header.xfeatures & AVX512_TRACKING_MASK)
111 fpu->avx512_timestamp = jiffies;
115 * Save the FPU register state in fpu->fpstate->regs. The register state is
118 * Must be called with fpregs_lock() held.
120 * The legacy FNSAVE instruction clears all FPU state unconditionally, so
121 * register state has to be reloaded. That might be a pointless exercise
122 * when the FPU is going to be used by another task right after that. But
123 * this only affects 20+ years old 32bit systems and avoids conditionals all
126 * FXSAVE and all XSAVE variants preserve the FPU register state.
128 void save_fpregs_to_fpstate(struct fpu *fpu)
130 if (likely(use_xsave())) {
131 os_xsave(fpu->fpstate);
132 update_avx_timestamp(fpu);
136 if (likely(use_fxsr())) {
137 fxsave(&fpu->fpstate->regs.fxsave);
142 * Legacy FPU register saving, FNSAVE always clears FPU registers,
143 * so we have to reload them from the memory state.
145 asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->fpstate->regs.fsave));
146 frstor(&fpu->fpstate->regs.fsave);
149 void restore_fpregs_from_fpstate(struct fpstate *fpstate, u64 mask)
152 * AMD K7/K8 and later CPUs up to Zen don't save/restore
153 * FDP/FIP/FOP unless an exception is pending. Clear the x87 state
154 * here by setting it to fixed values. "m" is a random variable
155 * that should be in L1.
157 if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
161 "fildl %P[addr]" /* set F?P to defined value */
162 : : [addr] "m" (fpstate));
167 * Dynamically enabled features are enabled in XCR0, but
168 * usage requires also that the corresponding bits in XFD
169 * are cleared. If the bits are set then using a related
170 * instruction will raise #NM. This allows to do the
171 * allocation of the larger FPU buffer lazy from #NM or if
172 * the task has no permission to kill it which would happen
173 * via #UD if the feature is disabled in XCR0.
175 * XFD state is following the same life time rules as
176 * XSTATE and to restore state correctly XFD has to be
177 * updated before XRSTORS otherwise the component would
178 * stay in or go into init state even if the bits are set
179 * in fpstate::regs::xsave::xfeatures.
181 xfd_update_state(fpstate);
184 * Restoring state always needs to modify all features
185 * which are in @mask even if the current task cannot use
188 * So fpstate->xfeatures cannot be used here, because then
189 * a feature for which the task has no permission but was
190 * used by the previous task would not go into init state.
192 mask = fpu_kernel_cfg.max_features & mask;
194 os_xrstor(fpstate, mask);
197 fxrstor(&fpstate->regs.fxsave);
199 frstor(&fpstate->regs.fsave);
203 void fpu_reset_from_exception_fixup(void)
205 restore_fpregs_from_fpstate(&init_fpstate, XFEATURE_MASK_FPSTATE);
208 #if IS_ENABLED(CONFIG_KVM)
209 static void __fpstate_reset(struct fpstate *fpstate);
211 bool fpu_alloc_guest_fpstate(struct fpu_guest *gfpu)
213 struct fpstate *fpstate;
216 size = fpu_user_cfg.default_size + ALIGN(offsetof(struct fpstate, regs), 64);
217 fpstate = vzalloc(size);
221 __fpstate_reset(fpstate);
222 fpstate_init_user(fpstate);
223 fpstate->is_valloc = true;
224 fpstate->is_guest = true;
226 gfpu->fpstate = fpstate;
229 EXPORT_SYMBOL_GPL(fpu_alloc_guest_fpstate);
231 void fpu_free_guest_fpstate(struct fpu_guest *gfpu)
233 struct fpstate *fps = gfpu->fpstate;
238 if (WARN_ON_ONCE(!fps->is_valloc || !fps->is_guest || fps->in_use))
241 gfpu->fpstate = NULL;
244 EXPORT_SYMBOL_GPL(fpu_free_guest_fpstate);
246 int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest)
248 struct fpstate *guest_fps = guest_fpu->fpstate;
249 struct fpu *fpu = ¤t->thread.fpu;
250 struct fpstate *cur_fps = fpu->fpstate;
253 if (!cur_fps->is_confidential && !test_thread_flag(TIF_NEED_FPU_LOAD))
254 save_fpregs_to_fpstate(fpu);
258 fpu->__task_fpstate = cur_fps;
259 fpu->fpstate = guest_fps;
260 guest_fps->in_use = true;
262 guest_fps->in_use = false;
263 fpu->fpstate = fpu->__task_fpstate;
264 fpu->__task_fpstate = NULL;
267 cur_fps = fpu->fpstate;
269 if (!cur_fps->is_confidential) {
270 /* Includes XFD update */
271 restore_fpregs_from_fpstate(cur_fps, XFEATURE_MASK_FPSTATE);
274 * XSTATE is restored by firmware from encrypted
275 * memory. Make sure XFD state is correct while
276 * running with guest fpstate
278 xfd_update_state(cur_fps);
281 fpregs_mark_activate();
285 EXPORT_SYMBOL_GPL(fpu_swap_kvm_fpstate);
287 void fpu_copy_guest_fpstate_to_uabi(struct fpu_guest *gfpu, void *buf,
288 unsigned int size, u32 pkru)
290 struct fpstate *kstate = gfpu->fpstate;
291 union fpregs_state *ustate = buf;
292 struct membuf mb = { .p = buf, .left = size };
294 if (cpu_feature_enabled(X86_FEATURE_XSAVE)) {
295 __copy_xstate_to_uabi_buf(mb, kstate, pkru, XSTATE_COPY_XSAVE);
297 memcpy(&ustate->fxsave, &kstate->regs.fxsave,
298 sizeof(ustate->fxsave));
299 /* Make it restorable on a XSAVE enabled host */
300 ustate->xsave.header.xfeatures = XFEATURE_MASK_FPSSE;
303 EXPORT_SYMBOL_GPL(fpu_copy_guest_fpstate_to_uabi);
305 int fpu_copy_uabi_to_guest_fpstate(struct fpu_guest *gfpu, const void *buf,
306 u64 xcr0, u32 *vpkru)
308 struct fpstate *kstate = gfpu->fpstate;
309 const union fpregs_state *ustate = buf;
310 struct pkru_state *xpkru;
313 if (!cpu_feature_enabled(X86_FEATURE_XSAVE)) {
314 if (ustate->xsave.header.xfeatures & ~XFEATURE_MASK_FPSSE)
316 if (ustate->fxsave.mxcsr & ~mxcsr_feature_mask)
318 memcpy(&kstate->regs.fxsave, &ustate->fxsave, sizeof(ustate->fxsave));
322 if (ustate->xsave.header.xfeatures & ~xcr0)
325 ret = copy_uabi_from_kernel_to_xstate(kstate, ustate);
329 /* Retrieve PKRU if not in init state */
330 if (kstate->regs.xsave.header.xfeatures & XFEATURE_MASK_PKRU) {
331 xpkru = get_xsave_addr(&kstate->regs.xsave, XFEATURE_PKRU);
332 *vpkru = xpkru->pkru;
335 /* Ensure that XCOMP_BV is set up for XSAVES */
336 xstate_init_xcomp_bv(&kstate->regs.xsave, kstate->xfeatures);
339 EXPORT_SYMBOL_GPL(fpu_copy_uabi_to_guest_fpstate);
340 #endif /* CONFIG_KVM */
342 void kernel_fpu_begin_mask(unsigned int kfpu_mask)
346 WARN_ON_FPU(!irq_fpu_usable());
347 WARN_ON_FPU(this_cpu_read(in_kernel_fpu));
349 this_cpu_write(in_kernel_fpu, true);
351 if (!(current->flags & PF_KTHREAD) &&
352 !test_thread_flag(TIF_NEED_FPU_LOAD)) {
353 set_thread_flag(TIF_NEED_FPU_LOAD);
354 save_fpregs_to_fpstate(¤t->thread.fpu);
356 __cpu_invalidate_fpregs_state();
358 /* Put sane initial values into the control registers. */
359 if (likely(kfpu_mask & KFPU_MXCSR) && boot_cpu_has(X86_FEATURE_XMM))
360 ldmxcsr(MXCSR_DEFAULT);
362 if (unlikely(kfpu_mask & KFPU_387) && boot_cpu_has(X86_FEATURE_FPU))
363 asm volatile ("fninit");
365 EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);
367 void kernel_fpu_end(void)
369 WARN_ON_FPU(!this_cpu_read(in_kernel_fpu));
371 this_cpu_write(in_kernel_fpu, false);
374 EXPORT_SYMBOL_GPL(kernel_fpu_end);
377 * Sync the FPU register state to current's memory register state when the
378 * current task owns the FPU. The hardware register state is preserved.
380 void fpu_sync_fpstate(struct fpu *fpu)
382 WARN_ON_FPU(fpu != ¤t->thread.fpu);
385 trace_x86_fpu_before_save(fpu);
387 if (!test_thread_flag(TIF_NEED_FPU_LOAD))
388 save_fpregs_to_fpstate(fpu);
390 trace_x86_fpu_after_save(fpu);
394 static inline unsigned int init_fpstate_copy_size(void)
397 return fpu_kernel_cfg.default_size;
399 /* XSAVE(S) just needs the legacy and the xstate header part */
400 return sizeof(init_fpstate.regs.xsave);
403 static inline void fpstate_init_fxstate(struct fpstate *fpstate)
405 fpstate->regs.fxsave.cwd = 0x37f;
406 fpstate->regs.fxsave.mxcsr = MXCSR_DEFAULT;
410 * Legacy x87 fpstate state init:
412 static inline void fpstate_init_fstate(struct fpstate *fpstate)
414 fpstate->regs.fsave.cwd = 0xffff037fu;
415 fpstate->regs.fsave.swd = 0xffff0000u;
416 fpstate->regs.fsave.twd = 0xffffffffu;
417 fpstate->regs.fsave.fos = 0xffff0000u;
421 * Used in two places:
422 * 1) Early boot to setup init_fpstate for non XSAVE systems
423 * 2) fpu_init_fpstate_user() which is invoked from KVM
425 void fpstate_init_user(struct fpstate *fpstate)
427 if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
428 fpstate_init_soft(&fpstate->regs.soft);
432 xstate_init_xcomp_bv(&fpstate->regs.xsave, fpstate->xfeatures);
434 if (cpu_feature_enabled(X86_FEATURE_FXSR))
435 fpstate_init_fxstate(fpstate);
437 fpstate_init_fstate(fpstate);
440 static void __fpstate_reset(struct fpstate *fpstate)
442 /* Initialize sizes and feature masks */
443 fpstate->size = fpu_kernel_cfg.default_size;
444 fpstate->user_size = fpu_user_cfg.default_size;
445 fpstate->xfeatures = fpu_kernel_cfg.default_features;
446 fpstate->user_xfeatures = fpu_user_cfg.default_features;
447 fpstate->xfd = init_fpstate.xfd;
450 void fpstate_reset(struct fpu *fpu)
452 /* Set the fpstate pointer to the default fpstate */
453 fpu->fpstate = &fpu->__fpstate;
454 __fpstate_reset(fpu->fpstate);
456 /* Initialize the permission related info in fpu */
457 fpu->perm.__state_perm = fpu_kernel_cfg.default_features;
458 fpu->perm.__state_size = fpu_kernel_cfg.default_size;
459 fpu->perm.__user_state_size = fpu_user_cfg.default_size;
462 static inline void fpu_inherit_perms(struct fpu *dst_fpu)
464 if (fpu_state_size_dynamic()) {
465 struct fpu *src_fpu = ¤t->group_leader->thread.fpu;
467 spin_lock_irq(¤t->sighand->siglock);
468 /* Fork also inherits the permissions of the parent */
469 dst_fpu->perm = src_fpu->perm;
470 spin_unlock_irq(¤t->sighand->siglock);
474 /* Clone current's FPU state on fork */
475 int fpu_clone(struct task_struct *dst, unsigned long clone_flags)
477 struct fpu *src_fpu = ¤t->thread.fpu;
478 struct fpu *dst_fpu = &dst->thread.fpu;
480 /* The new task's FPU state cannot be valid in the hardware. */
481 dst_fpu->last_cpu = -1;
483 fpstate_reset(dst_fpu);
485 if (!cpu_feature_enabled(X86_FEATURE_FPU))
489 * Enforce reload for user space tasks and prevent kernel threads
490 * from trying to save the FPU registers on context switch.
492 set_tsk_thread_flag(dst, TIF_NEED_FPU_LOAD);
495 * No FPU state inheritance for kernel threads and IO
498 if (dst->flags & (PF_KTHREAD | PF_IO_WORKER)) {
499 /* Clear out the minimal state */
500 memcpy(&dst_fpu->fpstate->regs, &init_fpstate.regs,
501 init_fpstate_copy_size());
506 * If a new feature is added, ensure all dynamic features are
507 * caller-saved from here!
509 BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);
512 * Save the default portion of the current FPU state into the
513 * clone. Assume all dynamic features to be defined as caller-
514 * saved, which enables skipping both the expansion of fpstate
515 * and the copying of any dynamic state.
517 * Do not use memcpy() when TIF_NEED_FPU_LOAD is set because
518 * copying is not valid when current uses non-default states.
521 if (test_thread_flag(TIF_NEED_FPU_LOAD))
522 fpregs_restore_userregs();
523 save_fpregs_to_fpstate(dst_fpu);
524 if (!(clone_flags & CLONE_THREAD))
525 fpu_inherit_perms(dst_fpu);
528 trace_x86_fpu_copy_src(src_fpu);
529 trace_x86_fpu_copy_dst(dst_fpu);
535 * Whitelist the FPU register state embedded into task_struct for hardened
538 void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size)
540 *offset = offsetof(struct thread_struct, fpu.__fpstate.regs);
541 *size = fpu_kernel_cfg.default_size;
545 * Drops current FPU state: deactivates the fpregs and
546 * the fpstate. NOTE: it still leaves previous contents
547 * in the fpregs in the eager-FPU case.
549 * This function can be used in cases where we know that
550 * a state-restore is coming: either an explicit one,
553 void fpu__drop(struct fpu *fpu)
557 if (fpu == ¤t->thread.fpu) {
558 /* Ignore delayed exceptions from user space */
559 asm volatile("1: fwait\n"
561 _ASM_EXTABLE(1b, 2b));
562 fpregs_deactivate(fpu);
565 trace_x86_fpu_dropped(fpu);
571 * Clear FPU registers by setting them up from the init fpstate.
572 * Caller must do fpregs_[un]lock() around it.
574 static inline void restore_fpregs_from_init_fpstate(u64 features_mask)
577 os_xrstor(&init_fpstate, features_mask);
579 fxrstor(&init_fpstate.regs.fxsave);
581 frstor(&init_fpstate.regs.fsave);
583 pkru_write_default();
587 * Reset current->fpu memory state to the init values.
589 static void fpu_reset_fpregs(void)
591 struct fpu *fpu = ¤t->thread.fpu;
596 * This does not change the actual hardware registers. It just
597 * resets the memory image and sets TIF_NEED_FPU_LOAD so a
598 * subsequent return to usermode will reload the registers from the
599 * task's memory image.
601 * Do not use fpstate_init() here. Just copy init_fpstate which has
602 * the correct content already except for PKRU.
604 * PKRU handling does not rely on the xstate when restoring for
605 * user space as PKRU is eagerly written in switch_to() and
608 memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size());
609 set_thread_flag(TIF_NEED_FPU_LOAD);
614 * Reset current's user FPU states to the init states. current's
615 * supervisor states, if any, are not modified by this function. The
616 * caller guarantees that the XSTATE header in memory is intact.
618 void fpu__clear_user_states(struct fpu *fpu)
620 WARN_ON_FPU(fpu != ¤t->thread.fpu);
623 if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
630 * Ensure that current's supervisor states are loaded into their
631 * corresponding registers.
633 if (xfeatures_mask_supervisor() &&
634 !fpregs_state_valid(fpu, smp_processor_id()))
635 os_xrstor_supervisor(fpu->fpstate);
637 /* Reset user states in registers. */
638 restore_fpregs_from_init_fpstate(XFEATURE_MASK_USER_RESTORE);
641 * Now all FPU registers have their desired values. Inform the FPU
642 * state machine that current's FPU registers are in the hardware
643 * registers. The memory image does not need to be updated because
644 * any operation relying on it has to save the registers first when
645 * current's FPU is marked active.
647 fpregs_mark_activate();
651 void fpu_flush_thread(void)
653 fpstate_reset(¤t->thread.fpu);
657 * Load FPU context before returning to userspace.
659 void switch_fpu_return(void)
661 if (!static_cpu_has(X86_FEATURE_FPU))
664 fpregs_restore_userregs();
666 EXPORT_SYMBOL_GPL(switch_fpu_return);
668 #ifdef CONFIG_X86_DEBUG_FPU
670 * If current FPU state according to its tracking (loaded FPU context on this
671 * CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is
672 * loaded on return to userland.
674 void fpregs_assert_state_consistent(void)
676 struct fpu *fpu = ¤t->thread.fpu;
678 if (test_thread_flag(TIF_NEED_FPU_LOAD))
681 WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));
683 EXPORT_SYMBOL_GPL(fpregs_assert_state_consistent);
686 void fpregs_mark_activate(void)
688 struct fpu *fpu = ¤t->thread.fpu;
690 fpregs_activate(fpu);
691 fpu->last_cpu = smp_processor_id();
692 clear_thread_flag(TIF_NEED_FPU_LOAD);
696 * x87 math exception handling:
699 int fpu__exception_code(struct fpu *fpu, int trap_nr)
703 if (trap_nr == X86_TRAP_MF) {
704 unsigned short cwd, swd;
706 * (~cwd & swd) will mask out exceptions that are not set to unmasked
707 * status. 0x3f is the exception bits in these regs, 0x200 is the
708 * C1 reg you need in case of a stack fault, 0x040 is the stack
709 * fault bit. We should only be taking one exception at a time,
710 * so if this combination doesn't produce any single exception,
711 * then we have a bad program that isn't synchronizing its FPU usage
712 * and it will suffer the consequences since we won't be able to
713 * fully reproduce the context of the exception.
715 if (boot_cpu_has(X86_FEATURE_FXSR)) {
716 cwd = fpu->fpstate->regs.fxsave.cwd;
717 swd = fpu->fpstate->regs.fxsave.swd;
719 cwd = (unsigned short)fpu->fpstate->regs.fsave.cwd;
720 swd = (unsigned short)fpu->fpstate->regs.fsave.swd;
726 * The SIMD FPU exceptions are handled a little differently, as there
727 * is only a single status/control register. Thus, to determine which
728 * unmasked exception was caught we must mask the exception mask bits
729 * at 0x1f80, and then use these to mask the exception bits at 0x3f.
731 unsigned short mxcsr = MXCSR_DEFAULT;
733 if (boot_cpu_has(X86_FEATURE_XMM))
734 mxcsr = fpu->fpstate->regs.fxsave.mxcsr;
736 err = ~(mxcsr >> 7) & mxcsr;
739 if (err & 0x001) { /* Invalid op */
741 * swd & 0x240 == 0x040: Stack Underflow
742 * swd & 0x240 == 0x240: Stack Overflow
743 * User must clear the SF bit (0x40) if set
746 } else if (err & 0x004) { /* Divide by Zero */
748 } else if (err & 0x008) { /* Overflow */
750 } else if (err & 0x012) { /* Denormal, Underflow */
752 } else if (err & 0x020) { /* Precision */
757 * If we're using IRQ 13, or supposedly even some trap
758 * X86_TRAP_MF implementations, it's possible
759 * we get a spurious trap, which is not an error.