/* SPDX-License-Identifier: GPL-2.0 */1#ifndef __X86_KERNEL_FPU_CONTEXT_H2#define __X86_KERNEL_FPU_CONTEXT_H34#include <asm/fpu/xstate.h>5#include <asm/trace/fpu.h>67/* Functions related to FPU context tracking */89/*10* The in-register FPU state for an FPU context on a CPU is assumed to be11* valid if the fpu->last_cpu matches the CPU, and the fpu_fpregs_owner_ctx12* matches the FPU.13*14* If the FPU register state is valid, the kernel can skip restoring the15* FPU state from memory.16*17* Any code that clobbers the FPU registers or updates the in-memory18* FPU state for a task MUST let the rest of the kernel know that the19* FPU registers are no longer valid for this task.20*21* Invalidate a resource you control: CPU if using the CPU for something else22* (with preemption disabled), FPU for the current task, or a task that23* is prevented from running by the current task.24*/25static inline void __cpu_invalidate_fpregs_state(void)26{27__this_cpu_write(fpu_fpregs_owner_ctx, NULL);28}2930static inline void __fpu_invalidate_fpregs_state(struct fpu *fpu)31{32fpu->last_cpu = -1;33}3435static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)36{37return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;38}3940static inline void fpregs_deactivate(struct fpu *fpu)41{42__this_cpu_write(fpu_fpregs_owner_ctx, NULL);43trace_x86_fpu_regs_deactivated(fpu);44}4546static inline void fpregs_activate(struct fpu *fpu)47{48__this_cpu_write(fpu_fpregs_owner_ctx, fpu);49trace_x86_fpu_regs_activated(fpu);50}5152/* Internal helper for switch_fpu_return() and signal frame setup */53static inline void fpregs_restore_userregs(void)54{55struct fpu *fpu = x86_task_fpu(current);56int cpu = smp_processor_id();5758if (WARN_ON_ONCE(current->flags & (PF_KTHREAD | PF_USER_WORKER)))59return;6061if (!fpregs_state_valid(fpu, cpu)) {62/*63* This restores _all_ xstate which has not been64* established yet.65*66* If PKRU is enabled, then the PKRU value is already67* correct because it was either set in switch_to() or in68* flush_thread(). So it is excluded because it might be69* not up to date in current->thread.fpu->xsave state.70*71* XFD state is handled in restore_fpregs_from_fpstate().72*/73restore_fpregs_from_fpstate(fpu->fpstate, XFEATURE_MASK_FPSTATE);7475fpregs_activate(fpu);76fpu->last_cpu = cpu;77}78clear_thread_flag(TIF_NEED_FPU_LOAD);79}8081#endif828384