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/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/msr.h>
15#include <asm/traps.h>
16#include <asm/irq_regs.h>
17
18#include <uapi/asm/kvm.h>
19
20#include <linux/hardirq.h>
21#include <linux/kvm_types.h>
22#include <linux/pkeys.h>
23#include <linux/vmalloc.h>
24
25#include "context.h"
26#include "internal.h"
27#include "legacy.h"
28#include "xstate.h"
29
30#define CREATE_TRACE_POINTS
31#include <asm/trace/fpu.h>
32
33#ifdef CONFIG_X86_64
34DEFINE_STATIC_KEY_FALSE(__fpu_state_size_dynamic);
35DEFINE_PER_CPU(u64, xfd_state);
36#endif
37
38/* The FPU state configuration data for kernel and user space */
39struct fpu_state_config fpu_kernel_cfg __ro_after_init;
40struct fpu_state_config fpu_user_cfg __ro_after_init;
41struct vcpu_fpu_config guest_default_cfg __ro_after_init;
42
43/*
44 * Represents the initial FPU state. It's mostly (but not completely) zeroes,
45 * depending on the FPU hardware format:
46 */
47struct fpstate init_fpstate __ro_after_init;
48
49/*
50 * Track FPU initialization and kernel-mode usage. 'true' means the FPU is
51 * initialized and is not currently being used by the kernel:
52 */
53DEFINE_PER_CPU(bool, kernel_fpu_allowed);
54
55/*
56 * Track which context is using the FPU on the CPU:
57 */
58DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
59
60#ifdef CONFIG_X86_DEBUG_FPU
61struct fpu *x86_task_fpu(struct task_struct *task)
62{
63 if (WARN_ON_ONCE(task->flags & PF_KTHREAD))
64 return NULL;
65
66 return (void *)task + sizeof(*task);
67}
68#endif
69
70/*
71 * Can we use the FPU in kernel mode with the
72 * whole "kernel_fpu_begin/end()" sequence?
73 */
74bool irq_fpu_usable(void)
75{
76 if (WARN_ON_ONCE(in_nmi()))
77 return false;
78
79 /*
80 * Return false in the following cases:
81 *
82 * - FPU is not yet initialized. This can happen only when the call is
83 * coming from CPU onlining, for example for microcode checksumming.
84 * - The kernel is already using the FPU, either because of explicit
85 * nesting (which should never be done), or because of implicit
86 * nesting when a hardirq interrupted a kernel-mode FPU section.
87 *
88 * The single boolean check below handles both cases:
89 */
90 if (!this_cpu_read(kernel_fpu_allowed))
91 return false;
92
93 /*
94 * When not in NMI or hard interrupt context, FPU can be used in:
95 *
96 * - Task context except from within fpregs_lock()'ed critical
97 * regions.
98 *
99 * - Soft interrupt processing context which cannot happen
100 * while in a fpregs_lock()'ed critical region.
101 */
102 if (!in_hardirq())
103 return true;
104
105 /*
106 * In hard interrupt context it's safe when soft interrupts
107 * are enabled, which means the interrupt did not hit in
108 * a fpregs_lock()'ed critical region.
109 */
110 return !softirq_count();
111}
112EXPORT_SYMBOL(irq_fpu_usable);
113
114/*
115 * Track AVX512 state use because it is known to slow the max clock
116 * speed of the core.
117 */
118static void update_avx_timestamp(struct fpu *fpu)
119{
120
121#define AVX512_TRACKING_MASK (XFEATURE_MASK_ZMM_Hi256 | XFEATURE_MASK_Hi16_ZMM)
122
123 if (fpu->fpstate->regs.xsave.header.xfeatures & AVX512_TRACKING_MASK)
124 fpu->avx512_timestamp = jiffies;
125}
126
127/*
128 * Save the FPU register state in fpu->fpstate->regs. The register state is
129 * preserved.
130 *
131 * Must be called with fpregs_lock() held.
132 *
133 * The legacy FNSAVE instruction clears all FPU state unconditionally, so
134 * register state has to be reloaded. That might be a pointless exercise
135 * when the FPU is going to be used by another task right after that. But
136 * this only affects 20+ years old 32bit systems and avoids conditionals all
137 * over the place.
138 *
139 * FXSAVE and all XSAVE variants preserve the FPU register state.
140 */
141void save_fpregs_to_fpstate(struct fpu *fpu)
142{
143 if (likely(use_xsave())) {
144 os_xsave(fpstate: fpu->fpstate);
145 update_avx_timestamp(fpu);
146 return;
147 }
148
149 if (likely(use_fxsr())) {
150 fxsave(fx: &fpu->fpstate->regs.fxsave);
151 return;
152 }
153
154 /*
155 * Legacy FPU register saving, FNSAVE always clears FPU registers,
156 * so we have to reload them from the memory state.
157 */
158 asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->fpstate->regs.fsave));
159 frstor(fx: &fpu->fpstate->regs.fsave);
160}
161
162void restore_fpregs_from_fpstate(struct fpstate *fpstate, u64 mask)
163{
164 /*
165 * AMD K7/K8 and later CPUs up to Zen don't save/restore
166 * FDP/FIP/FOP unless an exception is pending. Clear the x87 state
167 * here by setting it to fixed values. "m" is a random variable
168 * that should be in L1.
169 */
170 if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
171 asm volatile(
172 "fnclex\n\t"
173 "emms\n\t"
174 "fildl %[addr]" /* set F?P to defined value */
175 : : [addr] "m" (*fpstate));
176 }
177
178 if (use_xsave()) {
179 /*
180 * Dynamically enabled features are enabled in XCR0, but
181 * usage requires also that the corresponding bits in XFD
182 * are cleared. If the bits are set then using a related
183 * instruction will raise #NM. This allows to do the
184 * allocation of the larger FPU buffer lazy from #NM or if
185 * the task has no permission to kill it which would happen
186 * via #UD if the feature is disabled in XCR0.
187 *
188 * XFD state is following the same life time rules as
189 * XSTATE and to restore state correctly XFD has to be
190 * updated before XRSTORS otherwise the component would
191 * stay in or go into init state even if the bits are set
192 * in fpstate::regs::xsave::xfeatures.
193 */
194 xfd_update_state(fpstate);
195
196 /*
197 * Restoring state always needs to modify all features
198 * which are in @mask even if the current task cannot use
199 * extended features.
200 *
201 * So fpstate->xfeatures cannot be used here, because then
202 * a feature for which the task has no permission but was
203 * used by the previous task would not go into init state.
204 */
205 mask = fpu_kernel_cfg.max_features & mask;
206
207 os_xrstor(fpstate, mask);
208 } else {
209 if (use_fxsr())
210 fxrstor(fx: &fpstate->regs.fxsave);
211 else
212 frstor(fx: &fpstate->regs.fsave);
213 }
214}
215
216void fpu_reset_from_exception_fixup(void)
217{
218 restore_fpregs_from_fpstate(fpstate: &init_fpstate, XFEATURE_MASK_FPSTATE);
219}
220
221#if IS_ENABLED(CONFIG_KVM)
222static void __fpstate_reset(struct fpstate *fpstate);
223
224static void fpu_lock_guest_permissions(void)
225{
226 struct fpu_state_perm *fpuperm;
227 u64 perm;
228
229 if (!IS_ENABLED(CONFIG_X86_64))
230 return;
231
232 spin_lock_irq(lock: &current->sighand->siglock);
233 fpuperm = &x86_task_fpu(current->group_leader)->guest_perm;
234 perm = fpuperm->__state_perm;
235
236 /* First fpstate allocation locks down permissions. */
237 WRITE_ONCE(fpuperm->__state_perm, perm | FPU_GUEST_PERM_LOCKED);
238
239 spin_unlock_irq(lock: &current->sighand->siglock);
240}
241
242bool fpu_alloc_guest_fpstate(struct fpu_guest *gfpu)
243{
244 struct fpstate *fpstate;
245 unsigned int size;
246
247 size = guest_default_cfg.size + ALIGN(offsetof(struct fpstate, regs), 64);
248
249 fpstate = vzalloc(size);
250 if (!fpstate)
251 return false;
252
253 /* Initialize indicators to reflect properties of the fpstate */
254 fpstate->is_valloc = true;
255 fpstate->is_guest = true;
256
257 __fpstate_reset(fpstate);
258 fpstate_init_user(fpstate);
259
260 gfpu->fpstate = fpstate;
261 gfpu->xfeatures = guest_default_cfg.features;
262
263 /*
264 * KVM sets the FP+SSE bits in the XSAVE header when copying FPU state
265 * to userspace, even when XSAVE is unsupported, so that restoring FPU
266 * state on a different CPU that does support XSAVE can cleanly load
267 * the incoming state using its natural XSAVE. In other words, KVM's
268 * uABI size may be larger than this host's default size. Conversely,
269 * the default size should never be larger than KVM's base uABI size;
270 * all features that can expand the uABI size must be opt-in.
271 */
272 gfpu->uabi_size = sizeof(struct kvm_xsave);
273 if (WARN_ON_ONCE(fpu_user_cfg.default_size > gfpu->uabi_size))
274 gfpu->uabi_size = fpu_user_cfg.default_size;
275
276 fpu_lock_guest_permissions();
277
278 return true;
279}
280EXPORT_SYMBOL_FOR_KVM(fpu_alloc_guest_fpstate);
281
282void fpu_free_guest_fpstate(struct fpu_guest *gfpu)
283{
284 struct fpstate *fpstate = gfpu->fpstate;
285
286 if (!fpstate)
287 return;
288
289 if (WARN_ON_ONCE(!fpstate->is_valloc || !fpstate->is_guest || fpstate->in_use))
290 return;
291
292 gfpu->fpstate = NULL;
293 vfree(addr: fpstate);
294}
295EXPORT_SYMBOL_FOR_KVM(fpu_free_guest_fpstate);
296
297/*
298 * fpu_enable_guest_xfd_features - Check xfeatures against guest perm and enable
299 * @guest_fpu: Pointer to the guest FPU container
300 * @xfeatures: Features requested by guest CPUID
301 *
302 * Enable all dynamic xfeatures according to guest perm and requested CPUID.
303 *
304 * Return: 0 on success, error code otherwise
305 */
306int fpu_enable_guest_xfd_features(struct fpu_guest *guest_fpu, u64 xfeatures)
307{
308 lockdep_assert_preemption_enabled();
309
310 /* Nothing to do if all requested features are already enabled. */
311 xfeatures &= ~guest_fpu->xfeatures;
312 if (!xfeatures)
313 return 0;
314
315 return __xfd_enable_feature(which: xfeatures, guest_fpu);
316}
317EXPORT_SYMBOL_FOR_KVM(fpu_enable_guest_xfd_features);
318
319#ifdef CONFIG_X86_64
320void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd)
321{
322 struct fpstate *fpstate = guest_fpu->fpstate;
323
324 fpregs_lock();
325
326 /*
327 * KVM's guest ABI is that setting XFD[i]=1 *can* immediately revert the
328 * save state to its initial configuration. Likewise, KVM_GET_XSAVE does
329 * the same as XSAVE and returns XSTATE_BV[i]=0 whenever XFD[i]=1.
330 *
331 * If the guest's FPU state is in hardware, just update XFD: the XSAVE
332 * in fpu_swap_kvm_fpstate will clear XSTATE_BV[i] whenever XFD[i]=1.
333 *
334 * If however the guest's FPU state is NOT resident in hardware, clear
335 * disabled components in XSTATE_BV now, or a subsequent XRSTOR will
336 * attempt to load disabled components and generate #NM _in the host_.
337 */
338 if (xfd && test_thread_flag(TIF_NEED_FPU_LOAD))
339 fpstate->regs.xsave.header.xfeatures &= ~xfd;
340
341 fpstate->xfd = xfd;
342 if (fpstate->in_use)
343 xfd_update_state(fpstate);
344
345 fpregs_unlock();
346}
347EXPORT_SYMBOL_FOR_KVM(fpu_update_guest_xfd);
348
349/**
350 * fpu_sync_guest_vmexit_xfd_state - Synchronize XFD MSR and software state
351 *
352 * Must be invoked from KVM after a VMEXIT before enabling interrupts when
353 * XFD write emulation is disabled. This is required because the guest can
354 * freely modify XFD and the state at VMEXIT is not guaranteed to be the
355 * same as the state on VMENTER. So software state has to be updated before
356 * any operation which depends on it can take place.
357 *
358 * Note: It can be invoked unconditionally even when write emulation is
359 * enabled for the price of a then pointless MSR read.
360 */
361void fpu_sync_guest_vmexit_xfd_state(void)
362{
363 struct fpstate *fpstate = x86_task_fpu(current)->fpstate;
364
365 lockdep_assert_irqs_disabled();
366 if (fpu_state_size_dynamic()) {
367 rdmsrq(MSR_IA32_XFD, fpstate->xfd);
368 __this_cpu_write(xfd_state, fpstate->xfd);
369 }
370}
371EXPORT_SYMBOL_FOR_KVM(fpu_sync_guest_vmexit_xfd_state);
372#endif /* CONFIG_X86_64 */
373
374int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest)
375{
376 struct fpstate *guest_fps = guest_fpu->fpstate;
377 struct fpu *fpu = x86_task_fpu(current);
378 struct fpstate *cur_fps = fpu->fpstate;
379
380 fpregs_lock();
381 if (!cur_fps->is_confidential && !test_thread_flag(TIF_NEED_FPU_LOAD))
382 save_fpregs_to_fpstate(fpu);
383
384 /* Swap fpstate */
385 if (enter_guest) {
386 fpu->__task_fpstate = cur_fps;
387 fpu->fpstate = guest_fps;
388 guest_fps->in_use = true;
389 } else {
390 guest_fps->in_use = false;
391 fpu->fpstate = fpu->__task_fpstate;
392 fpu->__task_fpstate = NULL;
393 }
394
395 cur_fps = fpu->fpstate;
396
397 if (!cur_fps->is_confidential) {
398 /* Includes XFD update */
399 restore_fpregs_from_fpstate(fpstate: cur_fps, XFEATURE_MASK_FPSTATE);
400 } else {
401 /*
402 * XSTATE is restored by firmware from encrypted
403 * memory. Make sure XFD state is correct while
404 * running with guest fpstate
405 */
406 xfd_update_state(fpstate: cur_fps);
407 }
408
409 fpregs_mark_activate();
410 fpregs_unlock();
411 return 0;
412}
413EXPORT_SYMBOL_FOR_KVM(fpu_swap_kvm_fpstate);
414
415void fpu_copy_guest_fpstate_to_uabi(struct fpu_guest *gfpu, void *buf,
416 unsigned int size, u64 xfeatures, u32 pkru)
417{
418 struct fpstate *kstate = gfpu->fpstate;
419 union fpregs_state *ustate = buf;
420 struct membuf mb = { .p = buf, .left = size };
421
422 if (cpu_feature_enabled(X86_FEATURE_XSAVE)) {
423 __copy_xstate_to_uabi_buf(to: mb, fpstate: kstate, xfeatures, pkru_val: pkru,
424 copy_mode: XSTATE_COPY_XSAVE);
425 } else {
426 memcpy(&ustate->fxsave, &kstate->regs.fxsave,
427 sizeof(ustate->fxsave));
428 /* Make it restorable on a XSAVE enabled host */
429 ustate->xsave.header.xfeatures = XFEATURE_MASK_FPSSE;
430 }
431}
432EXPORT_SYMBOL_FOR_KVM(fpu_copy_guest_fpstate_to_uabi);
433
434int fpu_copy_uabi_to_guest_fpstate(struct fpu_guest *gfpu, const void *buf,
435 u64 xcr0, u32 *vpkru)
436{
437 struct fpstate *kstate = gfpu->fpstate;
438 const union fpregs_state *ustate = buf;
439
440 if (!cpu_feature_enabled(X86_FEATURE_XSAVE)) {
441 if (ustate->xsave.header.xfeatures & ~XFEATURE_MASK_FPSSE)
442 return -EINVAL;
443 if (ustate->fxsave.mxcsr & ~mxcsr_feature_mask)
444 return -EINVAL;
445 memcpy(&kstate->regs.fxsave, &ustate->fxsave, sizeof(ustate->fxsave));
446 return 0;
447 }
448
449 if (ustate->xsave.header.xfeatures & ~xcr0)
450 return -EINVAL;
451
452 /*
453 * Disabled features must be in their initial state, otherwise XRSTOR
454 * causes an exception.
455 */
456 if (WARN_ON_ONCE(ustate->xsave.header.xfeatures & kstate->xfd))
457 return -EINVAL;
458
459 /*
460 * Nullify @vpkru to preserve its current value if PKRU's bit isn't set
461 * in the header. KVM's odd ABI is to leave PKRU untouched in this
462 * case (all other components are eventually re-initialized).
463 */
464 if (!(ustate->xsave.header.xfeatures & XFEATURE_MASK_PKRU))
465 vpkru = NULL;
466
467 return copy_uabi_from_kernel_to_xstate(fpstate: kstate, kbuf: ustate, pkru: vpkru);
468}
469EXPORT_SYMBOL_FOR_KVM(fpu_copy_uabi_to_guest_fpstate);
470#endif /* CONFIG_KVM */
471
472void kernel_fpu_begin_mask(unsigned int kfpu_mask)
473{
474 if (!irqs_disabled())
475 fpregs_lock();
476
477 WARN_ON_FPU(!irq_fpu_usable());
478
479 /* Toggle kernel_fpu_allowed to false: */
480 WARN_ON_FPU(!this_cpu_read(kernel_fpu_allowed));
481 this_cpu_write(kernel_fpu_allowed, false);
482
483 if (!(current->flags & (PF_KTHREAD | PF_USER_WORKER)) &&
484 !test_thread_flag(TIF_NEED_FPU_LOAD)) {
485 set_thread_flag(TIF_NEED_FPU_LOAD);
486 save_fpregs_to_fpstate(fpu: x86_task_fpu(current));
487 }
488 __cpu_invalidate_fpregs_state();
489
490 /* Put sane initial values into the control registers. */
491 if (likely(kfpu_mask & KFPU_MXCSR) && boot_cpu_has(X86_FEATURE_XMM))
492 ldmxcsr(MXCSR_DEFAULT);
493
494 if (unlikely(kfpu_mask & KFPU_387) && boot_cpu_has(X86_FEATURE_FPU))
495 asm volatile ("fninit");
496}
497EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);
498
499void kernel_fpu_end(void)
500{
501 /* Toggle kernel_fpu_allowed back to true: */
502 WARN_ON_FPU(this_cpu_read(kernel_fpu_allowed));
503 this_cpu_write(kernel_fpu_allowed, true);
504
505 if (!irqs_disabled())
506 fpregs_unlock();
507}
508EXPORT_SYMBOL_GPL(kernel_fpu_end);
509
510/*
511 * Sync the FPU register state to current's memory register state when the
512 * current task owns the FPU. The hardware register state is preserved.
513 */
514void fpu_sync_fpstate(struct fpu *fpu)
515{
516 WARN_ON_FPU(fpu != x86_task_fpu(current));
517
518 fpregs_lock();
519 trace_x86_fpu_before_save(fpu);
520
521 if (!test_thread_flag(TIF_NEED_FPU_LOAD))
522 save_fpregs_to_fpstate(fpu);
523
524 trace_x86_fpu_after_save(fpu);
525 fpregs_unlock();
526}
527
528static inline unsigned int init_fpstate_copy_size(void)
529{
530 if (!use_xsave())
531 return fpu_kernel_cfg.default_size;
532
533 /* XSAVE(S) just needs the legacy and the xstate header part */
534 return sizeof(init_fpstate.regs.xsave);
535}
536
537static inline void fpstate_init_fxstate(struct fpstate *fpstate)
538{
539 fpstate->regs.fxsave.cwd = 0x37f;
540 fpstate->regs.fxsave.mxcsr = MXCSR_DEFAULT;
541}
542
543/*
544 * Legacy x87 fpstate state init:
545 */
546static inline void fpstate_init_fstate(struct fpstate *fpstate)
547{
548 fpstate->regs.fsave.cwd = 0xffff037fu;
549 fpstate->regs.fsave.swd = 0xffff0000u;
550 fpstate->regs.fsave.twd = 0xffffffffu;
551 fpstate->regs.fsave.fos = 0xffff0000u;
552}
553
554/*
555 * Used in two places:
556 * 1) Early boot to setup init_fpstate for non XSAVE systems
557 * 2) fpu_alloc_guest_fpstate() which is invoked from KVM
558 */
559void fpstate_init_user(struct fpstate *fpstate)
560{
561 if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
562 fpstate_init_soft(soft: &fpstate->regs.soft);
563 return;
564 }
565
566 xstate_init_xcomp_bv(xsave: &fpstate->regs.xsave, mask: fpstate->xfeatures);
567
568 if (cpu_feature_enabled(X86_FEATURE_FXSR))
569 fpstate_init_fxstate(fpstate);
570 else
571 fpstate_init_fstate(fpstate);
572}
573
574static void __fpstate_reset(struct fpstate *fpstate)
575{
576 /*
577 * Supervisor features (and thus sizes) may diverge between guest
578 * FPUs and host FPUs, as some supervisor features are supported
579 * for guests despite not being utilized by the host. User
580 * features and sizes are always identical, which allows for
581 * common guest and userspace ABI.
582 *
583 * For the host, set XFD to the kernel's desired initialization
584 * value. For guests, set XFD to its architectural RESET value.
585 */
586 if (fpstate->is_guest) {
587 fpstate->size = guest_default_cfg.size;
588 fpstate->xfeatures = guest_default_cfg.features;
589 fpstate->xfd = 0;
590 } else {
591 fpstate->size = fpu_kernel_cfg.default_size;
592 fpstate->xfeatures = fpu_kernel_cfg.default_features;
593 fpstate->xfd = init_fpstate.xfd;
594 }
595
596 fpstate->user_size = fpu_user_cfg.default_size;
597 fpstate->user_xfeatures = fpu_user_cfg.default_features;
598}
599
600void fpstate_reset(struct fpu *fpu)
601{
602 /* Set the fpstate pointer to the default fpstate */
603 fpu->fpstate = &fpu->__fpstate;
604 __fpstate_reset(fpstate: fpu->fpstate);
605
606 /* Initialize the permission related info in fpu */
607 fpu->perm.__state_perm = fpu_kernel_cfg.default_features;
608 fpu->perm.__state_size = fpu_kernel_cfg.default_size;
609 fpu->perm.__user_state_size = fpu_user_cfg.default_size;
610
611 fpu->guest_perm.__state_perm = guest_default_cfg.features;
612 fpu->guest_perm.__state_size = guest_default_cfg.size;
613 /*
614 * User features and sizes are always identical between host and
615 * guest FPUs, which allows for common guest and userspace ABI.
616 */
617 fpu->guest_perm.__user_state_size = fpu_user_cfg.default_size;
618}
619
620static inline void fpu_inherit_perms(struct fpu *dst_fpu)
621{
622 if (fpu_state_size_dynamic()) {
623 struct fpu *src_fpu = x86_task_fpu(current->group_leader);
624
625 spin_lock_irq(lock: &current->sighand->siglock);
626 /* Fork also inherits the permissions of the parent */
627 dst_fpu->perm = src_fpu->perm;
628 dst_fpu->guest_perm = src_fpu->guest_perm;
629 spin_unlock_irq(lock: &current->sighand->siglock);
630 }
631}
632
633/* A passed ssp of zero will not cause any update */
634static int update_fpu_shstk(struct task_struct *dst, unsigned long ssp)
635{
636#ifdef CONFIG_X86_USER_SHADOW_STACK
637 struct cet_user_state *xstate;
638
639 /* If ssp update is not needed. */
640 if (!ssp)
641 return 0;
642
643 xstate = get_xsave_addr(xsave: &x86_task_fpu(task: dst)->fpstate->regs.xsave,
644 xfeature_nr: XFEATURE_CET_USER);
645
646 /*
647 * If there is a non-zero ssp, then 'dst' must be configured with a shadow
648 * stack and the fpu state should be up to date since it was just copied
649 * from the parent in fpu_clone(). So there must be a valid non-init CET
650 * state location in the buffer.
651 */
652 if (WARN_ON_ONCE(!xstate))
653 return 1;
654
655 xstate->user_ssp = (u64)ssp;
656#endif
657 return 0;
658}
659
660/* Clone current's FPU state on fork */
661int fpu_clone(struct task_struct *dst, u64 clone_flags, bool minimal,
662 unsigned long ssp)
663{
664 /*
665 * We allocate the new FPU structure right after the end of the task struct.
666 * task allocation size already took this into account.
667 *
668 * This is safe because task_struct size is a multiple of cacheline size,
669 * thus x86_task_fpu() will always be cacheline aligned as well.
670 */
671 struct fpu *dst_fpu = (void *)dst + sizeof(*dst);
672
673 BUILD_BUG_ON(sizeof(*dst) % SMP_CACHE_BYTES != 0);
674
675 /* The new task's FPU state cannot be valid in the hardware. */
676 dst_fpu->last_cpu = -1;
677
678 fpstate_reset(fpu: dst_fpu);
679
680 if (!cpu_feature_enabled(X86_FEATURE_FPU))
681 return 0;
682
683 /*
684 * Enforce reload for user space tasks and prevent kernel threads
685 * from trying to save the FPU registers on context switch.
686 */
687 set_tsk_thread_flag(tsk: dst, TIF_NEED_FPU_LOAD);
688
689 /*
690 * No FPU state inheritance for kernel threads and IO
691 * worker threads.
692 */
693 if (minimal) {
694 /* Clear out the minimal state */
695 memcpy(&dst_fpu->fpstate->regs, &init_fpstate.regs,
696 init_fpstate_copy_size());
697 return 0;
698 }
699
700 /*
701 * If a new feature is added, ensure all dynamic features are
702 * caller-saved from here!
703 */
704 BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);
705
706 /*
707 * Save the default portion of the current FPU state into the
708 * clone. Assume all dynamic features to be defined as caller-
709 * saved, which enables skipping both the expansion of fpstate
710 * and the copying of any dynamic state.
711 *
712 * Do not use memcpy() when TIF_NEED_FPU_LOAD is set because
713 * copying is not valid when current uses non-default states.
714 */
715 fpregs_lock();
716 if (test_thread_flag(TIF_NEED_FPU_LOAD))
717 fpregs_restore_userregs();
718 save_fpregs_to_fpstate(fpu: dst_fpu);
719 fpregs_unlock();
720 if (!(clone_flags & CLONE_THREAD))
721 fpu_inherit_perms(dst_fpu);
722
723 /*
724 * Children never inherit PASID state.
725 * Force it to have its init value:
726 */
727 if (use_xsave())
728 dst_fpu->fpstate->regs.xsave.header.xfeatures &= ~XFEATURE_MASK_PASID;
729
730 /*
731 * Update shadow stack pointer, in case it changed during clone.
732 */
733 if (update_fpu_shstk(dst, ssp))
734 return 1;
735
736 trace_x86_fpu_copy_dst(fpu: dst_fpu);
737
738 return 0;
739}
740
741/*
742 * While struct fpu is no longer part of struct thread_struct, it is still
743 * allocated after struct task_struct in the "task_struct" kmem cache. But
744 * since FPU is expected to be part of struct thread_struct, we have to
745 * adjust for it here.
746 */
747void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size)
748{
749 /* The allocation follows struct task_struct. */
750 *offset = sizeof(struct task_struct) - offsetof(struct task_struct, thread);
751 *offset += offsetof(struct fpu, __fpstate.regs);
752 *size = fpu_kernel_cfg.default_size;
753}
754
755/*
756 * Drops current FPU state: deactivates the fpregs and
757 * the fpstate. NOTE: it still leaves previous contents
758 * in the fpregs in the eager-FPU case.
759 *
760 * This function can be used in cases where we know that
761 * a state-restore is coming: either an explicit one,
762 * or a reschedule.
763 */
764void fpu__drop(struct task_struct *tsk)
765{
766 struct fpu *fpu;
767
768 if (test_tsk_thread_flag(tsk, TIF_NEED_FPU_LOAD))
769 return;
770
771 fpu = x86_task_fpu(task: tsk);
772
773 preempt_disable();
774
775 if (fpu == x86_task_fpu(current)) {
776 /* Ignore delayed exceptions from user space */
777 asm volatile("1: fwait\n"
778 "2:\n"
779 _ASM_EXTABLE(1b, 2b));
780 fpregs_deactivate(fpu);
781 }
782
783 trace_x86_fpu_dropped(fpu);
784
785 preempt_enable();
786}
787
788/*
789 * Clear FPU registers by setting them up from the init fpstate.
790 * Caller must do fpregs_[un]lock() around it.
791 */
792static inline void restore_fpregs_from_init_fpstate(u64 features_mask)
793{
794 if (use_xsave())
795 os_xrstor(fpstate: &init_fpstate, mask: features_mask);
796 else if (use_fxsr())
797 fxrstor(fx: &init_fpstate.regs.fxsave);
798 else
799 frstor(fx: &init_fpstate.regs.fsave);
800
801 pkru_write_default();
802}
803
804/*
805 * Reset current->fpu memory state to the init values.
806 */
807static void fpu_reset_fpstate_regs(void)
808{
809 struct fpu *fpu = x86_task_fpu(current);
810
811 fpregs_lock();
812 __fpu_invalidate_fpregs_state(fpu);
813 /*
814 * This does not change the actual hardware registers. It just
815 * resets the memory image and sets TIF_NEED_FPU_LOAD so a
816 * subsequent return to usermode will reload the registers from the
817 * task's memory image.
818 *
819 * Do not use fpstate_init() here. Just copy init_fpstate which has
820 * the correct content already except for PKRU.
821 *
822 * PKRU handling does not rely on the xstate when restoring for
823 * user space as PKRU is eagerly written in switch_to() and
824 * flush_thread().
825 */
826 memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size());
827 set_thread_flag(TIF_NEED_FPU_LOAD);
828 fpregs_unlock();
829}
830
831/*
832 * Reset current's user FPU states to the init states. current's
833 * supervisor states, if any, are not modified by this function. The
834 * caller guarantees that the XSTATE header in memory is intact.
835 */
836void fpu__clear_user_states(struct fpu *fpu)
837{
838 WARN_ON_FPU(fpu != x86_task_fpu(current));
839
840 fpregs_lock();
841 if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
842 fpu_reset_fpstate_regs();
843 fpregs_unlock();
844 return;
845 }
846
847 /*
848 * Ensure that current's supervisor states are loaded into their
849 * corresponding registers.
850 */
851 if (xfeatures_mask_supervisor() &&
852 !fpregs_state_valid(fpu, smp_processor_id()))
853 os_xrstor_supervisor(fpstate: fpu->fpstate);
854
855 /* Ensure XFD state is in sync before reloading XSTATE */
856 xfd_update_state(fpstate: fpu->fpstate);
857
858 /* Reset user states in registers. */
859 restore_fpregs_from_init_fpstate(XFEATURE_MASK_USER_RESTORE);
860
861 /*
862 * Now all FPU registers have their desired values. Inform the FPU
863 * state machine that current's FPU registers are in the hardware
864 * registers. The memory image does not need to be updated because
865 * any operation relying on it has to save the registers first when
866 * current's FPU is marked active.
867 */
868 fpregs_mark_activate();
869 fpregs_unlock();
870}
871
872void fpu_flush_thread(void)
873{
874 fpstate_reset(fpu: x86_task_fpu(current));
875 fpu_reset_fpstate_regs();
876}
877/*
878 * Load FPU context before returning to userspace.
879 */
880void switch_fpu_return(void)
881{
882 if (!static_cpu_has(X86_FEATURE_FPU))
883 return;
884
885 fpregs_restore_userregs();
886}
887EXPORT_SYMBOL_FOR_KVM(switch_fpu_return);
888
889void fpregs_lock_and_load(void)
890{
891 /*
892 * fpregs_lock() only disables preemption (mostly). So modifying state
893 * in an interrupt could screw up some in progress fpregs operation.
894 * Warn about it.
895 */
896 WARN_ON_ONCE(!irq_fpu_usable());
897 WARN_ON_ONCE(current->flags & PF_KTHREAD);
898
899 fpregs_lock();
900
901 fpregs_assert_state_consistent();
902
903 if (test_thread_flag(TIF_NEED_FPU_LOAD))
904 fpregs_restore_userregs();
905}
906
907#ifdef CONFIG_X86_DEBUG_FPU
908/*
909 * If current FPU state according to its tracking (loaded FPU context on this
910 * CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is
911 * loaded on return to userland.
912 */
913void fpregs_assert_state_consistent(void)
914{
915 struct fpu *fpu = x86_task_fpu(current);
916
917 if (test_thread_flag(TIF_NEED_FPU_LOAD))
918 return;
919
920 WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));
921}
922EXPORT_SYMBOL_FOR_KVM(fpregs_assert_state_consistent);
923#endif
924
925void fpregs_mark_activate(void)
926{
927 struct fpu *fpu = x86_task_fpu(current);
928
929 fpregs_activate(fpu);
930 fpu->last_cpu = smp_processor_id();
931 clear_thread_flag(TIF_NEED_FPU_LOAD);
932}
933
934/*
935 * x87 math exception handling:
936 */
937
938int fpu__exception_code(struct fpu *fpu, int trap_nr)
939{
940 int err;
941
942 if (trap_nr == X86_TRAP_MF) {
943 unsigned short cwd, swd;
944 /*
945 * (~cwd & swd) will mask out exceptions that are not set to unmasked
946 * status. 0x3f is the exception bits in these regs, 0x200 is the
947 * C1 reg you need in case of a stack fault, 0x040 is the stack
948 * fault bit. We should only be taking one exception at a time,
949 * so if this combination doesn't produce any single exception,
950 * then we have a bad program that isn't synchronizing its FPU usage
951 * and it will suffer the consequences since we won't be able to
952 * fully reproduce the context of the exception.
953 */
954 if (boot_cpu_has(X86_FEATURE_FXSR)) {
955 cwd = fpu->fpstate->regs.fxsave.cwd;
956 swd = fpu->fpstate->regs.fxsave.swd;
957 } else {
958 cwd = (unsigned short)fpu->fpstate->regs.fsave.cwd;
959 swd = (unsigned short)fpu->fpstate->regs.fsave.swd;
960 }
961
962 err = swd & ~cwd;
963 } else {
964 /*
965 * The SIMD FPU exceptions are handled a little differently, as there
966 * is only a single status/control register. Thus, to determine which
967 * unmasked exception was caught we must mask the exception mask bits
968 * at 0x1f80, and then use these to mask the exception bits at 0x3f.
969 */
970 unsigned short mxcsr = MXCSR_DEFAULT;
971
972 if (boot_cpu_has(X86_FEATURE_XMM))
973 mxcsr = fpu->fpstate->regs.fxsave.mxcsr;
974
975 err = ~(mxcsr >> 7) & mxcsr;
976 }
977
978 if (err & 0x001) { /* Invalid op */
979 /*
980 * swd & 0x240 == 0x040: Stack Underflow
981 * swd & 0x240 == 0x240: Stack Overflow
982 * User must clear the SF bit (0x40) if set
983 */
984 return FPE_FLTINV;
985 } else if (err & 0x004) { /* Divide by Zero */
986 return FPE_FLTDIV;
987 } else if (err & 0x008) { /* Overflow */
988 return FPE_FLTOVF;
989 } else if (err & 0x012) { /* Denormal, Underflow */
990 return FPE_FLTUND;
991 } else if (err & 0x020) { /* Precision */
992 return FPE_FLTRES;
993 }
994
995 /*
996 * If we're using IRQ 13, or supposedly even some trap
997 * X86_TRAP_MF implementations, it's possible
998 * we get a spurious trap, which is not an error.
999 */
1000 return 0;
1001}
1002
1003/*
1004 * Initialize register state that may prevent from entering low-power idle.
1005 * This function will be invoked from the cpuidle driver only when needed.
1006 */
1007noinstr void fpu_idle_fpregs(void)
1008{
1009 /* Note: AMX_TILE being enabled implies XGETBV1 support */
1010 if (cpu_feature_enabled(X86_FEATURE_AMX_TILE) &&
1011 (xfeatures_in_use() & XFEATURE_MASK_XTILE)) {
1012 tile_release();
1013 __this_cpu_write(fpu_fpregs_owner_ctx, NULL);
1014 }
1015}
1016

source code of linux/arch/x86/kernel/fpu/core.c