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