// SPDX-License-Identifier: GPL-2.0-only1/*2* Copyright (C) 1994 Linus Torvalds3*4* Pentium III FXSR, SSE support5* General FPU state handling cleanups6* Gareth Hughes <[email protected]>, May 20007*/8#include <asm/fpu/api.h>9#include <asm/fpu/regset.h>10#include <asm/fpu/sched.h>11#include <asm/fpu/signal.h>12#include <asm/fpu/types.h>13#include <asm/msr.h>14#include <asm/traps.h>15#include <asm/irq_regs.h>1617#include <uapi/asm/kvm.h>1819#include <linux/hardirq.h>20#include <linux/kvm_types.h>21#include <linux/pkeys.h>22#include <linux/vmalloc.h>2324#include "context.h"25#include "internal.h"26#include "legacy.h"27#include "xstate.h"2829#define CREATE_TRACE_POINTS30#include <asm/trace/fpu.h>3132#ifdef CONFIG_X86_6433DEFINE_STATIC_KEY_FALSE(__fpu_state_size_dynamic);34DEFINE_PER_CPU(u64, xfd_state);35#endif3637/* The FPU state configuration data for kernel and user space */38struct fpu_state_config fpu_kernel_cfg __ro_after_init;39struct fpu_state_config fpu_user_cfg __ro_after_init;40struct vcpu_fpu_config guest_default_cfg __ro_after_init;4142/*43* Represents the initial FPU state. It's mostly (but not completely) zeroes,44* depending on the FPU hardware format:45*/46struct fpstate init_fpstate __ro_after_init;4748/*49* Track FPU initialization and kernel-mode usage. 'true' means the FPU is50* initialized and is not currently being used by the kernel:51*/52DEFINE_PER_CPU(bool, kernel_fpu_allowed);5354/*55* Track which context is using the FPU on the CPU:56*/57DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);5859#ifdef CONFIG_X86_DEBUG_FPU60struct fpu *x86_task_fpu(struct task_struct *task)61{62if (WARN_ON_ONCE(task->flags & PF_KTHREAD))63return NULL;6465return (void *)task + sizeof(*task);66}67#endif6869/*70* Can we use the FPU in kernel mode with the71* whole "kernel_fpu_begin/end()" sequence?72*/73bool irq_fpu_usable(void)74{75if (WARN_ON_ONCE(in_nmi()))76return false;7778/*79* Return false in the following cases:80*81* - FPU is not yet initialized. This can happen only when the call is82* coming from CPU onlining, for example for microcode checksumming.83* - The kernel is already using the FPU, either because of explicit84* nesting (which should never be done), or because of implicit85* nesting when a hardirq interrupted a kernel-mode FPU section.86*87* The single boolean check below handles both cases:88*/89if (!this_cpu_read(kernel_fpu_allowed))90return false;9192/*93* When not in NMI or hard interrupt context, FPU can be used in:94*95* - Task context except from within fpregs_lock()'ed critical96* regions.97*98* - Soft interrupt processing context which cannot happen99* while in a fpregs_lock()'ed critical region.100*/101if (!in_hardirq())102return true;103104/*105* In hard interrupt context it's safe when soft interrupts106* are enabled, which means the interrupt did not hit in107* a fpregs_lock()'ed critical region.108*/109return !softirq_count();110}111EXPORT_SYMBOL(irq_fpu_usable);112113/*114* Track AVX512 state use because it is known to slow the max clock115* speed of the core.116*/117static void update_avx_timestamp(struct fpu *fpu)118{119120#define AVX512_TRACKING_MASK (XFEATURE_MASK_ZMM_Hi256 | XFEATURE_MASK_Hi16_ZMM)121122if (fpu->fpstate->regs.xsave.header.xfeatures & AVX512_TRACKING_MASK)123fpu->avx512_timestamp = jiffies;124}125126/*127* Save the FPU register state in fpu->fpstate->regs. The register state is128* preserved.129*130* Must be called with fpregs_lock() held.131*132* The legacy FNSAVE instruction clears all FPU state unconditionally, so133* register state has to be reloaded. That might be a pointless exercise134* when the FPU is going to be used by another task right after that. But135* this only affects 20+ years old 32bit systems and avoids conditionals all136* over the place.137*138* FXSAVE and all XSAVE variants preserve the FPU register state.139*/140void save_fpregs_to_fpstate(struct fpu *fpu)141{142if (likely(use_xsave())) {143os_xsave(fpu->fpstate);144update_avx_timestamp(fpu);145return;146}147148if (likely(use_fxsr())) {149fxsave(&fpu->fpstate->regs.fxsave);150return;151}152153/*154* Legacy FPU register saving, FNSAVE always clears FPU registers,155* so we have to reload them from the memory state.156*/157asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->fpstate->regs.fsave));158frstor(&fpu->fpstate->regs.fsave);159}160161void restore_fpregs_from_fpstate(struct fpstate *fpstate, u64 mask)162{163/*164* AMD K7/K8 and later CPUs up to Zen don't save/restore165* FDP/FIP/FOP unless an exception is pending. Clear the x87 state166* here by setting it to fixed values. "m" is a random variable167* that should be in L1.168*/169if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {170asm volatile(171"fnclex\n\t"172"emms\n\t"173"fildl %[addr]" /* set F?P to defined value */174: : [addr] "m" (*fpstate));175}176177if (use_xsave()) {178/*179* Dynamically enabled features are enabled in XCR0, but180* usage requires also that the corresponding bits in XFD181* are cleared. If the bits are set then using a related182* instruction will raise #NM. This allows to do the183* allocation of the larger FPU buffer lazy from #NM or if184* the task has no permission to kill it which would happen185* via #UD if the feature is disabled in XCR0.186*187* XFD state is following the same life time rules as188* XSTATE and to restore state correctly XFD has to be189* updated before XRSTORS otherwise the component would190* stay in or go into init state even if the bits are set191* in fpstate::regs::xsave::xfeatures.192*/193xfd_update_state(fpstate);194195/*196* Restoring state always needs to modify all features197* which are in @mask even if the current task cannot use198* extended features.199*200* So fpstate->xfeatures cannot be used here, because then201* a feature for which the task has no permission but was202* used by the previous task would not go into init state.203*/204mask = fpu_kernel_cfg.max_features & mask;205206os_xrstor(fpstate, mask);207} else {208if (use_fxsr())209fxrstor(&fpstate->regs.fxsave);210else211frstor(&fpstate->regs.fsave);212}213}214215void fpu_reset_from_exception_fixup(void)216{217restore_fpregs_from_fpstate(&init_fpstate, XFEATURE_MASK_FPSTATE);218}219220#if IS_ENABLED(CONFIG_KVM)221static void __fpstate_reset(struct fpstate *fpstate);222223static void fpu_lock_guest_permissions(void)224{225struct fpu_state_perm *fpuperm;226u64 perm;227228if (!IS_ENABLED(CONFIG_X86_64))229return;230231spin_lock_irq(¤t->sighand->siglock);232fpuperm = &x86_task_fpu(current->group_leader)->guest_perm;233perm = fpuperm->__state_perm;234235/* First fpstate allocation locks down permissions. */236WRITE_ONCE(fpuperm->__state_perm, perm | FPU_GUEST_PERM_LOCKED);237238spin_unlock_irq(¤t->sighand->siglock);239}240241bool fpu_alloc_guest_fpstate(struct fpu_guest *gfpu)242{243struct fpstate *fpstate;244unsigned int size;245246size = guest_default_cfg.size + ALIGN(offsetof(struct fpstate, regs), 64);247248fpstate = vzalloc(size);249if (!fpstate)250return false;251252/* Initialize indicators to reflect properties of the fpstate */253fpstate->is_valloc = true;254fpstate->is_guest = true;255256__fpstate_reset(fpstate);257fpstate_init_user(fpstate);258259gfpu->fpstate = fpstate;260gfpu->xfeatures = guest_default_cfg.features;261262/*263* KVM sets the FP+SSE bits in the XSAVE header when copying FPU state264* to userspace, even when XSAVE is unsupported, so that restoring FPU265* state on a different CPU that does support XSAVE can cleanly load266* the incoming state using its natural XSAVE. In other words, KVM's267* uABI size may be larger than this host's default size. Conversely,268* the default size should never be larger than KVM's base uABI size;269* all features that can expand the uABI size must be opt-in.270*/271gfpu->uabi_size = sizeof(struct kvm_xsave);272if (WARN_ON_ONCE(fpu_user_cfg.default_size > gfpu->uabi_size))273gfpu->uabi_size = fpu_user_cfg.default_size;274275fpu_lock_guest_permissions();276277return true;278}279EXPORT_SYMBOL_FOR_KVM(fpu_alloc_guest_fpstate);280281void fpu_free_guest_fpstate(struct fpu_guest *gfpu)282{283struct fpstate *fpstate = gfpu->fpstate;284285if (!fpstate)286return;287288if (WARN_ON_ONCE(!fpstate->is_valloc || !fpstate->is_guest || fpstate->in_use))289return;290291gfpu->fpstate = NULL;292vfree(fpstate);293}294EXPORT_SYMBOL_FOR_KVM(fpu_free_guest_fpstate);295296/*297* fpu_enable_guest_xfd_features - Check xfeatures against guest perm and enable298* @guest_fpu: Pointer to the guest FPU container299* @xfeatures: Features requested by guest CPUID300*301* Enable all dynamic xfeatures according to guest perm and requested CPUID.302*303* Return: 0 on success, error code otherwise304*/305int fpu_enable_guest_xfd_features(struct fpu_guest *guest_fpu, u64 xfeatures)306{307lockdep_assert_preemption_enabled();308309/* Nothing to do if all requested features are already enabled. */310xfeatures &= ~guest_fpu->xfeatures;311if (!xfeatures)312return 0;313314return __xfd_enable_feature(xfeatures, guest_fpu);315}316EXPORT_SYMBOL_FOR_KVM(fpu_enable_guest_xfd_features);317318#ifdef CONFIG_X86_64319void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd)320{321struct fpstate *fpstate = guest_fpu->fpstate;322323fpregs_lock();324325/*326* KVM's guest ABI is that setting XFD[i]=1 *can* immediately revert the327* save state to its initial configuration. Likewise, KVM_GET_XSAVE does328* the same as XSAVE and returns XSTATE_BV[i]=0 whenever XFD[i]=1.329*330* If the guest's FPU state is in hardware, just update XFD: the XSAVE331* in fpu_swap_kvm_fpstate will clear XSTATE_BV[i] whenever XFD[i]=1.332*333* If however the guest's FPU state is NOT resident in hardware, clear334* disabled components in XSTATE_BV now, or a subsequent XRSTOR will335* attempt to load disabled components and generate #NM _in the host_.336*/337if (xfd && test_thread_flag(TIF_NEED_FPU_LOAD))338fpstate->regs.xsave.header.xfeatures &= ~xfd;339340fpstate->xfd = xfd;341if (fpstate->in_use)342xfd_update_state(fpstate);343344fpregs_unlock();345}346EXPORT_SYMBOL_FOR_KVM(fpu_update_guest_xfd);347348/**349* fpu_sync_guest_vmexit_xfd_state - Synchronize XFD MSR and software state350*351* Must be invoked from KVM after a VMEXIT before enabling interrupts when352* XFD write emulation is disabled. This is required because the guest can353* freely modify XFD and the state at VMEXIT is not guaranteed to be the354* same as the state on VMENTER. So software state has to be updated before355* any operation which depends on it can take place.356*357* Note: It can be invoked unconditionally even when write emulation is358* enabled for the price of a then pointless MSR read.359*/360void fpu_sync_guest_vmexit_xfd_state(void)361{362struct fpstate *fpstate = x86_task_fpu(current)->fpstate;363364lockdep_assert_irqs_disabled();365if (fpu_state_size_dynamic()) {366rdmsrq(MSR_IA32_XFD, fpstate->xfd);367__this_cpu_write(xfd_state, fpstate->xfd);368}369}370EXPORT_SYMBOL_FOR_KVM(fpu_sync_guest_vmexit_xfd_state);371#endif /* CONFIG_X86_64 */372373int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest)374{375struct fpstate *guest_fps = guest_fpu->fpstate;376struct fpu *fpu = x86_task_fpu(current);377struct fpstate *cur_fps = fpu->fpstate;378379fpregs_lock();380if (!cur_fps->is_confidential && !test_thread_flag(TIF_NEED_FPU_LOAD))381save_fpregs_to_fpstate(fpu);382383/* Swap fpstate */384if (enter_guest) {385fpu->__task_fpstate = cur_fps;386fpu->fpstate = guest_fps;387guest_fps->in_use = true;388} else {389guest_fps->in_use = false;390fpu->fpstate = fpu->__task_fpstate;391fpu->__task_fpstate = NULL;392}393394cur_fps = fpu->fpstate;395396if (!cur_fps->is_confidential) {397/* Includes XFD update */398restore_fpregs_from_fpstate(cur_fps, XFEATURE_MASK_FPSTATE);399} else {400/*401* XSTATE is restored by firmware from encrypted402* memory. Make sure XFD state is correct while403* running with guest fpstate404*/405xfd_update_state(cur_fps);406}407408fpregs_mark_activate();409fpregs_unlock();410return 0;411}412EXPORT_SYMBOL_FOR_KVM(fpu_swap_kvm_fpstate);413414void fpu_copy_guest_fpstate_to_uabi(struct fpu_guest *gfpu, void *buf,415unsigned int size, u64 xfeatures, u32 pkru)416{417struct fpstate *kstate = gfpu->fpstate;418union fpregs_state *ustate = buf;419struct membuf mb = { .p = buf, .left = size };420421if (cpu_feature_enabled(X86_FEATURE_XSAVE)) {422__copy_xstate_to_uabi_buf(mb, kstate, xfeatures, pkru,423XSTATE_COPY_XSAVE);424} else {425memcpy(&ustate->fxsave, &kstate->regs.fxsave,426sizeof(ustate->fxsave));427/* Make it restorable on a XSAVE enabled host */428ustate->xsave.header.xfeatures = XFEATURE_MASK_FPSSE;429}430}431EXPORT_SYMBOL_FOR_KVM(fpu_copy_guest_fpstate_to_uabi);432433int fpu_copy_uabi_to_guest_fpstate(struct fpu_guest *gfpu, const void *buf,434u64 xcr0, u32 *vpkru)435{436struct fpstate *kstate = gfpu->fpstate;437const union fpregs_state *ustate = buf;438439if (!cpu_feature_enabled(X86_FEATURE_XSAVE)) {440if (ustate->xsave.header.xfeatures & ~XFEATURE_MASK_FPSSE)441return -EINVAL;442if (ustate->fxsave.mxcsr & ~mxcsr_feature_mask)443return -EINVAL;444memcpy(&kstate->regs.fxsave, &ustate->fxsave, sizeof(ustate->fxsave));445return 0;446}447448if (ustate->xsave.header.xfeatures & ~xcr0)449return -EINVAL;450451/*452* Disabled features must be in their initial state, otherwise XRSTOR453* causes an exception.454*/455if (WARN_ON_ONCE(ustate->xsave.header.xfeatures & kstate->xfd))456return -EINVAL;457458/*459* Nullify @vpkru to preserve its current value if PKRU's bit isn't set460* in the header. KVM's odd ABI is to leave PKRU untouched in this461* case (all other components are eventually re-initialized).462*/463if (!(ustate->xsave.header.xfeatures & XFEATURE_MASK_PKRU))464vpkru = NULL;465466return copy_uabi_from_kernel_to_xstate(kstate, ustate, vpkru);467}468EXPORT_SYMBOL_FOR_KVM(fpu_copy_uabi_to_guest_fpstate);469#endif /* CONFIG_KVM */470471void kernel_fpu_begin_mask(unsigned int kfpu_mask)472{473if (!irqs_disabled())474fpregs_lock();475476WARN_ON_FPU(!irq_fpu_usable());477478/* Toggle kernel_fpu_allowed to false: */479WARN_ON_FPU(!this_cpu_read(kernel_fpu_allowed));480this_cpu_write(kernel_fpu_allowed, false);481482if (!(current->flags & (PF_KTHREAD | PF_USER_WORKER)) &&483!test_thread_flag(TIF_NEED_FPU_LOAD)) {484set_thread_flag(TIF_NEED_FPU_LOAD);485save_fpregs_to_fpstate(x86_task_fpu(current));486}487__cpu_invalidate_fpregs_state();488489/* Put sane initial values into the control registers. */490if (likely(kfpu_mask & KFPU_MXCSR) && boot_cpu_has(X86_FEATURE_XMM))491ldmxcsr(MXCSR_DEFAULT);492493if (unlikely(kfpu_mask & KFPU_387) && boot_cpu_has(X86_FEATURE_FPU))494asm volatile ("fninit");495}496EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);497498void kernel_fpu_end(void)499{500/* Toggle kernel_fpu_allowed back to true: */501WARN_ON_FPU(this_cpu_read(kernel_fpu_allowed));502this_cpu_write(kernel_fpu_allowed, true);503504if (!irqs_disabled())505fpregs_unlock();506}507EXPORT_SYMBOL_GPL(kernel_fpu_end);508509/*510* Sync the FPU register state to current's memory register state when the511* current task owns the FPU. The hardware register state is preserved.512*/513void fpu_sync_fpstate(struct fpu *fpu)514{515WARN_ON_FPU(fpu != x86_task_fpu(current));516517fpregs_lock();518trace_x86_fpu_before_save(fpu);519520if (!test_thread_flag(TIF_NEED_FPU_LOAD))521save_fpregs_to_fpstate(fpu);522523trace_x86_fpu_after_save(fpu);524fpregs_unlock();525}526527static inline unsigned int init_fpstate_copy_size(void)528{529if (!use_xsave())530return fpu_kernel_cfg.default_size;531532/* XSAVE(S) just needs the legacy and the xstate header part */533return sizeof(init_fpstate.regs.xsave);534}535536static inline void fpstate_init_fxstate(struct fpstate *fpstate)537{538fpstate->regs.fxsave.cwd = 0x37f;539fpstate->regs.fxsave.mxcsr = MXCSR_DEFAULT;540}541542/*543* Legacy x87 fpstate state init:544*/545static inline void fpstate_init_fstate(struct fpstate *fpstate)546{547fpstate->regs.fsave.cwd = 0xffff037fu;548fpstate->regs.fsave.swd = 0xffff0000u;549fpstate->regs.fsave.twd = 0xffffffffu;550fpstate->regs.fsave.fos = 0xffff0000u;551}552553/*554* Used in two places:555* 1) Early boot to setup init_fpstate for non XSAVE systems556* 2) fpu_alloc_guest_fpstate() which is invoked from KVM557*/558void fpstate_init_user(struct fpstate *fpstate)559{560if (!cpu_feature_enabled(X86_FEATURE_FPU)) {561fpstate_init_soft(&fpstate->regs.soft);562return;563}564565xstate_init_xcomp_bv(&fpstate->regs.xsave, fpstate->xfeatures);566567if (cpu_feature_enabled(X86_FEATURE_FXSR))568fpstate_init_fxstate(fpstate);569else570fpstate_init_fstate(fpstate);571}572573static void __fpstate_reset(struct fpstate *fpstate)574{575/*576* Supervisor features (and thus sizes) may diverge between guest577* FPUs and host FPUs, as some supervisor features are supported578* for guests despite not being utilized by the host. User579* features and sizes are always identical, which allows for580* common guest and userspace ABI.581*582* For the host, set XFD to the kernel's desired initialization583* value. For guests, set XFD to its architectural RESET value.584*/585if (fpstate->is_guest) {586fpstate->size = guest_default_cfg.size;587fpstate->xfeatures = guest_default_cfg.features;588fpstate->xfd = 0;589} else {590fpstate->size = fpu_kernel_cfg.default_size;591fpstate->xfeatures = fpu_kernel_cfg.default_features;592fpstate->xfd = init_fpstate.xfd;593}594595fpstate->user_size = fpu_user_cfg.default_size;596fpstate->user_xfeatures = fpu_user_cfg.default_features;597}598599void fpstate_reset(struct fpu *fpu)600{601/* Set the fpstate pointer to the default fpstate */602fpu->fpstate = &fpu->__fpstate;603__fpstate_reset(fpu->fpstate);604605/* Initialize the permission related info in fpu */606fpu->perm.__state_perm = fpu_kernel_cfg.default_features;607fpu->perm.__state_size = fpu_kernel_cfg.default_size;608fpu->perm.__user_state_size = fpu_user_cfg.default_size;609610fpu->guest_perm.__state_perm = guest_default_cfg.features;611fpu->guest_perm.__state_size = guest_default_cfg.size;612/*613* User features and sizes are always identical between host and614* guest FPUs, which allows for common guest and userspace ABI.615*/616fpu->guest_perm.__user_state_size = fpu_user_cfg.default_size;617}618619static inline void fpu_inherit_perms(struct fpu *dst_fpu)620{621if (fpu_state_size_dynamic()) {622struct fpu *src_fpu = x86_task_fpu(current->group_leader);623624spin_lock_irq(¤t->sighand->siglock);625/* Fork also inherits the permissions of the parent */626dst_fpu->perm = src_fpu->perm;627dst_fpu->guest_perm = src_fpu->guest_perm;628spin_unlock_irq(¤t->sighand->siglock);629}630}631632/* A passed ssp of zero will not cause any update */633static int update_fpu_shstk(struct task_struct *dst, unsigned long ssp)634{635#ifdef CONFIG_X86_USER_SHADOW_STACK636struct cet_user_state *xstate;637638/* If ssp update is not needed. */639if (!ssp)640return 0;641642xstate = get_xsave_addr(&x86_task_fpu(dst)->fpstate->regs.xsave,643XFEATURE_CET_USER);644645/*646* If there is a non-zero ssp, then 'dst' must be configured with a shadow647* stack and the fpu state should be up to date since it was just copied648* from the parent in fpu_clone(). So there must be a valid non-init CET649* state location in the buffer.650*/651if (WARN_ON_ONCE(!xstate))652return 1;653654xstate->user_ssp = (u64)ssp;655#endif656return 0;657}658659/* Clone current's FPU state on fork */660int fpu_clone(struct task_struct *dst, u64 clone_flags, bool minimal,661unsigned long ssp)662{663/*664* We allocate the new FPU structure right after the end of the task struct.665* task allocation size already took this into account.666*667* This is safe because task_struct size is a multiple of cacheline size,668* thus x86_task_fpu() will always be cacheline aligned as well.669*/670struct fpu *dst_fpu = (void *)dst + sizeof(*dst);671672BUILD_BUG_ON(sizeof(*dst) % SMP_CACHE_BYTES != 0);673674/* The new task's FPU state cannot be valid in the hardware. */675dst_fpu->last_cpu = -1;676677fpstate_reset(dst_fpu);678679if (!cpu_feature_enabled(X86_FEATURE_FPU))680return 0;681682/*683* Enforce reload for user space tasks and prevent kernel threads684* from trying to save the FPU registers on context switch.685*/686set_tsk_thread_flag(dst, TIF_NEED_FPU_LOAD);687688/*689* No FPU state inheritance for kernel threads and IO690* worker threads.691*/692if (minimal) {693/* Clear out the minimal state */694memcpy(&dst_fpu->fpstate->regs, &init_fpstate.regs,695init_fpstate_copy_size());696return 0;697}698699/*700* If a new feature is added, ensure all dynamic features are701* caller-saved from here!702*/703BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);704705/*706* Save the default portion of the current FPU state into the707* clone. Assume all dynamic features to be defined as caller-708* saved, which enables skipping both the expansion of fpstate709* and the copying of any dynamic state.710*711* Do not use memcpy() when TIF_NEED_FPU_LOAD is set because712* copying is not valid when current uses non-default states.713*/714fpregs_lock();715if (test_thread_flag(TIF_NEED_FPU_LOAD))716fpregs_restore_userregs();717save_fpregs_to_fpstate(dst_fpu);718fpregs_unlock();719if (!(clone_flags & CLONE_THREAD))720fpu_inherit_perms(dst_fpu);721722/*723* Children never inherit PASID state.724* Force it to have its init value:725*/726if (use_xsave())727dst_fpu->fpstate->regs.xsave.header.xfeatures &= ~XFEATURE_MASK_PASID;728729/*730* Update shadow stack pointer, in case it changed during clone.731*/732if (update_fpu_shstk(dst, ssp))733return 1;734735trace_x86_fpu_copy_dst(dst_fpu);736737return 0;738}739740/*741* While struct fpu is no longer part of struct thread_struct, it is still742* allocated after struct task_struct in the "task_struct" kmem cache. But743* since FPU is expected to be part of struct thread_struct, we have to744* adjust for it here.745*/746void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size)747{748/* The allocation follows struct task_struct. */749*offset = sizeof(struct task_struct) - offsetof(struct task_struct, thread);750*offset += offsetof(struct fpu, __fpstate.regs);751*size = fpu_kernel_cfg.default_size;752}753754/*755* Drops current FPU state: deactivates the fpregs and756* the fpstate. NOTE: it still leaves previous contents757* in the fpregs in the eager-FPU case.758*759* This function can be used in cases where we know that760* a state-restore is coming: either an explicit one,761* or a reschedule.762*/763void fpu__drop(struct task_struct *tsk)764{765struct fpu *fpu;766767if (test_tsk_thread_flag(tsk, TIF_NEED_FPU_LOAD))768return;769770fpu = x86_task_fpu(tsk);771772preempt_disable();773774if (fpu == x86_task_fpu(current)) {775/* Ignore delayed exceptions from user space */776asm volatile("1: fwait\n"777"2:\n"778_ASM_EXTABLE(1b, 2b));779fpregs_deactivate(fpu);780}781782trace_x86_fpu_dropped(fpu);783784preempt_enable();785}786787/*788* Clear FPU registers by setting them up from the init fpstate.789* Caller must do fpregs_[un]lock() around it.790*/791static inline void restore_fpregs_from_init_fpstate(u64 features_mask)792{793if (use_xsave())794os_xrstor(&init_fpstate, features_mask);795else if (use_fxsr())796fxrstor(&init_fpstate.regs.fxsave);797else798frstor(&init_fpstate.regs.fsave);799800pkru_write_default();801}802803/*804* Reset current->fpu memory state to the init values.805*/806static void fpu_reset_fpstate_regs(void)807{808struct fpu *fpu = x86_task_fpu(current);809810fpregs_lock();811__fpu_invalidate_fpregs_state(fpu);812/*813* This does not change the actual hardware registers. It just814* resets the memory image and sets TIF_NEED_FPU_LOAD so a815* subsequent return to usermode will reload the registers from the816* task's memory image.817*818* Do not use fpstate_init() here. Just copy init_fpstate which has819* the correct content already except for PKRU.820*821* PKRU handling does not rely on the xstate when restoring for822* user space as PKRU is eagerly written in switch_to() and823* flush_thread().824*/825memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size());826set_thread_flag(TIF_NEED_FPU_LOAD);827fpregs_unlock();828}829830/*831* Reset current's user FPU states to the init states. current's832* supervisor states, if any, are not modified by this function. The833* caller guarantees that the XSTATE header in memory is intact.834*/835void fpu__clear_user_states(struct fpu *fpu)836{837WARN_ON_FPU(fpu != x86_task_fpu(current));838839fpregs_lock();840if (!cpu_feature_enabled(X86_FEATURE_FPU)) {841fpu_reset_fpstate_regs();842fpregs_unlock();843return;844}845846/*847* Ensure that current's supervisor states are loaded into their848* corresponding registers.849*/850if (xfeatures_mask_supervisor() &&851!fpregs_state_valid(fpu, smp_processor_id()))852os_xrstor_supervisor(fpu->fpstate);853854/* Ensure XFD state is in sync before reloading XSTATE */855xfd_update_state(fpu->fpstate);856857/* Reset user states in registers. */858restore_fpregs_from_init_fpstate(XFEATURE_MASK_USER_RESTORE);859860/*861* Now all FPU registers have their desired values. Inform the FPU862* state machine that current's FPU registers are in the hardware863* registers. The memory image does not need to be updated because864* any operation relying on it has to save the registers first when865* current's FPU is marked active.866*/867fpregs_mark_activate();868fpregs_unlock();869}870871void fpu_flush_thread(void)872{873fpstate_reset(x86_task_fpu(current));874fpu_reset_fpstate_regs();875}876/*877* Load FPU context before returning to userspace.878*/879void switch_fpu_return(void)880{881if (!static_cpu_has(X86_FEATURE_FPU))882return;883884fpregs_restore_userregs();885}886EXPORT_SYMBOL_FOR_KVM(switch_fpu_return);887888void fpregs_lock_and_load(void)889{890/*891* fpregs_lock() only disables preemption (mostly). So modifying state892* in an interrupt could screw up some in progress fpregs operation.893* Warn about it.894*/895WARN_ON_ONCE(!irq_fpu_usable());896WARN_ON_ONCE(current->flags & PF_KTHREAD);897898fpregs_lock();899900fpregs_assert_state_consistent();901902if (test_thread_flag(TIF_NEED_FPU_LOAD))903fpregs_restore_userregs();904}905906#ifdef CONFIG_X86_DEBUG_FPU907/*908* If current FPU state according to its tracking (loaded FPU context on this909* CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is910* loaded on return to userland.911*/912void fpregs_assert_state_consistent(void)913{914struct fpu *fpu = x86_task_fpu(current);915916if (test_thread_flag(TIF_NEED_FPU_LOAD))917return;918919WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));920}921EXPORT_SYMBOL_FOR_KVM(fpregs_assert_state_consistent);922#endif923924void fpregs_mark_activate(void)925{926struct fpu *fpu = x86_task_fpu(current);927928fpregs_activate(fpu);929fpu->last_cpu = smp_processor_id();930clear_thread_flag(TIF_NEED_FPU_LOAD);931}932933/*934* x87 math exception handling:935*/936937int fpu__exception_code(struct fpu *fpu, int trap_nr)938{939int err;940941if (trap_nr == X86_TRAP_MF) {942unsigned short cwd, swd;943/*944* (~cwd & swd) will mask out exceptions that are not set to unmasked945* status. 0x3f is the exception bits in these regs, 0x200 is the946* C1 reg you need in case of a stack fault, 0x040 is the stack947* fault bit. We should only be taking one exception at a time,948* so if this combination doesn't produce any single exception,949* then we have a bad program that isn't synchronizing its FPU usage950* and it will suffer the consequences since we won't be able to951* fully reproduce the context of the exception.952*/953if (boot_cpu_has(X86_FEATURE_FXSR)) {954cwd = fpu->fpstate->regs.fxsave.cwd;955swd = fpu->fpstate->regs.fxsave.swd;956} else {957cwd = (unsigned short)fpu->fpstate->regs.fsave.cwd;958swd = (unsigned short)fpu->fpstate->regs.fsave.swd;959}960961err = swd & ~cwd;962} else {963/*964* The SIMD FPU exceptions are handled a little differently, as there965* is only a single status/control register. Thus, to determine which966* unmasked exception was caught we must mask the exception mask bits967* at 0x1f80, and then use these to mask the exception bits at 0x3f.968*/969unsigned short mxcsr = MXCSR_DEFAULT;970971if (boot_cpu_has(X86_FEATURE_XMM))972mxcsr = fpu->fpstate->regs.fxsave.mxcsr;973974err = ~(mxcsr >> 7) & mxcsr;975}976977if (err & 0x001) { /* Invalid op */978/*979* swd & 0x240 == 0x040: Stack Underflow980* swd & 0x240 == 0x240: Stack Overflow981* User must clear the SF bit (0x40) if set982*/983return FPE_FLTINV;984} else if (err & 0x004) { /* Divide by Zero */985return FPE_FLTDIV;986} else if (err & 0x008) { /* Overflow */987return FPE_FLTOVF;988} else if (err & 0x012) { /* Denormal, Underflow */989return FPE_FLTUND;990} else if (err & 0x020) { /* Precision */991return FPE_FLTRES;992}993994/*995* If we're using IRQ 13, or supposedly even some trap996* X86_TRAP_MF implementations, it's possible997* we get a spurious trap, which is not an error.998*/999return 0;1000}10011002/*1003* Initialize register state that may prevent from entering low-power idle.1004* This function will be invoked from the cpuidle driver only when needed.1005*/1006noinstr void fpu_idle_fpregs(void)1007{1008/* Note: AMX_TILE being enabled implies XGETBV1 support */1009if (cpu_feature_enabled(X86_FEATURE_AMX_TILE) &&1010(xfeatures_in_use() & XFEATURE_MASK_XTILE)) {1011tile_release();1012__this_cpu_write(fpu_fpregs_owner_ctx, NULL);1013}1014}101510161017