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