xref: /linux/arch/x86/kernel/fpu/core.c (revision ab05214025ee2af262591cd48df17883648bdb1a)
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
34 DEFINE_STATIC_KEY_FALSE(__fpu_state_size_dynamic);
35 DEFINE_PER_CPU(u64, xfd_state);
36 #endif
37 
38 /* The FPU state configuration data for kernel and user space */
39 struct fpu_state_config	fpu_kernel_cfg __ro_after_init;
40 struct fpu_state_config fpu_user_cfg __ro_after_init;
41 struct 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  */
47 struct 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  */
53 DEFINE_PER_CPU(bool, kernel_fpu_allowed);
54 
55 /*
56  * Track which context is using the FPU on the CPU:
57  */
58 DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
59 
60 #ifdef CONFIG_X86_DEBUG_FPU
61 struct 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  */
74 bool 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 }
112 EXPORT_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  */
118 static 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  */
141 void save_fpregs_to_fpstate(struct fpu *fpu)
142 {
143 	if (likely(use_xsave())) {
144 		os_xsave(fpu->fpstate);
145 		update_avx_timestamp(fpu);
146 		return;
147 	}
148 
149 	if (likely(use_fxsr())) {
150 		fxsave(&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(&fpu->fpstate->regs.fsave);
160 }
161 
162 void 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(&fpstate->regs.fxsave);
211 		else
212 			frstor(&fpstate->regs.fsave);
213 	}
214 }
215 
216 void fpu_reset_from_exception_fixup(void)
217 {
218 	restore_fpregs_from_fpstate(&init_fpstate, XFEATURE_MASK_FPSTATE);
219 }
220 
221 #if IS_ENABLED(CONFIG_KVM)
222 static void __fpstate_reset(struct fpstate *fpstate);
223 
224 static 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(&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(&current->sighand->siglock);
240 }
241 
242 bool 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 }
280 EXPORT_SYMBOL_FOR_KVM(fpu_alloc_guest_fpstate);
281 
282 void 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(fpstate);
294 }
295 EXPORT_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   */
306 int 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(xfeatures, guest_fpu);
316 }
317 EXPORT_SYMBOL_FOR_KVM(fpu_enable_guest_xfd_features);
318 
319 #ifdef CONFIG_X86_64
320 void 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 }
347 EXPORT_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  */
361 void 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 }
371 EXPORT_SYMBOL_FOR_KVM(fpu_sync_guest_vmexit_xfd_state);
372 #endif /* CONFIG_X86_64 */
373 
374 int 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(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(cur_fps);
407 	}
408 
409 	fpregs_mark_activate();
410 	fpregs_unlock();
411 	return 0;
412 }
413 EXPORT_SYMBOL_FOR_KVM(fpu_swap_kvm_fpstate);
414 
415 void 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(mb, kstate, xfeatures, pkru,
424 					  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 }
432 EXPORT_SYMBOL_FOR_KVM(fpu_copy_guest_fpstate_to_uabi);
433 
434 int 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(kstate, ustate, vpkru);
468 }
469 EXPORT_SYMBOL_FOR_KVM(fpu_copy_uabi_to_guest_fpstate);
470 #endif /* CONFIG_KVM */
471 
472 void 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(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 }
497 EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);
498 
499 void 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 }
508 EXPORT_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  */
514 void 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 
528 static 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 
537 static 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  */
546 static 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  */
559 void fpstate_init_user(struct fpstate *fpstate)
560 {
561 	xstate_init_xcomp_bv(&fpstate->regs.xsave, fpstate->xfeatures);
562 
563 	if (cpu_feature_enabled(X86_FEATURE_FXSR))
564 		fpstate_init_fxstate(fpstate);
565 	else
566 		fpstate_init_fstate(fpstate);
567 }
568 
569 static void __fpstate_reset(struct fpstate *fpstate)
570 {
571 	/*
572 	 * Supervisor features (and thus sizes) may diverge between guest
573 	 * FPUs and host FPUs, as some supervisor features are supported
574 	 * for guests despite not being utilized by the host. User
575 	 * features and sizes are always identical, which allows for
576 	 * common guest and userspace ABI.
577 	 *
578 	 * For the host, set XFD to the kernel's desired initialization
579 	 * value. For guests, set XFD to its architectural RESET value.
580 	 */
581 	if (fpstate->is_guest) {
582 		fpstate->size		= guest_default_cfg.size;
583 		fpstate->xfeatures	= guest_default_cfg.features;
584 		fpstate->xfd		= 0;
585 	} else {
586 		fpstate->size		= fpu_kernel_cfg.default_size;
587 		fpstate->xfeatures	= fpu_kernel_cfg.default_features;
588 		fpstate->xfd		= init_fpstate.xfd;
589 	}
590 
591 	fpstate->user_size	= fpu_user_cfg.default_size;
592 	fpstate->user_xfeatures	= fpu_user_cfg.default_features;
593 }
594 
595 void fpstate_reset(struct fpu *fpu)
596 {
597 	/* Set the fpstate pointer to the default fpstate */
598 	fpu->fpstate = &fpu->__fpstate;
599 	__fpstate_reset(fpu->fpstate);
600 
601 	/* Initialize the permission related info in fpu */
602 	fpu->perm.__state_perm		= fpu_kernel_cfg.default_features;
603 	fpu->perm.__state_size		= fpu_kernel_cfg.default_size;
604 	fpu->perm.__user_state_size	= fpu_user_cfg.default_size;
605 
606 	fpu->guest_perm.__state_perm	= guest_default_cfg.features;
607 	fpu->guest_perm.__state_size	= guest_default_cfg.size;
608 	/*
609 	 * User features and sizes are always identical between host and
610 	 * guest FPUs, which allows for common guest and userspace ABI.
611 	 */
612 	fpu->guest_perm.__user_state_size = fpu_user_cfg.default_size;
613 }
614 
615 static inline void fpu_inherit_perms(struct fpu *dst_fpu)
616 {
617 	if (fpu_state_size_dynamic()) {
618 		struct fpu *src_fpu = x86_task_fpu(current->group_leader);
619 
620 		spin_lock_irq(&current->sighand->siglock);
621 		/* Fork also inherits the permissions of the parent */
622 		dst_fpu->perm = src_fpu->perm;
623 		dst_fpu->guest_perm = src_fpu->guest_perm;
624 		spin_unlock_irq(&current->sighand->siglock);
625 	}
626 }
627 
628 /* A passed ssp of zero will not cause any update */
629 static int update_fpu_shstk(struct task_struct *dst, unsigned long ssp)
630 {
631 #ifdef CONFIG_X86_USER_SHADOW_STACK
632 	struct cet_user_state *xstate;
633 
634 	/* If ssp update is not needed. */
635 	if (!ssp)
636 		return 0;
637 
638 	xstate = get_xsave_addr(&x86_task_fpu(dst)->fpstate->regs.xsave,
639 				XFEATURE_CET_USER);
640 
641 	/*
642 	 * If there is a non-zero ssp, then 'dst' must be configured with a shadow
643 	 * stack and the fpu state should be up to date since it was just copied
644 	 * from the parent in fpu_clone(). So there must be a valid non-init CET
645 	 * state location in the buffer.
646 	 */
647 	if (WARN_ON_ONCE(!xstate))
648 		return 1;
649 
650 	xstate->user_ssp = (u64)ssp;
651 #endif
652 	return 0;
653 }
654 
655 /* Clone current's FPU state on fork */
656 int fpu_clone(struct task_struct *dst, u64 clone_flags, bool minimal,
657 	      unsigned long ssp)
658 {
659 	/*
660 	 * We allocate the new FPU structure right after the end of the task struct.
661 	 * task allocation size already took this into account.
662 	 *
663 	 * This is safe because task_struct size is a multiple of cacheline size,
664 	 * thus x86_task_fpu() will always be cacheline aligned as well.
665 	 */
666 	struct fpu *dst_fpu = (void *)dst + sizeof(*dst);
667 
668 	BUILD_BUG_ON(sizeof(*dst) % SMP_CACHE_BYTES != 0);
669 
670 	/* The new task's FPU state cannot be valid in the hardware. */
671 	dst_fpu->last_cpu = -1;
672 
673 	fpstate_reset(dst_fpu);
674 
675 	if (!cpu_feature_enabled(X86_FEATURE_FPU))
676 		return 0;
677 
678 	/*
679 	 * Enforce reload for user space tasks and prevent kernel threads
680 	 * from trying to save the FPU registers on context switch.
681 	 */
682 	set_tsk_thread_flag(dst, TIF_NEED_FPU_LOAD);
683 
684 	/*
685 	 * No FPU state inheritance for kernel threads and IO
686 	 * worker threads.
687 	 */
688 	if (minimal) {
689 		/* Clear out the minimal state */
690 		memcpy(&dst_fpu->fpstate->regs, &init_fpstate.regs,
691 		       init_fpstate_copy_size());
692 		return 0;
693 	}
694 
695 	/*
696 	 * If a new feature is added, ensure all dynamic features are
697 	 * caller-saved from here!
698 	 */
699 	BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);
700 
701 	/*
702 	 * Save the default portion of the current FPU state into the
703 	 * clone. Assume all dynamic features to be defined as caller-
704 	 * saved, which enables skipping both the expansion of fpstate
705 	 * and the copying of any dynamic state.
706 	 *
707 	 * Do not use memcpy() when TIF_NEED_FPU_LOAD is set because
708 	 * copying is not valid when current uses non-default states.
709 	 */
710 	fpregs_lock();
711 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
712 		fpregs_restore_userregs();
713 	save_fpregs_to_fpstate(dst_fpu);
714 	fpregs_unlock();
715 	if (!(clone_flags & CLONE_THREAD))
716 		fpu_inherit_perms(dst_fpu);
717 
718 	/*
719 	 * Children never inherit PASID state.
720 	 * Force it to have its init value:
721 	 */
722 	if (use_xsave())
723 		dst_fpu->fpstate->regs.xsave.header.xfeatures &= ~XFEATURE_MASK_PASID;
724 
725 	/*
726 	 * Update shadow stack pointer, in case it changed during clone.
727 	 */
728 	if (update_fpu_shstk(dst, ssp))
729 		return 1;
730 
731 	trace_x86_fpu_copy_dst(dst_fpu);
732 
733 	return 0;
734 }
735 
736 /*
737  * While struct fpu is no longer part of struct thread_struct, it is still
738  * allocated after struct task_struct in the "task_struct" kmem cache. But
739  * since FPU is expected to be part of struct thread_struct, we have to
740  * adjust for it here.
741  */
742 void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size)
743 {
744 	/* The allocation follows struct task_struct. */
745 	*offset = sizeof(struct task_struct) - offsetof(struct task_struct, thread);
746 	*offset += offsetof(struct fpu, __fpstate.regs);
747 	*size = fpu_kernel_cfg.default_size;
748 }
749 
750 /*
751  * Drops current FPU state: deactivates the fpregs and
752  * the fpstate. NOTE: it still leaves previous contents
753  * in the fpregs in the eager-FPU case.
754  *
755  * This function can be used in cases where we know that
756  * a state-restore is coming: either an explicit one,
757  * or a reschedule.
758  */
759 void fpu__drop(struct task_struct *tsk)
760 {
761 	struct fpu *fpu;
762 
763 	if (test_tsk_thread_flag(tsk, TIF_NEED_FPU_LOAD))
764 		return;
765 
766 	fpu = x86_task_fpu(tsk);
767 
768 	preempt_disable();
769 
770 	if (fpu == x86_task_fpu(current)) {
771 		/* Ignore delayed exceptions from user space */
772 		asm volatile("1: fwait\n"
773 			     "2:\n"
774 			     _ASM_EXTABLE(1b, 2b));
775 		fpregs_deactivate(fpu);
776 	}
777 
778 	trace_x86_fpu_dropped(fpu);
779 
780 	preempt_enable();
781 }
782 
783 /*
784  * Clear FPU registers by setting them up from the init fpstate.
785  * Caller must do fpregs_[un]lock() around it.
786  */
787 static inline void restore_fpregs_from_init_fpstate(u64 features_mask)
788 {
789 	if (use_xsave())
790 		os_xrstor(&init_fpstate, features_mask);
791 	else if (use_fxsr())
792 		fxrstor(&init_fpstate.regs.fxsave);
793 	else
794 		frstor(&init_fpstate.regs.fsave);
795 
796 	pkru_write_default();
797 }
798 
799 /*
800  * Reset current->fpu memory state to the init values.
801  */
802 static void fpu_reset_fpstate_regs(void)
803 {
804 	struct fpu *fpu = x86_task_fpu(current);
805 
806 	fpregs_lock();
807 	__fpu_invalidate_fpregs_state(fpu);
808 	/*
809 	 * This does not change the actual hardware registers. It just
810 	 * resets the memory image and sets TIF_NEED_FPU_LOAD so a
811 	 * subsequent return to usermode will reload the registers from the
812 	 * task's memory image.
813 	 *
814 	 * Do not use fpstate_init() here. Just copy init_fpstate which has
815 	 * the correct content already except for PKRU.
816 	 *
817 	 * PKRU handling does not rely on the xstate when restoring for
818 	 * user space as PKRU is eagerly written in switch_to() and
819 	 * flush_thread().
820 	 */
821 	memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size());
822 	set_thread_flag(TIF_NEED_FPU_LOAD);
823 	fpregs_unlock();
824 }
825 
826 /*
827  * Reset current's user FPU states to the init states.  current's
828  * supervisor states, if any, are not modified by this function.  The
829  * caller guarantees that the XSTATE header in memory is intact.
830  */
831 void fpu__clear_user_states(struct fpu *fpu)
832 {
833 	WARN_ON_FPU(fpu != x86_task_fpu(current));
834 
835 	fpregs_lock();
836 	if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
837 		fpu_reset_fpstate_regs();
838 		fpregs_unlock();
839 		return;
840 	}
841 
842 	/*
843 	 * Ensure that current's supervisor states are loaded into their
844 	 * corresponding registers.
845 	 */
846 	if (xfeatures_mask_supervisor() &&
847 	    !fpregs_state_valid(fpu, smp_processor_id()))
848 		os_xrstor_supervisor(fpu->fpstate);
849 
850 	/* Ensure XFD state is in sync before reloading XSTATE */
851 	xfd_update_state(fpu->fpstate);
852 
853 	/* Reset user states in registers. */
854 	restore_fpregs_from_init_fpstate(XFEATURE_MASK_USER_RESTORE);
855 
856 	/*
857 	 * Now all FPU registers have their desired values.  Inform the FPU
858 	 * state machine that current's FPU registers are in the hardware
859 	 * registers. The memory image does not need to be updated because
860 	 * any operation relying on it has to save the registers first when
861 	 * current's FPU is marked active.
862 	 */
863 	fpregs_mark_activate();
864 	fpregs_unlock();
865 }
866 
867 void fpu_flush_thread(void)
868 {
869 	fpstate_reset(x86_task_fpu(current));
870 	fpu_reset_fpstate_regs();
871 }
872 /*
873  * Load FPU context before returning to userspace.
874  */
875 void switch_fpu_return(void)
876 {
877 	if (!static_cpu_has(X86_FEATURE_FPU))
878 		return;
879 
880 	fpregs_restore_userregs();
881 }
882 EXPORT_SYMBOL_FOR_KVM(switch_fpu_return);
883 
884 void fpregs_lock_and_load(void)
885 {
886 	/*
887 	 * fpregs_lock() only disables preemption (mostly). So modifying state
888 	 * in an interrupt could screw up some in progress fpregs operation.
889 	 * Warn about it.
890 	 */
891 	WARN_ON_ONCE(!irq_fpu_usable());
892 	WARN_ON_ONCE(current->flags & PF_KTHREAD);
893 
894 	fpregs_lock();
895 
896 	fpregs_assert_state_consistent();
897 
898 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
899 		fpregs_restore_userregs();
900 }
901 
902 #ifdef CONFIG_X86_DEBUG_FPU
903 /*
904  * If current FPU state according to its tracking (loaded FPU context on this
905  * CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is
906  * loaded on return to userland.
907  */
908 void fpregs_assert_state_consistent(void)
909 {
910 	struct fpu *fpu = x86_task_fpu(current);
911 
912 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
913 		return;
914 
915 	WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));
916 }
917 EXPORT_SYMBOL_FOR_KVM(fpregs_assert_state_consistent);
918 #endif
919 
920 void fpregs_mark_activate(void)
921 {
922 	struct fpu *fpu = x86_task_fpu(current);
923 
924 	fpregs_activate(fpu);
925 	fpu->last_cpu = smp_processor_id();
926 	clear_thread_flag(TIF_NEED_FPU_LOAD);
927 }
928 
929 /*
930  * x87 math exception handling:
931  */
932 
933 int fpu__exception_code(struct fpu *fpu, int trap_nr)
934 {
935 	int err;
936 
937 	if (trap_nr == X86_TRAP_MF) {
938 		unsigned short cwd, swd;
939 		/*
940 		 * (~cwd & swd) will mask out exceptions that are not set to unmasked
941 		 * status.  0x3f is the exception bits in these regs, 0x200 is the
942 		 * C1 reg you need in case of a stack fault, 0x040 is the stack
943 		 * fault bit.  We should only be taking one exception at a time,
944 		 * so if this combination doesn't produce any single exception,
945 		 * then we have a bad program that isn't synchronizing its FPU usage
946 		 * and it will suffer the consequences since we won't be able to
947 		 * fully reproduce the context of the exception.
948 		 */
949 		if (boot_cpu_has(X86_FEATURE_FXSR)) {
950 			cwd = fpu->fpstate->regs.fxsave.cwd;
951 			swd = fpu->fpstate->regs.fxsave.swd;
952 		} else {
953 			cwd = (unsigned short)fpu->fpstate->regs.fsave.cwd;
954 			swd = (unsigned short)fpu->fpstate->regs.fsave.swd;
955 		}
956 
957 		err = swd & ~cwd;
958 	} else {
959 		/*
960 		 * The SIMD FPU exceptions are handled a little differently, as there
961 		 * is only a single status/control register.  Thus, to determine which
962 		 * unmasked exception was caught we must mask the exception mask bits
963 		 * at 0x1f80, and then use these to mask the exception bits at 0x3f.
964 		 */
965 		unsigned short mxcsr = MXCSR_DEFAULT;
966 
967 		if (boot_cpu_has(X86_FEATURE_XMM))
968 			mxcsr = fpu->fpstate->regs.fxsave.mxcsr;
969 
970 		err = ~(mxcsr >> 7) & mxcsr;
971 	}
972 
973 	if (err & 0x001) {	/* Invalid op */
974 		/*
975 		 * swd & 0x240 == 0x040: Stack Underflow
976 		 * swd & 0x240 == 0x240: Stack Overflow
977 		 * User must clear the SF bit (0x40) if set
978 		 */
979 		return FPE_FLTINV;
980 	} else if (err & 0x004) { /* Divide by Zero */
981 		return FPE_FLTDIV;
982 	} else if (err & 0x008) { /* Overflow */
983 		return FPE_FLTOVF;
984 	} else if (err & 0x012) { /* Denormal, Underflow */
985 		return FPE_FLTUND;
986 	} else if (err & 0x020) { /* Precision */
987 		return FPE_FLTRES;
988 	}
989 
990 	/*
991 	 * If we're using IRQ 13, or supposedly even some trap
992 	 * X86_TRAP_MF implementations, it's possible
993 	 * we get a spurious trap, which is not an error.
994 	 */
995 	return 0;
996 }
997 
998 /*
999  * Initialize register state that may prevent from entering low-power idle.
1000  * This function will be invoked from the cpuidle driver only when needed.
1001  */
1002 noinstr void fpu_idle_fpregs(void)
1003 {
1004 	/* Note: AMX_TILE being enabled implies XGETBV1 support */
1005 	if (cpu_feature_enabled(X86_FEATURE_AMX_TILE) &&
1006 	    (xfeatures_in_use() & XFEATURE_MASK_XTILE)) {
1007 		tile_release();
1008 		__this_cpu_write(fpu_fpregs_owner_ctx, NULL);
1009 	}
1010 }
1011