xref: /linux/arch/x86/kernel/fpu/core.c (revision 7fc2cd2e4b398c57c9cf961cfea05eadbf34c05c)
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 	fpregs_lock();
323 	guest_fpu->fpstate->xfd = xfd;
324 	if (guest_fpu->fpstate->in_use)
325 		xfd_update_state(guest_fpu->fpstate);
326 	fpregs_unlock();
327 }
328 EXPORT_SYMBOL_FOR_KVM(fpu_update_guest_xfd);
329 
330 /**
331  * fpu_sync_guest_vmexit_xfd_state - Synchronize XFD MSR and software state
332  *
333  * Must be invoked from KVM after a VMEXIT before enabling interrupts when
334  * XFD write emulation is disabled. This is required because the guest can
335  * freely modify XFD and the state at VMEXIT is not guaranteed to be the
336  * same as the state on VMENTER. So software state has to be updated before
337  * any operation which depends on it can take place.
338  *
339  * Note: It can be invoked unconditionally even when write emulation is
340  * enabled for the price of a then pointless MSR read.
341  */
342 void fpu_sync_guest_vmexit_xfd_state(void)
343 {
344 	struct fpstate *fpstate = x86_task_fpu(current)->fpstate;
345 
346 	lockdep_assert_irqs_disabled();
347 	if (fpu_state_size_dynamic()) {
348 		rdmsrq(MSR_IA32_XFD, fpstate->xfd);
349 		__this_cpu_write(xfd_state, fpstate->xfd);
350 	}
351 }
352 EXPORT_SYMBOL_FOR_KVM(fpu_sync_guest_vmexit_xfd_state);
353 #endif /* CONFIG_X86_64 */
354 
355 int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest)
356 {
357 	struct fpstate *guest_fps = guest_fpu->fpstate;
358 	struct fpu *fpu = x86_task_fpu(current);
359 	struct fpstate *cur_fps = fpu->fpstate;
360 
361 	fpregs_lock();
362 	if (!cur_fps->is_confidential && !test_thread_flag(TIF_NEED_FPU_LOAD))
363 		save_fpregs_to_fpstate(fpu);
364 
365 	/* Swap fpstate */
366 	if (enter_guest) {
367 		fpu->__task_fpstate = cur_fps;
368 		fpu->fpstate = guest_fps;
369 		guest_fps->in_use = true;
370 	} else {
371 		guest_fps->in_use = false;
372 		fpu->fpstate = fpu->__task_fpstate;
373 		fpu->__task_fpstate = NULL;
374 	}
375 
376 	cur_fps = fpu->fpstate;
377 
378 	if (!cur_fps->is_confidential) {
379 		/* Includes XFD update */
380 		restore_fpregs_from_fpstate(cur_fps, XFEATURE_MASK_FPSTATE);
381 	} else {
382 		/*
383 		 * XSTATE is restored by firmware from encrypted
384 		 * memory. Make sure XFD state is correct while
385 		 * running with guest fpstate
386 		 */
387 		xfd_update_state(cur_fps);
388 	}
389 
390 	fpregs_mark_activate();
391 	fpregs_unlock();
392 	return 0;
393 }
394 EXPORT_SYMBOL_FOR_KVM(fpu_swap_kvm_fpstate);
395 
396 void fpu_copy_guest_fpstate_to_uabi(struct fpu_guest *gfpu, void *buf,
397 				    unsigned int size, u64 xfeatures, u32 pkru)
398 {
399 	struct fpstate *kstate = gfpu->fpstate;
400 	union fpregs_state *ustate = buf;
401 	struct membuf mb = { .p = buf, .left = size };
402 
403 	if (cpu_feature_enabled(X86_FEATURE_XSAVE)) {
404 		__copy_xstate_to_uabi_buf(mb, kstate, xfeatures, pkru,
405 					  XSTATE_COPY_XSAVE);
406 	} else {
407 		memcpy(&ustate->fxsave, &kstate->regs.fxsave,
408 		       sizeof(ustate->fxsave));
409 		/* Make it restorable on a XSAVE enabled host */
410 		ustate->xsave.header.xfeatures = XFEATURE_MASK_FPSSE;
411 	}
412 }
413 EXPORT_SYMBOL_FOR_KVM(fpu_copy_guest_fpstate_to_uabi);
414 
415 int fpu_copy_uabi_to_guest_fpstate(struct fpu_guest *gfpu, const void *buf,
416 				   u64 xcr0, u32 *vpkru)
417 {
418 	struct fpstate *kstate = gfpu->fpstate;
419 	const union fpregs_state *ustate = buf;
420 
421 	if (!cpu_feature_enabled(X86_FEATURE_XSAVE)) {
422 		if (ustate->xsave.header.xfeatures & ~XFEATURE_MASK_FPSSE)
423 			return -EINVAL;
424 		if (ustate->fxsave.mxcsr & ~mxcsr_feature_mask)
425 			return -EINVAL;
426 		memcpy(&kstate->regs.fxsave, &ustate->fxsave, sizeof(ustate->fxsave));
427 		return 0;
428 	}
429 
430 	if (ustate->xsave.header.xfeatures & ~xcr0)
431 		return -EINVAL;
432 
433 	/*
434 	 * Nullify @vpkru to preserve its current value if PKRU's bit isn't set
435 	 * in the header.  KVM's odd ABI is to leave PKRU untouched in this
436 	 * case (all other components are eventually re-initialized).
437 	 */
438 	if (!(ustate->xsave.header.xfeatures & XFEATURE_MASK_PKRU))
439 		vpkru = NULL;
440 
441 	return copy_uabi_from_kernel_to_xstate(kstate, ustate, vpkru);
442 }
443 EXPORT_SYMBOL_FOR_KVM(fpu_copy_uabi_to_guest_fpstate);
444 #endif /* CONFIG_KVM */
445 
446 void kernel_fpu_begin_mask(unsigned int kfpu_mask)
447 {
448 	if (!irqs_disabled())
449 		fpregs_lock();
450 
451 	WARN_ON_FPU(!irq_fpu_usable());
452 
453 	/* Toggle kernel_fpu_allowed to false: */
454 	WARN_ON_FPU(!this_cpu_read(kernel_fpu_allowed));
455 	this_cpu_write(kernel_fpu_allowed, false);
456 
457 	if (!(current->flags & (PF_KTHREAD | PF_USER_WORKER)) &&
458 	    !test_thread_flag(TIF_NEED_FPU_LOAD)) {
459 		set_thread_flag(TIF_NEED_FPU_LOAD);
460 		save_fpregs_to_fpstate(x86_task_fpu(current));
461 	}
462 	__cpu_invalidate_fpregs_state();
463 
464 	/* Put sane initial values into the control registers. */
465 	if (likely(kfpu_mask & KFPU_MXCSR) && boot_cpu_has(X86_FEATURE_XMM))
466 		ldmxcsr(MXCSR_DEFAULT);
467 
468 	if (unlikely(kfpu_mask & KFPU_387) && boot_cpu_has(X86_FEATURE_FPU))
469 		asm volatile ("fninit");
470 }
471 EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);
472 
473 void kernel_fpu_end(void)
474 {
475 	/* Toggle kernel_fpu_allowed back to true: */
476 	WARN_ON_FPU(this_cpu_read(kernel_fpu_allowed));
477 	this_cpu_write(kernel_fpu_allowed, true);
478 
479 	if (!irqs_disabled())
480 		fpregs_unlock();
481 }
482 EXPORT_SYMBOL_GPL(kernel_fpu_end);
483 
484 /*
485  * Sync the FPU register state to current's memory register state when the
486  * current task owns the FPU. The hardware register state is preserved.
487  */
488 void fpu_sync_fpstate(struct fpu *fpu)
489 {
490 	WARN_ON_FPU(fpu != x86_task_fpu(current));
491 
492 	fpregs_lock();
493 	trace_x86_fpu_before_save(fpu);
494 
495 	if (!test_thread_flag(TIF_NEED_FPU_LOAD))
496 		save_fpregs_to_fpstate(fpu);
497 
498 	trace_x86_fpu_after_save(fpu);
499 	fpregs_unlock();
500 }
501 
502 static inline unsigned int init_fpstate_copy_size(void)
503 {
504 	if (!use_xsave())
505 		return fpu_kernel_cfg.default_size;
506 
507 	/* XSAVE(S) just needs the legacy and the xstate header part */
508 	return sizeof(init_fpstate.regs.xsave);
509 }
510 
511 static inline void fpstate_init_fxstate(struct fpstate *fpstate)
512 {
513 	fpstate->regs.fxsave.cwd = 0x37f;
514 	fpstate->regs.fxsave.mxcsr = MXCSR_DEFAULT;
515 }
516 
517 /*
518  * Legacy x87 fpstate state init:
519  */
520 static inline void fpstate_init_fstate(struct fpstate *fpstate)
521 {
522 	fpstate->regs.fsave.cwd = 0xffff037fu;
523 	fpstate->regs.fsave.swd = 0xffff0000u;
524 	fpstate->regs.fsave.twd = 0xffffffffu;
525 	fpstate->regs.fsave.fos = 0xffff0000u;
526 }
527 
528 /*
529  * Used in two places:
530  * 1) Early boot to setup init_fpstate for non XSAVE systems
531  * 2) fpu_alloc_guest_fpstate() which is invoked from KVM
532  */
533 void fpstate_init_user(struct fpstate *fpstate)
534 {
535 	if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
536 		fpstate_init_soft(&fpstate->regs.soft);
537 		return;
538 	}
539 
540 	xstate_init_xcomp_bv(&fpstate->regs.xsave, fpstate->xfeatures);
541 
542 	if (cpu_feature_enabled(X86_FEATURE_FXSR))
543 		fpstate_init_fxstate(fpstate);
544 	else
545 		fpstate_init_fstate(fpstate);
546 }
547 
548 static void __fpstate_reset(struct fpstate *fpstate)
549 {
550 	/*
551 	 * Supervisor features (and thus sizes) may diverge between guest
552 	 * FPUs and host FPUs, as some supervisor features are supported
553 	 * for guests despite not being utilized by the host. User
554 	 * features and sizes are always identical, which allows for
555 	 * common guest and userspace ABI.
556 	 *
557 	 * For the host, set XFD to the kernel's desired initialization
558 	 * value. For guests, set XFD to its architectural RESET value.
559 	 */
560 	if (fpstate->is_guest) {
561 		fpstate->size		= guest_default_cfg.size;
562 		fpstate->xfeatures	= guest_default_cfg.features;
563 		fpstate->xfd		= 0;
564 	} else {
565 		fpstate->size		= fpu_kernel_cfg.default_size;
566 		fpstate->xfeatures	= fpu_kernel_cfg.default_features;
567 		fpstate->xfd		= init_fpstate.xfd;
568 	}
569 
570 	fpstate->user_size	= fpu_user_cfg.default_size;
571 	fpstate->user_xfeatures	= fpu_user_cfg.default_features;
572 }
573 
574 void fpstate_reset(struct fpu *fpu)
575 {
576 	/* Set the fpstate pointer to the default fpstate */
577 	fpu->fpstate = &fpu->__fpstate;
578 	__fpstate_reset(fpu->fpstate);
579 
580 	/* Initialize the permission related info in fpu */
581 	fpu->perm.__state_perm		= fpu_kernel_cfg.default_features;
582 	fpu->perm.__state_size		= fpu_kernel_cfg.default_size;
583 	fpu->perm.__user_state_size	= fpu_user_cfg.default_size;
584 
585 	fpu->guest_perm.__state_perm	= guest_default_cfg.features;
586 	fpu->guest_perm.__state_size	= guest_default_cfg.size;
587 	/*
588 	 * User features and sizes are always identical between host and
589 	 * guest FPUs, which allows for common guest and userspace ABI.
590 	 */
591 	fpu->guest_perm.__user_state_size = fpu_user_cfg.default_size;
592 }
593 
594 static inline void fpu_inherit_perms(struct fpu *dst_fpu)
595 {
596 	if (fpu_state_size_dynamic()) {
597 		struct fpu *src_fpu = x86_task_fpu(current->group_leader);
598 
599 		spin_lock_irq(&current->sighand->siglock);
600 		/* Fork also inherits the permissions of the parent */
601 		dst_fpu->perm = src_fpu->perm;
602 		dst_fpu->guest_perm = src_fpu->guest_perm;
603 		spin_unlock_irq(&current->sighand->siglock);
604 	}
605 }
606 
607 /* A passed ssp of zero will not cause any update */
608 static int update_fpu_shstk(struct task_struct *dst, unsigned long ssp)
609 {
610 #ifdef CONFIG_X86_USER_SHADOW_STACK
611 	struct cet_user_state *xstate;
612 
613 	/* If ssp update is not needed. */
614 	if (!ssp)
615 		return 0;
616 
617 	xstate = get_xsave_addr(&x86_task_fpu(dst)->fpstate->regs.xsave,
618 				XFEATURE_CET_USER);
619 
620 	/*
621 	 * If there is a non-zero ssp, then 'dst' must be configured with a shadow
622 	 * stack and the fpu state should be up to date since it was just copied
623 	 * from the parent in fpu_clone(). So there must be a valid non-init CET
624 	 * state location in the buffer.
625 	 */
626 	if (WARN_ON_ONCE(!xstate))
627 		return 1;
628 
629 	xstate->user_ssp = (u64)ssp;
630 #endif
631 	return 0;
632 }
633 
634 /* Clone current's FPU state on fork */
635 int fpu_clone(struct task_struct *dst, u64 clone_flags, bool minimal,
636 	      unsigned long ssp)
637 {
638 	/*
639 	 * We allocate the new FPU structure right after the end of the task struct.
640 	 * task allocation size already took this into account.
641 	 *
642 	 * This is safe because task_struct size is a multiple of cacheline size,
643 	 * thus x86_task_fpu() will always be cacheline aligned as well.
644 	 */
645 	struct fpu *dst_fpu = (void *)dst + sizeof(*dst);
646 
647 	BUILD_BUG_ON(sizeof(*dst) % SMP_CACHE_BYTES != 0);
648 
649 	/* The new task's FPU state cannot be valid in the hardware. */
650 	dst_fpu->last_cpu = -1;
651 
652 	fpstate_reset(dst_fpu);
653 
654 	if (!cpu_feature_enabled(X86_FEATURE_FPU))
655 		return 0;
656 
657 	/*
658 	 * Enforce reload for user space tasks and prevent kernel threads
659 	 * from trying to save the FPU registers on context switch.
660 	 */
661 	set_tsk_thread_flag(dst, TIF_NEED_FPU_LOAD);
662 
663 	/*
664 	 * No FPU state inheritance for kernel threads and IO
665 	 * worker threads.
666 	 */
667 	if (minimal) {
668 		/* Clear out the minimal state */
669 		memcpy(&dst_fpu->fpstate->regs, &init_fpstate.regs,
670 		       init_fpstate_copy_size());
671 		return 0;
672 	}
673 
674 	/*
675 	 * If a new feature is added, ensure all dynamic features are
676 	 * caller-saved from here!
677 	 */
678 	BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);
679 
680 	/*
681 	 * Save the default portion of the current FPU state into the
682 	 * clone. Assume all dynamic features to be defined as caller-
683 	 * saved, which enables skipping both the expansion of fpstate
684 	 * and the copying of any dynamic state.
685 	 *
686 	 * Do not use memcpy() when TIF_NEED_FPU_LOAD is set because
687 	 * copying is not valid when current uses non-default states.
688 	 */
689 	fpregs_lock();
690 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
691 		fpregs_restore_userregs();
692 	save_fpregs_to_fpstate(dst_fpu);
693 	fpregs_unlock();
694 	if (!(clone_flags & CLONE_THREAD))
695 		fpu_inherit_perms(dst_fpu);
696 
697 	/*
698 	 * Children never inherit PASID state.
699 	 * Force it to have its init value:
700 	 */
701 	if (use_xsave())
702 		dst_fpu->fpstate->regs.xsave.header.xfeatures &= ~XFEATURE_MASK_PASID;
703 
704 	/*
705 	 * Update shadow stack pointer, in case it changed during clone.
706 	 */
707 	if (update_fpu_shstk(dst, ssp))
708 		return 1;
709 
710 	trace_x86_fpu_copy_dst(dst_fpu);
711 
712 	return 0;
713 }
714 
715 /*
716  * While struct fpu is no longer part of struct thread_struct, it is still
717  * allocated after struct task_struct in the "task_struct" kmem cache. But
718  * since FPU is expected to be part of struct thread_struct, we have to
719  * adjust for it here.
720  */
721 void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size)
722 {
723 	/* The allocation follows struct task_struct. */
724 	*offset = sizeof(struct task_struct) - offsetof(struct task_struct, thread);
725 	*offset += offsetof(struct fpu, __fpstate.regs);
726 	*size = fpu_kernel_cfg.default_size;
727 }
728 
729 /*
730  * Drops current FPU state: deactivates the fpregs and
731  * the fpstate. NOTE: it still leaves previous contents
732  * in the fpregs in the eager-FPU case.
733  *
734  * This function can be used in cases where we know that
735  * a state-restore is coming: either an explicit one,
736  * or a reschedule.
737  */
738 void fpu__drop(struct task_struct *tsk)
739 {
740 	struct fpu *fpu;
741 
742 	if (test_tsk_thread_flag(tsk, TIF_NEED_FPU_LOAD))
743 		return;
744 
745 	fpu = x86_task_fpu(tsk);
746 
747 	preempt_disable();
748 
749 	if (fpu == x86_task_fpu(current)) {
750 		/* Ignore delayed exceptions from user space */
751 		asm volatile("1: fwait\n"
752 			     "2:\n"
753 			     _ASM_EXTABLE(1b, 2b));
754 		fpregs_deactivate(fpu);
755 	}
756 
757 	trace_x86_fpu_dropped(fpu);
758 
759 	preempt_enable();
760 }
761 
762 /*
763  * Clear FPU registers by setting them up from the init fpstate.
764  * Caller must do fpregs_[un]lock() around it.
765  */
766 static inline void restore_fpregs_from_init_fpstate(u64 features_mask)
767 {
768 	if (use_xsave())
769 		os_xrstor(&init_fpstate, features_mask);
770 	else if (use_fxsr())
771 		fxrstor(&init_fpstate.regs.fxsave);
772 	else
773 		frstor(&init_fpstate.regs.fsave);
774 
775 	pkru_write_default();
776 }
777 
778 /*
779  * Reset current->fpu memory state to the init values.
780  */
781 static void fpu_reset_fpstate_regs(void)
782 {
783 	struct fpu *fpu = x86_task_fpu(current);
784 
785 	fpregs_lock();
786 	__fpu_invalidate_fpregs_state(fpu);
787 	/*
788 	 * This does not change the actual hardware registers. It just
789 	 * resets the memory image and sets TIF_NEED_FPU_LOAD so a
790 	 * subsequent return to usermode will reload the registers from the
791 	 * task's memory image.
792 	 *
793 	 * Do not use fpstate_init() here. Just copy init_fpstate which has
794 	 * the correct content already except for PKRU.
795 	 *
796 	 * PKRU handling does not rely on the xstate when restoring for
797 	 * user space as PKRU is eagerly written in switch_to() and
798 	 * flush_thread().
799 	 */
800 	memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size());
801 	set_thread_flag(TIF_NEED_FPU_LOAD);
802 	fpregs_unlock();
803 }
804 
805 /*
806  * Reset current's user FPU states to the init states.  current's
807  * supervisor states, if any, are not modified by this function.  The
808  * caller guarantees that the XSTATE header in memory is intact.
809  */
810 void fpu__clear_user_states(struct fpu *fpu)
811 {
812 	WARN_ON_FPU(fpu != x86_task_fpu(current));
813 
814 	fpregs_lock();
815 	if (!cpu_feature_enabled(X86_FEATURE_FPU)) {
816 		fpu_reset_fpstate_regs();
817 		fpregs_unlock();
818 		return;
819 	}
820 
821 	/*
822 	 * Ensure that current's supervisor states are loaded into their
823 	 * corresponding registers.
824 	 */
825 	if (xfeatures_mask_supervisor() &&
826 	    !fpregs_state_valid(fpu, smp_processor_id()))
827 		os_xrstor_supervisor(fpu->fpstate);
828 
829 	/* Ensure XFD state is in sync before reloading XSTATE */
830 	xfd_update_state(fpu->fpstate);
831 
832 	/* Reset user states in registers. */
833 	restore_fpregs_from_init_fpstate(XFEATURE_MASK_USER_RESTORE);
834 
835 	/*
836 	 * Now all FPU registers have their desired values.  Inform the FPU
837 	 * state machine that current's FPU registers are in the hardware
838 	 * registers. The memory image does not need to be updated because
839 	 * any operation relying on it has to save the registers first when
840 	 * current's FPU is marked active.
841 	 */
842 	fpregs_mark_activate();
843 	fpregs_unlock();
844 }
845 
846 void fpu_flush_thread(void)
847 {
848 	fpstate_reset(x86_task_fpu(current));
849 	fpu_reset_fpstate_regs();
850 }
851 /*
852  * Load FPU context before returning to userspace.
853  */
854 void switch_fpu_return(void)
855 {
856 	if (!static_cpu_has(X86_FEATURE_FPU))
857 		return;
858 
859 	fpregs_restore_userregs();
860 }
861 EXPORT_SYMBOL_FOR_KVM(switch_fpu_return);
862 
863 void fpregs_lock_and_load(void)
864 {
865 	/*
866 	 * fpregs_lock() only disables preemption (mostly). So modifying state
867 	 * in an interrupt could screw up some in progress fpregs operation.
868 	 * Warn about it.
869 	 */
870 	WARN_ON_ONCE(!irq_fpu_usable());
871 	WARN_ON_ONCE(current->flags & PF_KTHREAD);
872 
873 	fpregs_lock();
874 
875 	fpregs_assert_state_consistent();
876 
877 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
878 		fpregs_restore_userregs();
879 }
880 
881 #ifdef CONFIG_X86_DEBUG_FPU
882 /*
883  * If current FPU state according to its tracking (loaded FPU context on this
884  * CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is
885  * loaded on return to userland.
886  */
887 void fpregs_assert_state_consistent(void)
888 {
889 	struct fpu *fpu = x86_task_fpu(current);
890 
891 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
892 		return;
893 
894 	WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));
895 }
896 EXPORT_SYMBOL_FOR_KVM(fpregs_assert_state_consistent);
897 #endif
898 
899 void fpregs_mark_activate(void)
900 {
901 	struct fpu *fpu = x86_task_fpu(current);
902 
903 	fpregs_activate(fpu);
904 	fpu->last_cpu = smp_processor_id();
905 	clear_thread_flag(TIF_NEED_FPU_LOAD);
906 }
907 
908 /*
909  * x87 math exception handling:
910  */
911 
912 int fpu__exception_code(struct fpu *fpu, int trap_nr)
913 {
914 	int err;
915 
916 	if (trap_nr == X86_TRAP_MF) {
917 		unsigned short cwd, swd;
918 		/*
919 		 * (~cwd & swd) will mask out exceptions that are not set to unmasked
920 		 * status.  0x3f is the exception bits in these regs, 0x200 is the
921 		 * C1 reg you need in case of a stack fault, 0x040 is the stack
922 		 * fault bit.  We should only be taking one exception at a time,
923 		 * so if this combination doesn't produce any single exception,
924 		 * then we have a bad program that isn't synchronizing its FPU usage
925 		 * and it will suffer the consequences since we won't be able to
926 		 * fully reproduce the context of the exception.
927 		 */
928 		if (boot_cpu_has(X86_FEATURE_FXSR)) {
929 			cwd = fpu->fpstate->regs.fxsave.cwd;
930 			swd = fpu->fpstate->regs.fxsave.swd;
931 		} else {
932 			cwd = (unsigned short)fpu->fpstate->regs.fsave.cwd;
933 			swd = (unsigned short)fpu->fpstate->regs.fsave.swd;
934 		}
935 
936 		err = swd & ~cwd;
937 	} else {
938 		/*
939 		 * The SIMD FPU exceptions are handled a little differently, as there
940 		 * is only a single status/control register.  Thus, to determine which
941 		 * unmasked exception was caught we must mask the exception mask bits
942 		 * at 0x1f80, and then use these to mask the exception bits at 0x3f.
943 		 */
944 		unsigned short mxcsr = MXCSR_DEFAULT;
945 
946 		if (boot_cpu_has(X86_FEATURE_XMM))
947 			mxcsr = fpu->fpstate->regs.fxsave.mxcsr;
948 
949 		err = ~(mxcsr >> 7) & mxcsr;
950 	}
951 
952 	if (err & 0x001) {	/* Invalid op */
953 		/*
954 		 * swd & 0x240 == 0x040: Stack Underflow
955 		 * swd & 0x240 == 0x240: Stack Overflow
956 		 * User must clear the SF bit (0x40) if set
957 		 */
958 		return FPE_FLTINV;
959 	} else if (err & 0x004) { /* Divide by Zero */
960 		return FPE_FLTDIV;
961 	} else if (err & 0x008) { /* Overflow */
962 		return FPE_FLTOVF;
963 	} else if (err & 0x012) { /* Denormal, Underflow */
964 		return FPE_FLTUND;
965 	} else if (err & 0x020) { /* Precision */
966 		return FPE_FLTRES;
967 	}
968 
969 	/*
970 	 * If we're using IRQ 13, or supposedly even some trap
971 	 * X86_TRAP_MF implementations, it's possible
972 	 * we get a spurious trap, which is not an error.
973 	 */
974 	return 0;
975 }
976 
977 /*
978  * Initialize register state that may prevent from entering low-power idle.
979  * This function will be invoked from the cpuidle driver only when needed.
980  */
981 noinstr void fpu_idle_fpregs(void)
982 {
983 	/* Note: AMX_TILE being enabled implies XGETBV1 support */
984 	if (cpu_feature_enabled(X86_FEATURE_AMX_TILE) &&
985 	    (xfeatures_in_use() & XFEATURE_MASK_XTILE)) {
986 		tile_release();
987 		__this_cpu_write(fpu_fpregs_owner_ctx, NULL);
988 	}
989 }
990